: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
chore(queries): delete the dead legacy SQL-builder chain (#91453)
Sandy Spicer23953d6b1c4e
diff --git a/ee/clickhouse/models/test/__snapshots__/test_cohort.ambr b/ee/clickhouse/models/test/__snapshots__/test_cohort.ambrindex cef97d8e9187..400e47b9b4b4 100644--- a/ee/clickhouse/models/test/__snapshots__/test_cohort.ambr+++ b/ee/clickhouse/models/test/__snapshots__/test_cohort.ambr@@ -222,49 +222,6 @@join_algorithm = 'auto''''# ----# name: TestCohort.test_cohortpeople_with_not_in_cohort_operator_and_no_precalculation- '''- SELECT uuid,- distinct_id- FROM events- WHERE team_id = 99999- AND (distinct_id IN- (SELECT distinct_id- FROM- (SELECT person_distinct_ids.distinct_id AS distinct_id- FROM- (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id,- person_distinct_id2.distinct_id AS distinct_id- FROM person_distinct_id2- WHERE equals(person_distinct_id2.team_id, 99999)- GROUP BY person_distinct_id2.distinct_id- HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids- WHERE globalIn(person_distinct_ids.person_id, ((- (SELECT source.id AS id- FROM- (SELECT actor_id AS actor_id, count() AS event_count, groupUniqArray(distinct_id) AS event_distinct_ids, max(timestamp) AS last_seen, actor_id AS id- FROM- (SELECT if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS actor_id, toTimeZone(e.timestamp, 'UTC') AS timestamp, e.uuid AS uuid, e.distinct_id AS distinct_id- FROM events AS e- LEFT OUTER JOIN- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id- FROM person_distinct_id_overrides- WHERE equals(person_distinct_id_overrides.team_id, 99999)- GROUP BY person_distinct_id_overrides.distinct_id- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)- WHERE and(equals(e.team_id, 99999), greaterOrEquals(timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(timestamp, toDateTime64('today', 6, 'UTC')), equals(e.event, '$pageview')))- GROUP BY actor_id) AS source- ORDER BY source.id ASC SETTINGS optimize_aggregation_in_order=1, join_algorithm='auto'))- EXCEPT (- (SELECT cohort_people.person_id AS id- FROM- (SELECT DISTINCT cohortpeople.person_id AS person_id, cohortpeople.cohort_id AS cohort_id, cohortpeople.team_id AS team_id- FROM cohortpeople- WHERE 0) AS cohort_people- WHERE and(equals(cohort_people.cohort_id, 99999), equals(cohort_people.team_id, 99999))))))- LIMIT 1000000000)))- '''-# ---# name: TestCohort.test_cohortpeople_with_not_in_cohort_operator_for_behavioural_cohorts'''/* cohort_calculation:cohort_calc:00000000 */@@ -441,22 +398,3 @@join_algorithm = 'auto''''# ----# name: TestCohort.test_static_cohort_precalculated- '''- SELECT distinct_id- FROM- (SELECT person_distinct_ids.distinct_id AS distinct_id- FROM- (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id,- person_distinct_id2.distinct_id AS distinct_id- FROM person_distinct_id2- WHERE equals(person_distinct_id2.team_id, 99999)- GROUP BY person_distinct_id2.distinct_id- HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids- WHERE in(person_distinct_ids.person_id,- (SELECT person_static_cohort.person_id AS person_id- FROM person_static_cohort- WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999))))- LIMIT 1000000000)- '''-# ---diff --git a/ee/clickhouse/models/test/__snapshots__/test_property.ambr b/ee/clickhouse/models/test/__snapshots__/test_property.ambrdeleted file mode 100644index d7ba09fdadf5..000000000000--- a/ee/clickhouse/models/test/__snapshots__/test_property.ambr+++ /dev/null@@ -1,155 +0,0 @@-# serializer version: 1-# name: TestPropFormat.test_parse_groups- '''- SELECT uuid- FROM events- WHERE team_id = 99999- AND ((has(['val_1'], replaceRegexpAll(JSONExtractRaw(properties, 'attr_1'), '^"|"$', ''))- AND has(['val_2'], replaceRegexpAll(JSONExtractRaw(properties, 'attr_2'), '^"|"$', '')))- OR (has(['val_2'], replaceRegexpAll(JSONExtractRaw(properties, 'attr_1'), '^"|"$', ''))))- '''-# ----# name: TestPropFormat.test_parse_groups_persons- '''- SELECT uuid- FROM events- WHERE team_id = 99999- AND ((distinct_id IN- (SELECT distinct_id- FROM- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0)- WHERE person_id IN- (SELECT id- FROM- (SELECT id,- argMax(properties, person._timestamp) as properties,- max(is_deleted) as is_deleted- FROM person- WHERE team_id = 99999- GROUP BY id- HAVING is_deleted = 0)- WHERE has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '')))))- OR (distinct_id IN- (SELECT distinct_id- FROM- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0)- WHERE person_id IN- (SELECT id- FROM- (SELECT id,- argMax(properties, person._timestamp) as properties,- max(is_deleted) as is_deleted- FROM person- WHERE team_id = 99999- GROUP BY id- HAVING is_deleted = 0)- WHERE has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', ''))))))- '''-# ----# name: test_parse_groups_persons_edge_case_with_single_filter- tuple(- 'AND ( has(%(vglobalperson_0)s, replaceRegexpAll(JSONExtractRaw(person_props, %(kglobalperson_0)s), \'^"|"$\', \'\')))',- dict({- 'kglobalperson_0': 'email',- 'vglobalperson_0': list([- '[email protected]',- ]),- }),- )-# ----# name: test_parse_prop_clauses_defaults- tuple(- '''- AND ( has(%(vglobal_0)s, replaceRegexpAll(JSONExtractRaw(properties, %(kglobal_0)s), '^"|"$', '')) AND distinct_id IN (- SELECT distinct_id- FROM (-- SELECT distinct_id, argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = %(team_id)s-- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0-- )- WHERE person_id IN- (- SELECT id- FROM (- SELECT id, argMax(properties, person._timestamp) as properties, max(is_deleted) as is_deleted- FROM person- WHERE team_id = %(team_id)s- GROUP BY id- HAVING is_deleted = 0- )- WHERE replaceRegexpAll(JSONExtractRaw(properties, %(kglobalperson_1)s), '^"|"$', '') ILIKE %(vglobalperson_1)s- )- ))- ''',- dict({- 'kglobal_0': 'event_prop',- 'kglobalperson_1': 'email',- 'vglobal_0': list([- 'value',- ]),- 'vglobalperson_1': '%posthog%',- }),- )-# ----# name: test_parse_prop_clauses_defaults.1- tuple(- 'AND ( has(%(vglobal_0)s, replaceRegexpAll(JSONExtractRaw(properties, %(kglobal_0)s), \'^"|"$\', \'\')) AND replaceRegexpAll(JSONExtractRaw(person_props, %(kglobalperson_1)s), \'^"|"$\', \'\') ILIKE %(vglobalperson_1)s)',- dict({- 'kglobal_0': 'event_prop',- 'kglobalperson_1': 'email',- 'vglobal_0': list([- 'value',- ]),- 'vglobalperson_1': '%posthog%',- }),- )-# ----# name: test_parse_prop_clauses_defaults.2- tuple(- 'AND ( has(%(vglobal_0)s, replaceRegexpAll(JSONExtractRaw(properties, %(kglobal_0)s), \'^"|"$\', \'\')) AND replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), %(kpersonquery_global_1)s), \'^"|"$\', \'\') ILIKE %(vpersonquery_global_1)s)',- dict({- 'kglobal_0': 'event_prop',- 'kpersonquery_global_1': 'email',- 'vglobal_0': list([- 'value',- ]),- 'vpersonquery_global_1': '%posthog%',- }),- )-# ----# name: test_parse_prop_clauses_funnel_step_element_prepend_regression- tuple(- 'AND ( (match(elements_chain, %(PREPEND__text_0_attributes_regex)s)))',- dict({- 'PREPEND__text_0_attributes_regex': '(text="Insights1")',- }),- )-# ----# name: test_parse_prop_clauses_precalculated_cohort- tuple(- '''- AND ( pdi.person_id IN (- SELECT DISTINCT person_id FROM cohortpeople WHERE team_id = %(team_id)s AND cohort_id = %(global_cohort_id_0)s AND version = %(global_version_0)s- ))- ''',- dict({- 'global_cohort_id_0': 42,- 'global_version_0': None,- }),- )-# ---diff --git a/ee/clickhouse/models/test/test_action.py b/ee/clickhouse/models/test/test_action.pyindex 7ddf80dab030..cb9e7f2a6c1e 100644--- a/ee/clickhouse/models/test/test_action.py+++ b/ee/clickhouse/models/test/test_action.py@@ -1,17 +1,9 @@-import dataclasses--from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person+from posthog.test.base import BaseTestfrom posthog.hogql.compiler.bytecode import create_bytecode-from posthog.hogql.hogql import HogQLContextfrom posthog.hogql.property import action_to_expr-from posthog.clickhouse.client import sync_execute-from posthog.models.event.new_events_schema import events_read_table, use_new_events_schema-from posthog.models.test.test_event_model import filter_by_actions_factory-from products.actions.backend.models.action import Action-from products.actions.backend.models.util import filter_event, format_action_filterfrom common.hogvm.python.operation import (HOGQL_BYTECODE_IDENTIFIER as _H,@@ -20,267 +12,8 @@ from common.hogvm.python.operation import ()-class MockEvent:- uuid: str- distinct_id: str---def _get_events_for_action(action: Action) -> list[MockEvent]:- hogql_context = HogQLContext(team_id=action.team_id)- formatted_query, params = format_action_filter(- team_id=action.team_id, action=action, prepend="", hogql_context=hogql_context- )- events_table = events_read_table(hogql_context.uses_new_events_schema())- query = f"""- SELECT- events.uuid,- events.distinct_id- FROM {events_table} AS events- WHERE {formatted_query}- AND events.team_id = %(team_id)s- ORDER BY events.timestamp DESC- """- events = sync_execute(- query,- {"team_id": action.team_id, **params, **hogql_context.values},- team_id=action.team_id,- )- return [MockEvent(str(uuid), distinct_id) for uuid, distinct_id in events]---def _event_uuid_query(new_events_schema: bool) -> str:- events_table = events_read_table(new_events_schema)- return f"SELECT uuid FROM {events_table} AS events WHERE {{}} AND team_id = %(team_id)s"---class TestActions(- ClickhouseTestMixin,- filter_by_actions_factory(_create_event, _create_person, _get_events_for_action), # type: ignore-):- pass---class TestActionFormat(ClickhouseTestMixin, BaseTest):- def test_filter_event_exact_url(self):- event_target_uuid = _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- properties={"$current_url": "https://posthog.com/feedback/123"},- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="whatever",- properties={"$current_url": "https://posthog.com/feedback/123"},- )-- _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- properties={"$current_url": "https://posthog.com/feedback/1234"},- )-- action1 = Action.objects.create(- team=self.team,- name="action1",- steps_json=[- {- "event": "$autocapture",- "url": "https://posthog.com/feedback/123",- "url_matching": "exact",- }- ],- )- new_events_schema = use_new_events_schema(self.team.pk)- query, params = filter_event(action1.steps[0], use_new_events_schema=new_events_schema)-- full_query = _event_uuid_query(new_events_schema).format(" AND ".join(query))- result = sync_execute(full_query, {**params, "team_id": self.team.pk}, team_id=self.team.pk)-- self.assertEqual(len(result), 1)- self.assertCountEqual(- [str(r[0]) for r in result],- [event_target_uuid],- )-- def test_filter_event_exact_url_with_query_params(self):- first_match_uuid = _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- properties={"$current_url": "https://posthog.com/feedback/123?vip=1"},- )-- second_match_uuid = _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- properties={"$current_url": "https://posthog.com/feedback/123?vip=1"},- )-- _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- properties={"$current_url": "https://posthog.com/feedback/123?vip=0"},- )-- action1 = Action.objects.create(- team=self.team,- name="action1",- steps_json=[- {- "event": "$autocapture",- "url": "https://posthog.com/feedback/123?vip=1",- "url_matching": "exact",- }- ],- )- new_events_schema = use_new_events_schema(self.team.pk)- query, params = filter_event(action1.steps[0], use_new_events_schema=new_events_schema)-- full_query = _event_uuid_query(new_events_schema).format(" AND ".join(query))- result = sync_execute(full_query, {**params, "team_id": self.team.pk}, team_id=self.team.pk)-- self.assertEqual(len(result), 2)- self.assertCountEqual(- [str(r[0]) for r in result],- [first_match_uuid, second_match_uuid],- )-- def test_filter_event_contains_url(self):- _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- properties={"$current_url": "https://posthog.com/feedback/123"},- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="whatever",- properties={"$current_url": "https://posthog.com/feedback/123"},- )-- _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- properties={"$current_url": "https://posthog.com/feedback/1234"},- )-- action1 = Action.objects.create(- team=self.team,- name="action1",- steps_json=[{"event": "$autocapture", "url": "https://posthog.com/feedback/123"}],- )- new_events_schema = use_new_events_schema(self.team.pk)- query, params = filter_event(action1.steps[0], use_new_events_schema=new_events_schema)-- full_query = _event_uuid_query(new_events_schema).format(" AND ".join(query))- result = sync_execute(full_query, {**params, "team_id": self.team.pk}, team_id=self.team.pk)- self.assertEqual(len(result), 2)-- def test_filter_event_regex_url(self):- _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- properties={"$current_url": "https://posthog.com/feedback/123"},- )-- _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- properties={"$current_url": "https://test.com/feedback"},- )-- _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- properties={"$current_url": "https://posthog.com/feedback/1234"},- )-- action1 = Action.objects.create(- team=self.team,- name="action1",- steps_json=[- {- "event": "$autocapture",- "url": "/123",- "url_matching": "regex",- }- ],- )- new_events_schema = use_new_events_schema(self.team.pk)- query, params = filter_event(action1.steps[0], use_new_events_schema=new_events_schema)-- full_query = _event_uuid_query(new_events_schema).format(" AND ".join(query))- result = sync_execute(full_query, {**params, "team_id": self.team.pk}, team_id=self.team.pk)- self.assertEqual(len(result), 2)-- def test_double(self):- # Tests a regression where the second step properties would override those of the first step, causing issues- _create_event(- event="insight viewed",- team=self.team,- distinct_id="whatever",- properties={"filters_count": 2},- )-- action1 = Action.objects.create(- team=self.team,- name="action1",- steps_json=[- {- "event": "insight viewed",- "properties": [- {- "key": "insight",- "type": "event",- "value": ["RETENTION"],- "operator": "exact",- }- ],- },- {- "event": "insight viewed",- "properties": [- {- "key": "filters_count",- "type": "event",- "value": "1",- "operator": "gt",- }- ],- },- ],- )-- events = _get_events_for_action(action1)- self.assertEqual(len(events), 1)-- def test_filter_with_hogql(self):- _create_event(- event="insight viewed",- team=self.team,- distinct_id="first",- properties={"filters_count": 20},- )- _create_event(- event="insight viewed",- team=self.team,- distinct_id="second",- properties={"filters_count": 1},- )-+class TestActionBytecode(BaseTest):+ def test_bytecode_for_hogql_step_property(self):action1 = Action.objects.create(team=self.team,name="action1",@@ -292,9 +25,6 @@ class TestActionFormat(ClickhouseTestMixin, BaseTest):],)- events = _get_events_for_action(action1)- self.assertEqual(len(events), 1)-self.assertEqual(action1.bytecode, create_bytecode(action_to_expr(action1)).bytecode)self.assertEqual(action1.bytecode,diff --git a/ee/clickhouse/models/test/test_cohort.py b/ee/clickhouse/models/test/test_cohort.pyindex 8739a5e5bc72..46b1e4932305 100644--- a/ee/clickhouse/models/test/test_cohort.py+++ b/ee/clickhouse/models/test/test_cohort.py@@ -13,66 +13,29 @@ from posthog.test.base import (also_test_with_materialized_columns,flush_persons_and_events,snapshot_clickhouse_insert_cohortpeople_queries,- snapshot_clickhouse_queries,)-from django.utils import timezone-from rest_framework.exceptions import ValidationError-from posthog.schema import PersonsOnEventsMode-from posthog.hogql.constants import MAX_SELECT_COHORT_CALCULATION_LIMITfrom posthog.clickhouse.client import sync_execute-from posthog.models.event.new_events_schema import events_read_table-from posthog.models.filters import Filter-from posthog.models.organization import Organization-from posthog.models.person.sql import GET_LATEST_PERSON_SQL, GET_PERSON_IDS_BY_FILTER-from posthog.models.property.util import parse_prop_grouped_clausesfrom posthog.models.team import Team-from posthog.queries.person_distinct_id_query import get_team_distinct_ids_query-from posthog.queries.util import PersonPropertiesModefrom posthog.test.persons import create_person, delete_person, update_personfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort-from products.cohorts.backend.models.sql import GET_COHORTPEOPLE_BY_COHORT_ID-from products.cohorts.backend.models.util import format_filter_query---def _events_table_for_filter(filter_obj: Filter) -> str:- return events_read_table(filter_obj.hogql_context.uses_new_events_schema())---def get_person_ids_by_cohort_id(- team_id: int,- cohort_id: int,- limit: Optional[int] = None,- offset: Optional[int] = None,-):- from posthog.models.property.util import parse_prop_grouped_clauses-- filter = Filter(data={"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]})- filter_query, filter_params = parse_prop_grouped_clauses(- team_id=team_id,- property_group=filter.property_groups,- table_name="pdi",- hogql_context=filter.hogql_context,- )-- results = sync_execute(- GET_PERSON_IDS_BY_FILTER.format(- person_query=GET_LATEST_PERSON_SQL,- distinct_query=filter_query,- query="",- GET_TEAM_PERSON_DISTINCT_IDS=get_team_distinct_ids_query(team_id),- offset="OFFSET %(offset)s" if offset else "",- limit="ORDER BY _timestamp ASC LIMIT %(limit)s" if limit else "",- ),- {**filter_params, "team_id": team_id, "offset": offset, "limit": limit},- )+from products.cohorts.backend.models.sql import GET_COHORTPEOPLE_BY_COHORT_ID, GET_STATIC_COHORTPEOPLE_BY_COHORT_ID++def get_person_ids_by_cohort_id(team_id: int, cohort_id: int) -> list[str]:+ cohort = Cohort.objects.get(pk=cohort_id)+ if cohort.is_static:+ results = sync_execute(GET_STATIC_COHORTPEOPLE_BY_COHORT_ID, {"team_id": team_id, "cohort_id": cohort_id})+ else:+ results = sync_execute(+ GET_COHORTPEOPLE_BY_COHORT_ID, {"team_id": team_id, "cohort_id": cohort_id, "version": cohort.version}+ )return [str(row[0]) for row in results]@@ -129,418 +92,6 @@ class TestCohort(ClickhouseTestMixin, BaseTest):},)- def test_prop_cohort_basic(self):- _create_person(- distinct_ids=["some_other_id"],- team_id=self.team.pk,- properties={"$some_prop": "something"},- )-- _create_person(- distinct_ids=["some_id"],- team_id=self.team.pk,- properties={"$some_prop": "something", "$another_prop": "something"},- )- _create_person(distinct_ids=["no_match"], team_id=self.team.pk)- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_id",- properties={"attr": "some_val"},- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_other_id",- properties={"attr": "some_val"},- )-- cohort1 = Cohort.objects.create(- team=self.team,- groups=[- {- "properties": [- {"key": "$some_prop", "value": "something", "type": "person"},- {- "key": "$another_prop",- "value": "something",- "type": "person",- },- ]- }- ],- name="cohort1",- )-- filter = Filter(data={"properties": [{"key": "id", "value": cohort1.pk, "type": "cohort"}]})- query, params = parse_prop_grouped_clauses(- team_id=self.team.pk,- property_group=filter.property_groups,- hogql_context=filter.hogql_context,- )- final_query = f"SELECT uuid FROM {_events_table_for_filter(filter)} WHERE team_id = %(team_id)s {query}"- result = sync_execute(- final_query,- {**params, **filter.hogql_context.values, "team_id": self.team.pk},- )- self.assertEqual(len(result), 1)-- def test_prop_cohort_basic_action(self):- _create_person(- distinct_ids=["some_other_id"],- team_id=self.team.pk,- properties={"$some_prop": "something"},- )-- _create_person(- distinct_ids=["some_id"],- team_id=self.team.pk,- properties={"$some_prop": "something", "$another_prop": "something"},- )- _create_person(distinct_ids=["no_match"], team_id=self.team.pk)-- action = _create_action(team=self.team, name="$pageview")- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_id",- properties={"attr": "some_val"},- timestamp=datetime.now() - timedelta(days=1),- )-- _create_event(- event="$not_pageview",- team=self.team,- distinct_id="some_other_id",- properties={"attr": "some_val"},- timestamp=datetime.now() - timedelta(days=2),- )-- cohort1 = Cohort.objects.create(team=self.team, groups=[{"action_id": action.pk, "days": 3}], name="cohort1")-- filter = Filter(- data={"properties": [{"key": "id", "value": cohort1.pk, "type": "cohort"}]},- team=self.team,- )- query, params = parse_prop_grouped_clauses(- team_id=self.team.pk,- property_group=filter.property_groups,- person_properties_mode=(- PersonPropertiesMode.USING_SUBQUERY- if self.team.person_on_events_mode == PersonsOnEventsMode.DISABLED- else PersonPropertiesMode.DIRECT_ON_EVENTS- ),- hogql_context=filter.hogql_context,- )- final_query = f"SELECT uuid FROM {_events_table_for_filter(filter)} WHERE team_id = %(team_id)s {query}"- result = sync_execute(- final_query,- {**params, **filter.hogql_context.values, "team_id": self.team.pk},- )-- self.assertEqual(len(result), 1)-- def test_prop_cohort_basic_event_days(self):- _create_person(- distinct_ids=["some_other_id"],- team_id=self.team.pk,- properties={"$some_prop": "something"},- )-- _create_person(- distinct_ids=["some_id"],- team_id=self.team.pk,- properties={"$some_prop": "something", "$another_prop": "something"},- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_id",- properties={"attr": "some_val"},- timestamp=datetime.now() - timedelta(days=0, hours=12),- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_other_id",- properties={"attr": "some_val"},- timestamp=datetime.now() - timedelta(days=4, hours=12),- )-- cohort1 = Cohort.objects.create(- team=self.team,- groups=[{"event_id": "$pageview", "days": 1}],- name="cohort1",- )-- filter = Filter(- data={"properties": [{"key": "id", "value": cohort1.pk, "type": "cohort"}]},- team=self.team,- )- query, params = parse_prop_grouped_clauses(- team_id=self.team.pk,- property_group=filter.property_groups,- person_properties_mode=(- PersonPropertiesMode.USING_SUBQUERY- if self.team.person_on_events_mode == PersonsOnEventsMode.DISABLED- else PersonPropertiesMode.DIRECT_ON_EVENTS- ),- hogql_context=filter.hogql_context,- )- final_query = f"SELECT uuid FROM {_events_table_for_filter(filter)} WHERE team_id = %(team_id)s {query}"- result = sync_execute(- final_query,- {**params, **filter.hogql_context.values, "team_id": self.team.pk},- )- self.assertEqual(len(result), 1)-- cohort2 = Cohort.objects.create(- team=self.team,- groups=[{"event_id": "$pageview", "days": 7}],- name="cohort2",- )-- filter = Filter(- data={"properties": [{"key": "id", "value": cohort2.pk, "type": "cohort"}]},- team=self.team,- )- query, params = parse_prop_grouped_clauses(- team_id=self.team.pk,- property_group=filter.property_groups,- person_properties_mode=(- PersonPropertiesMode.USING_SUBQUERY- if self.team.person_on_events_mode == PersonsOnEventsMode.DISABLED- else PersonPropertiesMode.DIRECT_ON_EVENTS- ),- hogql_context=filter.hogql_context,- )- final_query = f"SELECT uuid FROM {_events_table_for_filter(filter)} WHERE team_id = %(team_id)s {query}"- result = sync_execute(- final_query,- {**params, **filter.hogql_context.values, "team_id": self.team.pk},- )- self.assertEqual(len(result), 2)-- def test_prop_cohort_basic_action_days(self):- _create_person(- distinct_ids=["some_other_id"],- team_id=self.team.pk,- properties={"$some_prop": "something"},- )-- _create_person(- distinct_ids=["some_id"],- team_id=self.team.pk,- properties={"$some_prop": "something", "$another_prop": "something"},- )-- action = _create_action(team=self.team, name="$pageview")- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_id",- properties={"attr": "some_val"},- timestamp=datetime.now() - timedelta(hours=22),- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_other_id",- properties={"attr": "some_val"},- timestamp=datetime.now() - timedelta(days=5),- )-- cohort1 = Cohort.objects.create(team=self.team, groups=[{"action_id": action.pk, "days": 1}], name="cohort1")-- filter = Filter(- data={"properties": [{"key": "id", "value": cohort1.pk, "type": "cohort"}]},- team=self.team,- )- query, params = parse_prop_grouped_clauses(- team_id=self.team.pk,- property_group=filter.property_groups,- person_properties_mode=(- PersonPropertiesMode.USING_SUBQUERY- if self.team.person_on_events_mode == PersonsOnEventsMode.DISABLED- else PersonPropertiesMode.DIRECT_ON_EVENTS- ),- hogql_context=filter.hogql_context,- )- final_query = f"SELECT uuid FROM {_events_table_for_filter(filter)} WHERE team_id = %(team_id)s {query}"- result = sync_execute(- final_query,- {**params, **filter.hogql_context.values, "team_id": self.team.pk},- )- self.assertEqual(len(result), 1)-- cohort2 = Cohort.objects.create(team=self.team, groups=[{"action_id": action.pk, "days": 7}], name="cohort2")-- filter = Filter(- data={"properties": [{"key": "id", "value": cohort2.pk, "type": "cohort"}]},- team=self.team,- )- query, params = parse_prop_grouped_clauses(- team_id=self.team.pk,- property_group=filter.property_groups,- person_properties_mode=(- PersonPropertiesMode.USING_SUBQUERY- if self.team.person_on_events_mode == PersonsOnEventsMode.DISABLED- else PersonPropertiesMode.DIRECT_ON_EVENTS- ),- hogql_context=filter.hogql_context,- )- final_query = f"SELECT uuid FROM {_events_table_for_filter(filter)} WHERE team_id = %(team_id)s {query}"- result = sync_execute(- final_query,- {**params, **filter.hogql_context.values, "team_id": self.team.pk},- )- self.assertEqual(len(result), 2)-- def test_prop_cohort_multiple_groups(self):- _create_person(- distinct_ids=["some_other_id"],- team_id=self.team.pk,- properties={"$some_prop": "something"},- )-- _create_person(- distinct_ids=["some_id"],- team_id=self.team.pk,- properties={"$another_prop": "something"},- )- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_id",- properties={"attr": "some_val"},- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_other_id",- properties={"attr": "some_val"},- )-- cohort1 = Cohort.objects.create(- team=self.team,- groups=[- {"properties": [{"key": "$some_prop", "value": "something", "type": "person"}]},- {"properties": [{"key": "$another_prop", "value": "something", "type": "person"}]},- ],- name="cohort1",- )-- filter = Filter(- data={"properties": [{"key": "id", "value": cohort1.pk, "type": "cohort"}]},- team=self.team,- )- query, params = parse_prop_grouped_clauses(- team_id=self.team.pk,- property_group=filter.property_groups,- hogql_context=filter.hogql_context,- )- final_query = f"SELECT uuid FROM {_events_table_for_filter(filter)} WHERE team_id = %(team_id)s {query}"- result = sync_execute(- final_query,- {**params, **filter.hogql_context.values, "team_id": self.team.pk},- )- self.assertEqual(len(result), 2)-- def test_prop_cohort_with_negation(self):- team2 = Organization.objects.bootstrap(None)[2]-- _create_person(- distinct_ids=["some_other_id"],- team_id=self.team.pk,- properties={"$some_prop": "something"},- )-- _create_person(- distinct_ids=["some_id"],- team_id=team2.pk,- properties={"$another_prop": "something"},- )- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_id",- properties={"attr": "some_val"},- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_other_id",- properties={"attr": "some_val"},- )-- cohort1 = Cohort.objects.create(- team=self.team,- groups=[- {- "properties": [- {- "type": "person",- "key": "$some_prop",- "operator": "is_not",- "value": "something",- }- ]- }- ],- name="cohort1",- )-- filter = Filter(- data={"properties": [{"key": "id", "value": cohort1.pk, "type": "cohort"}]},- team=self.team,- )- query, params = parse_prop_grouped_clauses(- team_id=self.team.pk,- property_group=filter.property_groups,- hogql_context=filter.hogql_context,- )- final_query = f"SELECT uuid FROM {_events_table_for_filter(filter)} WHERE team_id = %(team_id)s {query}"- self.assertIn("person_distinct_id2", final_query)-- result = sync_execute(- final_query,- {**params, **filter.hogql_context.values, "team_id": self.team.pk},- )- self.assertEqual(len(result), 0)-- def test_cohort_get_person_ids_by_cohort_id(self):- user1 = _create_person(- distinct_ids=["user1"],- team_id=self.team.pk,- properties={"$some_prop": "something"},- )- _create_person(- distinct_ids=["user2"],- team_id=self.team.pk,- properties={"$some_prop": "another"},- )- user3 = _create_person(- distinct_ids=["user3"],- team_id=self.team.pk,- properties={"$some_prop": "something"},- )- cohort = Cohort.objects.create(- team=self.team,- groups=[{"properties": [{"key": "$some_prop", "value": "something", "type": "person"}]}],- name="cohort1",- )-- results = get_person_ids_by_cohort_id(self.team.pk, cohort.id)- self.assertEqual(len(results), 2)- self.assertIn(str(user1.uuid), results)- self.assertIn(str(user3.uuid), results)-def test_insert_by_distinct_id_or_email(self):create_person(team_id=self.team.pk, distinct_ids=["1"])create_person(team_id=self.team.pk, distinct_ids=["123"])@@ -916,23 +467,6 @@ class TestCohort(ClickhouseTestMixin, BaseTest):self.assertEqual(len(results), 1)self.assertEqual(results[0][0], p2.uuid)- def test_static_cohort_precalculated(self):- create_person(team_id=self.team.pk, distinct_ids=["1"])- create_person(team_id=self.team.pk, distinct_ids=["123"])- create_person(team_id=self.team.pk, distinct_ids=["2"])- # Team leakage- team2 = Team.objects.create(organization=self.organization)- create_person(team=team2, distinct_ids=["1"])-- cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, last_calculation=timezone.now())- cohort.insert_users_by_list(["1", "123"])-- self.calculate_cohort_hogql_test_harness(cohort, 0)-- with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):- sql, _ = format_filter_query(cohort, 0)- self.assertQueryMatchesSnapshot(sql)-def test_cohortpeople_with_valid_other_cohort_filter(self):create_person(team_id=self.team.pk, distinct_ids=["1"], properties={"foo": "bar"})create_person(team_id=self.team.pk, distinct_ids=["2"], properties={"foo": "non"})@@ -962,7 +496,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):team_id=self.team.pk,properties={"$some_prop": "something1"},)- _create_person(+ person2 = _create_person(distinct_ids=["2"],team_id=self.team.pk,properties={"$some_prop": "something2"},@@ -1021,120 +555,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):self.calculate_cohort_hogql_test_harness(cohort1, 0)- with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):- filter = Filter(- data={- "properties": [- {- "key": "id",- "value": cohort1.pk,- "type": "precalculated-cohort",- }- ]- },- team=self.team,- )- query, params = parse_prop_grouped_clauses(- team_id=self.team.pk,- property_group=filter.property_groups,- hogql_context=filter.hogql_context,- )- final_query = (- f"SELECT uuid, distinct_id FROM {_events_table_for_filter(filter)} WHERE team_id = %(team_id)s {query}"- )-- result = sync_execute(- final_query,- {**params, **filter.hogql_context.values, "team_id": self.team.pk},- )-- self.assertEqual(len(result), 1)- self.assertEqual(result[0][1], "2") # distinct_id '2' is the one in cohort-- @snapshot_clickhouse_queries- def test_cohortpeople_with_not_in_cohort_operator_and_no_precalculation(self):- _create_person(- distinct_ids=["1"],- team_id=self.team.pk,- properties={"$some_prop": "something1"},- )- _create_person(- distinct_ids=["2"],- team_id=self.team.pk,- properties={"$some_prop": "something2"},- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="1",- properties={"attr": "some_val"},- timestamp=datetime.now() - timedelta(days=10),- )- _create_event(- event="$pageview",- team=self.team,- distinct_id="2",- properties={"attr": "some_val"},- timestamp=datetime.now() - timedelta(days=20),- )-- flush_persons_and_events()-- cohort0: Cohort = Cohort.objects.create(- team=self.team,- groups=[{"properties": [{"key": "$some_prop", "value": "something1", "type": "person"}]}],- name="cohort0",- )-- cohort1 = Cohort.objects.create(- team=self.team,- filters={- "properties": {- "type": "AND",- "values": [- {- "event_type": "events",- "key": "$pageview",- "negation": False,- "time_interval": "year",- "time_value": 2,- "type": "behavioral",- "value": "performed_event",- },- {- "key": "id",- "negation": True,- "type": "cohort",- "value": cohort0.pk,- },- ],- }- },- name="cohort1",- )-- filter = Filter(- data={"properties": [{"key": "id", "value": cohort1.pk, "type": "cohort"}]},- team=self.team,- )- query, params = parse_prop_grouped_clauses(- team_id=self.team.pk,- property_group=filter.property_groups,- hogql_context=filter.hogql_context,- )- final_query = (- f"SELECT uuid, distinct_id FROM {_events_table_for_filter(filter)} WHERE team_id = %(team_id)s {query}"- )- self.assertIn("person_distinct_id2", final_query)-- result = sync_execute(- final_query,- {**params, **filter.hogql_context.values, "team_id": self.team.pk},- )- self.assertEqual(len(result), 2) # because we didn't precalculate the cohort, both people are in the cohort- distinct_ids = [r[1] for r in result]- self.assertCountEqual(distinct_ids, ["1", "2"])+ self.assertEqual([str(row[0]) for row in self._get_cohortpeople(cohort1)], [str(person2.uuid)])@snapshot_clickhouse_insert_cohortpeople_queriesdef test_cohortpeople_with_not_in_cohort_operator_for_behavioural_cohorts(self):@@ -1143,7 +564,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):team_id=self.team.pk,properties={"$some_prop": "something"},)- _create_person(+ person2 = _create_person(distinct_ids=["2"],team_id=self.team.pk,properties={"$some_prop": "something"},@@ -1222,27 +643,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):self.calculate_cohort_hogql_test_harness(cohort1, 0)- with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):- filter = Filter(- data={"properties": [{"key": "id", "value": cohort1.pk, "type": "cohort"}]},- team=self.team,- )- query, params = parse_prop_grouped_clauses(- team_id=self.team.pk,- property_group=filter.property_groups,- hogql_context=filter.hogql_context,- )- final_query = (- f"SELECT uuid, distinct_id FROM {_events_table_for_filter(filter)} WHERE team_id = %(team_id)s {query}"- )-- result = sync_execute(- final_query,- {**params, **filter.hogql_context.values, "team_id": self.team.pk},- )-- self.assertEqual(len(result), 1)- self.assertEqual(result[0][1], "2") # distinct_id '2' is the one in cohort+ self.assertEqual([str(row[0]) for row in self._get_cohortpeople(cohort1)], [str(person2.uuid)])def test_cohortpeople_with_nonexistent_other_cohort_filter(self):create_person(team_id=self.team.pk, distinct_ids=["1"], properties={"foo": "bar"})diff --git a/ee/clickhouse/models/test/test_filters.py b/ee/clickhouse/models/test/test_filters.pyindex 4957ff1b455c..d0f1bf9b9099 100644--- a/ee/clickhouse/models/test/test_filters.py+++ b/ee/clickhouse/models/test/test_filters.py@@ -1,70 +1,10 @@-import json-from typing import Optional--from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person--from posthog.clickhouse.client import query_with_columns, sync_execute-from posthog.constants import FILTER_TEST_ACCOUNTS-from posthog.models import Element, Organization, Team-from posthog.models.event.new_events_schema import events_read_table-from posthog.models.event.util import ClickhouseEventSerializerfrom posthog.models.filters import Filterfrom posthog.models.filters.retention_filter import RetentionFilterfrom posthog.models.filters.test.test_filter import TestFilter as PGTestFilters-from posthog.models.property.util import parse_prop_grouped_clauses-from posthog.queries.util import PersonPropertiesMode-from posthog.test.persons import create_person-from posthog.test.test_journeys import journeys_forfrom products.cohorts.backend.models.cohort import Cohort-def _filter_events(filter: Filter, team: Team, order_by: Optional[str] = None):- prop_filters, prop_filter_params = parse_prop_grouped_clauses(- property_group=filter.property_groups,- team_id=team.pk,- hogql_context=filter.hogql_context,- )- params = {"team_id": team.pk, **prop_filter_params}- use_new_events_schema = filter.hogql_context.uses_new_events_schema()- events_table = events_read_table(use_new_events_schema)- properties_expr = "toJSONString(properties)" if use_new_events_schema else "properties"-- events = query_with_columns(- f"""- SELECT- uuid,- event,- {properties_expr} AS properties,- timestamp,- distinct_id,- elements_chain- FROM {events_table} WHERE- team_id = %(team_id)s- {prop_filters}- {"ORDER BY {}".format(order_by) if order_by else ""}- """,- {**params, **filter.hogql_context.values},- )- parsed_events = ClickhouseEventSerializer(events, many=True, context={"elements": None, "people": None}).data- return parsed_events---def _filter_persons(filter: Filter, team: Team):- prop_filters, prop_filter_params = parse_prop_grouped_clauses(- property_group=filter.property_groups,- team_id=team.pk,- person_properties_mode=PersonPropertiesMode.USING_PERSON_PROPERTIES_COLUMN,- hogql_context=filter.hogql_context,- )- # Note this query does not handle person rows changing over time- rows = sync_execute(- f"SELECT id, properties AS person_props FROM person WHERE team_id = %(team_id)s {prop_filters}",- {"team_id": team.pk, **prop_filter_params, **filter.hogql_context.values},- )- return [str(uuid) for uuid, _ in rows]--class TestFilters(PGTestFilters):maxDiff = None@@ -549,776 +489,6 @@ class TestFilters(PGTestFilters):},)--class TestFiltering(ClickhouseTestMixin, BaseTest):- def test_simple(self):- _create_event(team=self.team, distinct_id="test", event="$pageview")- _create_event(- team=self.team,- distinct_id="test",- event="$pageview",- properties={"$current_url": 1},- ) # test for type incompatibility- _create_event(- team=self.team,- distinct_id="test",- event="$pageview",- properties={"$current_url": {"bla": "bla"}},- ) # test for type incompatibility- _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"$current_url": "https://whatever.com"},- )- filter = Filter(data={"properties": {"$current_url": "https://whatever.com"}})- events = _filter_events(filter, self.team)- self.assertEqual(len(events), 1)-- def test_multiple_equality(self):- _create_event(team=self.team, distinct_id="test", event="$pageview")- _create_event(- team=self.team,- distinct_id="test",- event="$pageview",- properties={"$current_url": 1},- ) # test for type incompatibility- _create_event(- team=self.team,- distinct_id="test",- event="$pageview",- properties={"$current_url": {"bla": "bla"}},- ) # test for type incompatibility- _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"$current_url": "https://whatever.com"},- )- _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"$current_url": "https://example.com"},- )- filter = Filter(data={"properties": {"$current_url": ["https://whatever.com", "https://example.com"]}})- events = _filter_events(filter, self.team)- self.assertEqual(len(events), 2)-- def test_numerical(self):- event1_uuid = _create_event(- team=self.team,- distinct_id="test",- event="$pageview",- properties={"$a_number": 5},- )- event2_uuid = _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"$a_number": 6},- )- _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"$a_number": "rubbish"},- )- filter = Filter(data={"properties": {"$a_number__gt": 5}})- events = _filter_events(filter, self.team)- self.assertEqual(events[0]["id"], event2_uuid)-- filter = Filter(data={"properties": {"$a_number": 5}})- events = _filter_events(filter, self.team)- self.assertEqual(events[0]["id"], event1_uuid)-- filter = Filter(data={"properties": {"$a_number__lt": 6}})- events = _filter_events(filter, self.team)- self.assertEqual(events[0]["id"], event1_uuid)-- def test_numerical_person_properties(self):- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"$a_number": 4})- _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"$a_number": 5})- _create_person(team_id=self.team.pk, distinct_ids=["p3"], properties={"$a_number": 6})-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "$a_number",- "value": 4,- "operator": "gt",- }- ]- }- )- self.assertEqual(len(_filter_persons(filter, self.team)), 2)-- filter = Filter(data={"properties": [{"type": "person", "key": "$a_number", "value": 5}]})- self.assertEqual(len(_filter_persons(filter, self.team)), 1)-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "$a_number",- "value": 6,- "operator": "lt",- }- ]- }- )- self.assertEqual(len(_filter_persons(filter, self.team)), 2)-- def test_contains(self):- _create_event(team=self.team, distinct_id="test", event="$pageview")- event2_uuid = _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"$current_url": "https://whatever.com"},- )- filter = Filter(data={"properties": {"$current_url__icontains": "whatever"}})- events = _filter_events(filter, self.team)- self.assertEqual(events[0]["id"], event2_uuid)-- def test_regex(self):- event1_uuid = _create_event(team=self.team, distinct_id="test", event="$pageview")- event2_uuid = _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"$current_url": "https://whatever.com"},- )- filter = Filter(data={"properties": {"$current_url__regex": r"\.com$"}})- events = _filter_events(filter, self.team)- self.assertEqual(events[0]["id"], event2_uuid)-- filter = Filter(data={"properties": {"$current_url__not_regex": r"\.eee$"}})- events = _filter_events(filter, self.team, order_by="timestamp")- self.assertEqual(events[0]["id"], event1_uuid)- self.assertEqual(events[1]["id"], event2_uuid)-- def test_invalid_regex(self):- _create_event(team=self.team, distinct_id="test", event="$pageview")- _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"$current_url": "https://whatever.com"},- )-- filter = Filter(data={"properties": {"$current_url__regex": "?*"}})- self.assertEqual(len(_filter_events(filter, self.team)), 0)-- filter = Filter(data={"properties": {"$current_url__not_regex": "?*"}})- self.assertEqual(len(_filter_events(filter, self.team)), 0)-- def test_is_not(self):- event1_uuid = _create_event(team=self.team, distinct_id="test", event="$pageview")- event2_uuid = _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"$current_url": "https://something.com"},- )- _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"$current_url": "https://whatever.com"},- )- filter = Filter(data={"properties": {"$current_url__is_not": "https://whatever.com"}})- events = _filter_events(filter, self.team)- self.assertEqual(- sorted([events[0]["id"], events[1]["id"]]),- sorted([event1_uuid, event2_uuid]),- )- self.assertEqual(len(events), 2)-- def test_does_not_contain(self):- event1_uuid = _create_event(team=self.team, event="$pageview", distinct_id="test")- event2_uuid = _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"$current_url": "https://something.com"},- )- _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"$current_url": "https://whatever.com"},- )- event3_uuid = _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"$current_url": None},- )- filter = Filter(data={"properties": {"$current_url__not_icontains": "whatever.com"}})- events = _filter_events(filter, self.team)- self.assertCountEqual([event["id"] for event in events], [event1_uuid, event2_uuid, event3_uuid])- self.assertEqual(len(events), 3)-- def test_multiple(self):- event2_uuid = _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={- "$current_url": "https://something.com",- "another_key": "value",- },- )- _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"$current_url": "https://something.com"},- )- filter = Filter(- data={- "properties": {- "$current_url__icontains": "something.com",- "another_key": "value",- }- }- )- events = _filter_events(filter, self.team)- self.assertEqual(events[0]["id"], event2_uuid)- self.assertEqual(len(events), 1)-- def test_user_properties(self):- _create_person(- team_id=self.team.pk,- distinct_ids=["person1"],- properties={"group": "some group"},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person2"],- properties={"group": "another group"},- )- event2_uuid = _create_event(- team=self.team,- distinct_id="person1",- event="$pageview",- properties={- "$current_url": "https://something.com",- "another_key": "value",- },- )- event_p2_uuid = _create_event(- team=self.team,- distinct_id="person2",- event="$pageview",- properties={"$current_url": "https://something.com"},- )-- # test for leakage- _, _, team2 = Organization.objects.bootstrap(None)- _create_person(- team_id=team2.pk,- distinct_ids=["person_team_2"],- properties={"group": "another group"},- )- _create_event(- team=team2,- distinct_id="person_team_2",- event="$pageview",- properties={- "$current_url": "https://something.com",- "another_key": "value",- },- )-- filter = Filter(data={"properties": [{"key": "group", "value": "some group", "type": "person"}]})- events = _filter_events(filter=filter, team=self.team, order_by=None)- self.assertEqual(len(events), 1)- self.assertEqual(events[0]["id"], event2_uuid)-- filter = Filter(- data={- "properties": [- {- "key": "group",- "operator": "is_not",- "value": "some group",- "type": "person",- }- ]- }- )- events = _filter_events(filter=filter, team=self.team, order_by=None)- self.assertEqual(events[0]["id"], event_p2_uuid)- self.assertEqual(len(events), 1)-- def test_user_properties_numerical(self):- _create_person(team_id=self.team.pk, distinct_ids=["person1"], properties={"group": 1})- _create_person(team_id=self.team.pk, distinct_ids=["person2"], properties={"group": 2})- event2_uuid = _create_event(- team=self.team,- distinct_id="person1",- event="$pageview",- properties={- "$current_url": "https://something.com",- "another_key": "value",- },- )- _create_event(- team=self.team,- distinct_id="person2",- event="$pageview",- properties={"$current_url": "https://something.com"},- )- filter = Filter(- data={- "properties": [- {"key": "group", "operator": "lt", "value": 2, "type": "person"},- {"key": "group", "operator": "gt", "value": 0, "type": "person"},- ]- }- )- events = _filter_events(filter=filter, team=self.team, order_by=None)- self.assertEqual(events[0]["id"], event2_uuid)- self.assertEqual(len(events), 1)-- def test_boolean_filters(self):- _create_event(team=self.team, event="$pageview", distinct_id="test")- event2_uuid = _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"is_first_user": True},- )- filter = Filter(data={"properties": [{"key": "is_first_user", "value": "true"}]})- events = _filter_events(filter, self.team)- self.assertEqual(events[0]["id"], event2_uuid)- self.assertEqual(len(events), 1)-- def test_is_not_set_and_is_set(self):- event1_uuid = _create_event(team=self.team, event="$pageview", distinct_id="test")- event2_uuid = _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"is_first_user": True},- )- filter = Filter(- data={- "properties": [- {- "key": "is_first_user",- "operator": "is_not_set",- "value": "is_not_set",- }- ]- }- )- events = _filter_events(filter, self.team)- self.assertEqual(events[0]["id"], event1_uuid)- self.assertEqual(len(events), 1)-- filter = Filter(data={"properties": [{"key": "is_first_user", "operator": "is_set", "value": "is_set"}]})- events = _filter_events(filter, self.team)- self.assertEqual(events[0]["id"], event2_uuid)- self.assertEqual(len(events), 1)-- def test_is_not_set_and_is_set_with_missing_value(self):- event1_uuid = _create_event(team=self.team, event="$pageview", distinct_id="test")- event2_uuid = _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"is_first_user": True},- )- filter = Filter(data={"properties": [{"key": "is_first_user", "operator": "is_not_set"}]})- events = _filter_events(filter, self.team)- self.assertEqual(events[0]["id"], event1_uuid)- self.assertEqual(len(events), 1)-- filter = Filter(data={"properties": [{"key": "is_first_user", "operator": "is_set"}]})- events = _filter_events(filter, self.team)- self.assertEqual(events[0]["id"], event2_uuid)- self.assertEqual(len(events), 1)-- def test_true_false(self):- _create_event(team=self.team, distinct_id="test", event="$pageview")- event2_uuid = _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"is_first": True},- )- filter = Filter(data={"properties": {"is_first": "true"}})- events = _filter_events(filter, self.team)- self.assertEqual(events[0]["id"], event2_uuid)-- filter = Filter(data={"properties": {"is_first": ["true"]}})- events = _filter_events(filter, self.team)-- self.assertEqual(events[0]["id"], event2_uuid)-- def test_is_not_true_false(self):- event_uuid = _create_event(team=self.team, distinct_id="test", event="$pageview")- _create_event(- team=self.team,- event="$pageview",- distinct_id="test",- properties={"is_first": True},- )- filter = Filter(data={"properties": [{"key": "is_first", "value": "true", "operator": "is_not"}]})- events = _filter_events(filter, self.team)- self.assertEqual(events[0]["id"], event_uuid)-- def test_json_object(self):- _create_person(- team_id=self.team.pk,- distinct_ids=["person1"],- properties={"name": {"first_name": "Mary", "last_name": "Smith"}},- )- event1_uuid = _create_event(- team=self.team,- distinct_id="person1",- event="$pageview",- properties={"$current_url": "https://something.com"},- )- filter = Filter(- data={- "properties": [- {- "key": "name",- "value": json.dumps({"first_name": "Mary", "last_name": "Smith"}),- "type": "person",- }- ]- }- )- events = _filter_events(filter=filter, team=self.team, order_by=None)- self.assertEqual(events[0]["id"], event1_uuid)- self.assertEqual(len(events), 1)-- def test_element_selectors(self):- _create_event(- team=self.team,- event="$autocapture",- distinct_id="distinct_id",- elements=[- Element.objects.create(tag_name="a"),- Element.objects.create(tag_name="div"),- ],- )- _create_event(team=self.team, event="$autocapture", distinct_id="distinct_id")- filter = Filter(data={"properties": [{"key": "selector", "value": "div > a", "type": "element"}]})- events = _filter_events(filter=filter, team=self.team)- self.assertEqual(len(events), 1)-- def test_element_filter(self):- _create_event(- team=self.team,- event="$autocapture",- distinct_id="distinct_id",- elements=[- Element.objects.create(tag_name="a", text="some text"),- Element.objects.create(tag_name="div"),- ],- )-- _create_event(- team=self.team,- event="$autocapture",- distinct_id="distinct_id",- elements=[- Element.objects.create(tag_name="a", text="some other text"),- Element.objects.create(tag_name="div"),- ],- )-- _create_event(team=self.team, event="$autocapture", distinct_id="distinct_id")- filter = Filter(- data={- "properties": [- {- "key": "text",- "value": ["some text", "some other text"],- "type": "element",- }- ]- }- )- events = _filter_events(filter=filter, team=self.team)- self.assertEqual(len(events), 2)-- filter2 = Filter(data={"properties": [{"key": "text", "value": "some text", "type": "element"}]})- events_response_2 = _filter_events(filter=filter2, team=self.team)- self.assertEqual(len(events_response_2), 1)-- def test_filter_out_team_members(self):- _create_person(- team_id=self.team.pk,- distinct_ids=["team_member"],- properties={"email": "[email protected]"},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["random_user"],- properties={"email": "[email protected]"},- )- self.team.test_account_filters = [- {- "key": "email",- "value": "@posthog.com",- "operator": "not_icontains",- "type": "person",- }- ]- self.team.save()- _create_event(team=self.team, distinct_id="team_member", event="$pageview")- _create_event(team=self.team, distinct_id="random_user", event="$pageview")- filter = Filter(- data={FILTER_TEST_ACCOUNTS: True, "events": [{"id": "$pageview"}]},- team=self.team,- )- events = _filter_events(filter=filter, team=self.team)- self.assertEqual(len(events), 1)-- def test_filter_out_team_members_with_grouped_properties(self):- _create_person(- team_id=self.team.pk,- distinct_ids=["person1"],- properties={"email": "[email protected]", "name": "test", "age": "10"},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person2"],- properties={"email": "[email protected]", "name": "test", "age": "20"},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person3"],- properties={"email": "[email protected]", "name": "test", "age": "30"},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person4"],- properties={"email": "[email protected]", "name": "test", "age": "40"},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person5"],- properties={"email": "[email protected]", "name": "test", "age": "50"},- )-- self.team.test_account_filters = [- {- "key": "email",- "value": "@posthog.com",- "operator": "not_icontains",- "type": "person",- }- ]- self.team.save()-- journeys_for(- team=self.team,- create_people=False,- events_by_person={- "person1": [- {- "event": "$pageview",- "properties": {- "key": "val",- "$browser": "Safari",- "$browser_version": 14,- },- }- ],- "person2": [- {- "event": "$pageview",- "properties": {- "key": "val",- "$browser": "Safari",- "$browser_version": 14,- },- }- ],- "person3": [- {- "event": "$pageview",- "properties": {- "key": "val",- "$browser": "Safari",- "$browser_version": 14,- },- }- ],- "person4": [- {- "event": "$pageview",- "properties": {- "key": "val",- "$browser": "Safari",- "$browser_version": 14,- },- }- ],- "person5": [- {- "event": "$pageview",- "properties": {- "key": "val",- "$browser": "Safari",- "$browser_version": 14,- },- }- ],- },- )-- filter = Filter(- data={- FILTER_TEST_ACCOUNTS: True,- "events": [{"id": "$pageview"}],- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "age",- "value": "10",- "operator": "exact",- "type": "person",- },- {- "key": "age",- "value": "20",- "operator": "exact",- "type": "person",- },- # choose person 1 and 2- ],- },- {- "type": "AND",- "values": [- {- "key": "$browser",- "value": "Safari",- "operator": "exact",- "type": "event",- },- {- "key": "age",- "value": "50",- "operator": "exact",- "type": "person",- },- # choose person 5- ],- },- ],- },- },- team=self.team,- )- events = _filter_events(filter=filter, team=self.team)- # test account filters delete person 5, so only 1 and 2 remain- self.assertEqual(len(events), 2)-- def test_person_cohort_properties(self):- person1_distinct_id = "person1"- create_person(- team=self.team,- distinct_ids=[person1_distinct_id],- properties={"$some_prop": "something"},- )-- cohort1 = Cohort.objects.create(- team=self.team,- groups=[{"properties": [{"type": "person", "key": "$some_prop", "value": "something"}]}],- name="cohort1",- )-- person2_distinct_id = "person2"- create_person(- team=self.team,- distinct_ids=[person2_distinct_id],- properties={"$some_prop": "different"},- )- cohort2 = Cohort.objects.create(- team=self.team,- groups=[- {- "properties": [- {- "type": "person",- "key": "$some_prop",- "value": "something",- "operator": "is_not",- }- ]- }- ],- name="cohort2",- )-- filter = Filter(- data={"properties": [{"key": "id", "value": cohort1.pk, "type": "cohort"}]},- team=self.team,- )-- prop_clause, prop_clause_params = parse_prop_grouped_clauses(- property_group=filter.property_groups,- has_person_id_joined=False,- team_id=self.team.pk,- hogql_context=filter.hogql_context,- )- query = """- SELECT distinct_id FROM person_distinct_id2 WHERE team_id = %(team_id)s {prop_clause}- """.format(prop_clause=prop_clause)- # get distinct_id column of result- result = sync_execute(- query,- {- "team_id": self.team.pk,- **prop_clause_params,- **filter.hogql_context.values,- },- )[0][0]- self.assertEqual(result, person1_distinct_id)-- # test cohort2 with negation- filter = Filter(- data={"properties": [{"key": "id", "value": cohort2.pk, "type": "cohort"}]},- team=self.team,- )- prop_clause, prop_clause_params = parse_prop_grouped_clauses(- property_group=filter.property_groups,- has_person_id_joined=False,- team_id=self.team.pk,- hogql_context=filter.hogql_context,- )- query = """- SELECT distinct_id FROM person_distinct_id2 WHERE team_id = %(team_id)s {prop_clause}- """.format(prop_clause=prop_clause)- # get distinct_id column of result- result = sync_execute(- query,- {- "team_id": self.team.pk,- **prop_clause_params,- **filter.hogql_context.values,- },- )[0][0]-- self.assertEqual(result, person2_distinct_id)-def test_simplify_nested(self):filter = Filter(data={diff --git a/ee/clickhouse/models/test/test_property.py b/ee/clickhouse/models/test/test_property.pyindex 3911c0f59923..dfde018e61ea 100644--- a/ee/clickhouse/models/test/test_property.py+++ b/ee/clickhouse/models/test/test_property.py@@ -1,869 +1,17 @@-from datetime import datetimefrom typing import Any, cast-from uuid import UUID-import pytest-from freezegun.api import freeze_time-from posthog.test.base import (- BaseTest,- ClickhouseTestMixin,- _create_event,- _create_person,- cleanup_materialized_columns,- snapshot_clickhouse_queries,-)+from posthog.test.base import BaseTest, ClickhouseTestMixin-from rest_framework.exceptions import ValidationError--from posthog.clickhouse.client import sync_executefrom posthog.constants import PropertyOperatorType-from posthog.models.element import Element-from posthog.models.event.new_events_schema import events_read_table, use_new_events_schema-from posthog.models.filters import Filter-from posthog.models.instance_setting import get_instance_setting-from posthog.models.organization import Organizationfrom posthog.models.property import Property-from posthog.models.property.util import (- PropertyGroup,- get_property_string_expr,- parse_prop_grouped_clauses,- prop_filter_json_extract,-)-from posthog.models.team import Team-from posthog.queries.util import PersonPropertiesMode--from products.cohorts.backend.models.cohort import Cohort+from posthog.models.property.util import PropertyGroup, get_property_string_exprfrom ee.clickhouse.materialized_columns.columns import materialize-class TestPropFormat(ClickhouseTestMixin, BaseTest):- CLASS_DATA_LEVEL_SETUP = False-- def _run_query(self, filter: Filter, **kwargs) -> list:- query, params = parse_prop_grouped_clauses(- property_group=filter.property_groups,- allow_denormalized_props=True,- team_id=self.team.pk,- hogql_context=filter.hogql_context,- **kwargs,- )- events_table = events_read_table(filter.hogql_context.uses_new_events_schema())- final_query = f"SELECT uuid FROM {events_table} WHERE team_id = %(team_id)s {query}"- return sync_execute(- final_query,- {**params, **filter.hogql_context.values, "team_id": self.team.pk},- )-- def test_prop_person(self):- _create_person(- distinct_ids=["some_other_id"],- team_id=self.team.pk,- properties={"email": "[email protected]"},- )-- _create_person(- distinct_ids=["some_id"],- team_id=self.team.pk,- properties={"email": "[email protected]"},- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_id",- properties={"attr": "some_val"},- )-- filter = Filter(data={"properties": [{"key": "email", "value": "[email protected]", "type": "person"}]})- self.assertEqual(len(self._run_query(filter)), 1)-- def test_prop_event(self):- _create_event(- event="$pageview",- team=self.team,- distinct_id="whatever",- properties={"attr": "some_other_val"},- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="whatever",- properties={"attr": "some_val"},- )-- filter_exact = Filter(data={"properties": [{"key": "attr", "value": "some_val"}]})- self.assertEqual(len(self._run_query(filter_exact)), 1)-- filter_regex = Filter(data={"properties": [{"key": "attr", "value": "some_.+_val", "operator": "regex"}]})- self.assertEqual(len(self._run_query(filter_regex)), 1)-- filter_icontains = Filter(data={"properties": [{"key": "attr", "value": "Some_Val", "operator": "icontains"}]})- self.assertEqual(len(self._run_query(filter_icontains)), 1)-- filter_not_icontains = Filter(- data={"properties": [{"key": "attr", "value": "other", "operator": "not_icontains"}]}- )- self.assertEqual(len(self._run_query(filter_not_icontains)), 1)-- def test_prop_element(self):- _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- properties={"attr": "some_other_val"},- elements=[- Element(- tag_name="a",- href="/a-url",- attr_class=["small"],- text="bla bla",- nth_child=1,- nth_of_type=0,- ),- Element(- tag_name="button",- attr_class=["btn", "btn-primary"],- nth_child=0,- nth_of_type=0,- ),- Element(tag_name="div", nth_child=0, nth_of_type=0),- Element(tag_name="label", nth_child=0, nth_of_type=0, attr_id="nested"),- ],- )- _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- properties={"attr": "some_val"},- elements=[- Element(- tag_name="a",- href="/a-url",- attr_class=["small"],- text='bla"bla',- attributes={},- nth_child=1,- nth_of_type=0,- ),- Element(- tag_name="button",- attr_class=["btn", "btn-secondary"],- nth_child=0,- nth_of_type=0,- ),- Element(tag_name="div", nth_child=0, nth_of_type=0),- Element(tag_name="img", nth_child=0, nth_of_type=0, attr_id="nested"),- ],- )- _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- elements=[- Element(tag_name="a", href="/789", nth_child=0, nth_of_type=0),- Element(- tag_name="button",- attr_class=["btn", "btn-tertiary"],- nth_child=0,- nth_of_type=0,- ),- ],- )-- # selector-- filter = Filter(- data={- "properties": [- {- "key": "selector",- "value": [".btn"],- "operator": "exact",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter)), 3)-- filter = Filter(- data={- "properties": [- {- "key": "selector",- "value": ".btn",- "operator": "exact",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter)), 3)-- filter = Filter(- data={- "properties": [- {- "key": "selector",- "value": [".btn-primary"],- "operator": "exact",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter)), 1)-- filter = Filter(- data={- "properties": [- {- "key": "selector",- "value": [".btn-secondary"],- "operator": "exact",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter)), 1)-- filter = Filter(- data={- "properties": [- {- "key": "selector",- "value": [".btn-primary", ".btn-secondary"],- "operator": "exact",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter)), 2)-- filter_selector_exact_empty = Filter(- data={- "properties": [- {- "key": "selector",- "value": [],- "operator": "exact",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter_selector_exact_empty)), 0)-- filter_selector_is_not_empty = Filter(- data={- "properties": [- {- "key": "selector",- "value": [],- "operator": "is_not",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter_selector_is_not_empty)), 3)-- # tag_name-- filter = Filter(- data={- "properties": [- {- "key": "tag_name",- "value": ["div"],- "operator": "exact",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter)), 2)-- filter = Filter(- data={- "properties": [- {- "key": "tag_name",- "value": "div",- "operator": "exact",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter)), 2)-- filter = Filter(- data={- "properties": [- {- "key": "tag_name",- "value": ["img"],- "operator": "exact",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter)), 1)-- filter = Filter(- data={- "properties": [- {- "key": "tag_name",- "value": ["label"],- "operator": "exact",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter)), 1)-- filter = Filter(- data={- "properties": [- {- "key": "tag_name",- "value": ["img", "label"],- "operator": "exact",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter)), 2)-- # href/text-- filter_href_exact = Filter(- data={- "properties": [- {- "key": "href",- "value": ["/a-url"],- "operator": "exact",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter_href_exact)), 2)-- filter_href_exact_double = Filter(- data={- "properties": [- {- "key": "href",- "value": ["/a-url", "/789"],- "operator": "exact",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter_href_exact_double)), 3)-- filter_href_exact_empty = Filter(- data={"properties": [{"key": "href", "value": [], "operator": "exact", "type": "element"}]}- )- self.assertEqual(len(self._run_query(filter_href_exact_empty)), 0)-- filter_href_is_not = Filter(- data={- "properties": [- {- "key": "href",- "value": ["/a-url"],- "operator": "is_not",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter_href_is_not)), 1)-- filter_href_is_not_double = Filter(- data={- "properties": [- {- "key": "href",- "value": ["/a-url", "/789"],- "operator": "is_not",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter_href_is_not_double)), 0)-- filter_href_is_not_empty = Filter(- data={- "properties": [- {- "key": "href",- "value": [],- "operator": "is_not",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter_href_is_not_empty)), 3)-- filter_href_exact_with_tag_name_is_not = Filter(- data={- "properties": [- {"key": "href", "value": ["/a-url"], "type": "element"},- {- "key": "tag_name",- "value": ["marquee"],- "operator": "is_not",- "type": "element",- },- ]- }- )- self.assertEqual(len(self._run_query(filter_href_exact_with_tag_name_is_not)), 2)-- filter_href_icontains = Filter(- data={- "properties": [- {- "key": "href",- "value": ["UrL"],- "operator": "icontains",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter_href_icontains)), 2)-- filter_href_regex = Filter(- data={- "properties": [- {- "key": "href",- "value": "/a-.+",- "operator": "regex",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter_href_regex)), 2)-- filter_href_not_regex = Filter(- data={- "properties": [- {- "key": "href",- "value": r"/\d+",- "operator": "not_regex",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter_href_not_regex)), 2)-- filter_text_icontains_with_doublequote = Filter(- data={- "properties": [- {- "key": "text",- "value": 'bla"bla',- "operator": "icontains",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter_text_icontains_with_doublequote)), 1)-- filter_text_is_set = Filter(- data={- "properties": [- {- "key": "text",- "value": "is_set",- "operator": "is_set",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter_text_is_set)), 2)-- filter_text_is_not_set = Filter(- data={- "properties": [- {- "key": "text",- "value": "is_not_set",- "operator": "is_not_set",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter_text_is_not_set)), 1)-- def test_prop_element_with_space(self):- _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- elements=[- Element(tag_name="a", href="/789", nth_child=0, nth_of_type=0),- Element(- tag_name="button",- attr_class=["btn space", "btn-tertiary"],- nth_child=0,- nth_of_type=0,- ),- ],- )-- # selector-- filter = Filter(- data={- "properties": [- {- "key": "selector",- "value": ["button"],- "operator": "exact",- "type": "element",- }- ]- }- )- self.assertEqual(len(self._run_query(filter)), 1)-- def test_prop_ints_saved_as_strings(self):- _create_event(- event="$pageview",- team=self.team,- distinct_id="whatever",- properties={"test_prop": "0"},- )- _create_event(- event="$pageview",- team=self.team,- distinct_id="whatever",- properties={"test_prop": "2"},- )- _create_event(- event="$pageview",- team=self.team,- distinct_id="whatever",- properties={"test_prop": 2},- )- _create_event(- event="$pageview",- team=self.team,- distinct_id="whatever",- properties={"test_prop": "string"},- )- filter = Filter(data={"properties": [{"key": "test_prop", "value": "2"}]})- self.assertEqual(len(self._run_query(filter)), 2)-- filter = Filter(data={"properties": [{"key": "test_prop", "value": 2}]})- self.assertEqual(len(self._run_query(filter)), 2)-- # value passed as string- filter = Filter(data={"properties": [{"key": "test_prop", "value": "1", "operator": "gt"}]})- self.assertEqual(len(self._run_query(filter)), 2)- filter = Filter(data={"properties": [{"key": "test_prop", "value": "3", "operator": "lt"}]})- self.assertEqual(len(self._run_query(filter)), 3)-- # value passed as int- filter = Filter(data={"properties": [{"key": "test_prop", "value": 1, "operator": "gt"}]})- self.assertEqual(len(self._run_query(filter)), 2)-- filter = Filter(data={"properties": [{"key": "test_prop", "value": 3, "operator": "lt"}]})- self.assertEqual(len(self._run_query(filter)), 3)-- def test_prop_decimals(self):- _create_event(- event="$pageview",- team=self.team,- distinct_id="whatever",- properties={"test_prop": 1.4},- )- _create_event(- event="$pageview",- team=self.team,- distinct_id="whatever",- properties={"test_prop": 1.3},- )- _create_event(- event="$pageview",- team=self.team,- distinct_id="whatever",- properties={"test_prop": 2},- )- _create_event(- event="$pageview",- team=self.team,- distinct_id="whatever",- properties={"test_prop": 2.5},- )-- filter = Filter(data={"properties": [{"key": "test_prop", "value": 1.5}]})- self.assertEqual(len(self._run_query(filter)), 0)-- filter = Filter(data={"properties": [{"key": "test_prop", "value": 1.2, "operator": "gt"}]})- self.assertEqual(len(self._run_query(filter)), 4)-- filter = Filter(data={"properties": [{"key": "test_prop", "value": "1.2", "operator": "gt"}]})- self.assertEqual(len(self._run_query(filter)), 4)-- filter = Filter(data={"properties": [{"key": "test_prop", "value": 2.3, "operator": "lt"}]})- self.assertEqual(len(self._run_query(filter)), 3)-- @snapshot_clickhouse_queries- def test_parse_groups(self):- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_id",- properties={"attr_1": "val_1", "attr_2": "val_2"},- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_id",- properties={"attr_1": "val_2"},- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_other_id",- properties={"attr_1": "val_3"},- )-- filter = Filter(- data={- "properties": {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {"key": "attr_1", "value": "val_1"},- {"key": "attr_2", "value": "val_2"},- ],- },- {"type": "OR", "values": [{"key": "attr_1", "value": "val_2"}]},- ],- }- }- )-- self.assertEqual(len(self._run_query(filter)), 2)-- def test_parse_groups_invalid_type(self):- filter = Filter(- data={- "properties": {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {"key": "attr", "value": "val_1"},- {"key": "attr_2", "value": "val_2"},- ],- },- {"type": "XOR", "values": [{"key": "attr", "value": "val_2"}]},- ],- }- }- )- with self.assertRaises(ValidationError):- self._run_query(filter)-- @snapshot_clickhouse_queries- def test_parse_groups_persons(self):- _create_person(- distinct_ids=["some_id"],- team_id=self.team.pk,- properties={"email": "[email protected]"},- )-- _create_person(- distinct_ids=["some_other_id"],- team_id=self.team.pk,- properties={"email": "[email protected]"},- )- _create_person(- distinct_ids=["some_other_random_id"],- team_id=self.team.pk,- properties={"email": "[email protected]"},- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_id",- properties={"attr": "val_1"},- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_other_id",- properties={"attr": "val_3"},- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_other_random_id",- properties={"attr": "val_3"},- )-- filter = Filter(- data={- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "email",- "type": "person",- "value": "[email protected]",- }- ],- },- {- "type": "OR",- "values": [- {- "key": "email",- "type": "person",- "value": "[email protected]",- }- ],- },- ],- }- }- )-- self.assertEqual(len(self._run_query(filter)), 2)--class TestPropDenormalized(ClickhouseTestMixin, BaseTest):CLASS_DATA_LEVEL_SETUP = False- def _run_query(self, filter: Filter) -> list:- filter.hogql_context.use_new_events_schema = False- query, params = parse_prop_grouped_clauses(- team_id=self.team.pk,- property_group=filter.property_groups,- allow_denormalized_props=True,- person_properties_mode=PersonPropertiesMode.USING_PERSON_PROPERTIES_COLUMN,- hogql_context=filter.hogql_context,- )- final_query = f"SELECT uuid FROM events WHERE team_id = %(team_id)s {query}"- # Make sure we don't accidentally use json on the properties field- self.assertNotIn("json", final_query.lower())- return sync_execute(- final_query,- {**params, **filter.hogql_context.values, "team_id": self.team.pk},- )-- def test_prop_event_denormalized(self):- _create_event(- event="$pageview",- team=self.team,- distinct_id="whatever",- properties={"test_prop": "some_other_val"},- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="whatever",- properties={"test_prop": "some_val"},- )-- materialize("events", "test_prop")- materialize("events", "something_else")-- filter = Filter(data={"properties": [{"key": "test_prop", "value": "some_val"}]})- self.assertEqual(len(self._run_query(filter)), 1)-- filter = Filter(data={"properties": [{"key": "test_prop", "value": "some_val", "operator": "is_not"}]})- self.assertEqual(len(self._run_query(filter)), 1)-- filter = Filter(data={"properties": [{"key": "test_prop", "value": "some_val", "operator": "is_set"}]})- self.assertEqual(len(self._run_query(filter)), 2)-- filter = Filter(data={"properties": [{"key": "test_prop", "value": "some_val", "operator": "is_not_set"}]})- self.assertEqual(len(self._run_query(filter)), 0)-- filter = Filter(data={"properties": [{"key": "test_prop", "value": "_other_", "operator": "icontains"}]})- self.assertEqual(len(self._run_query(filter)), 1)-- filter = Filter(- data={- "properties": [- {- "key": "test_prop",- "value": "_other_",- "operator": "not_icontains",- }- ]- }- )- self.assertEqual(len(self._run_query(filter)), 1)-- def test_prop_event_denormalized_ints(self):- _create_event(- event="$pageview",- team=self.team,- distinct_id="whatever",- properties={"test_prop": 0},- )-- _create_event(- event="$pageview",- team=self.team,- distinct_id="whatever",- properties={"test_prop": 2},- )-- materialize("events", "test_prop")- materialize("events", "something_else")-- filter = Filter(data={"properties": [{"key": "test_prop", "value": 1, "operator": "gt"}]})- self.assertEqual(len(self._run_query(filter)), 1)-- filter = Filter(data={"properties": [{"key": "test_prop", "value": 1, "operator": "lt"}]})- self.assertEqual(len(self._run_query(filter)), 1)-- filter = Filter(data={"properties": [{"key": "test_prop", "value": 0}]})- self.assertEqual(len(self._run_query(filter)), 1)-def test_get_property_string_expr(self):string_expr = get_property_string_expr("events", "some_non_mat_prop", "'some_non_mat_prop'", "properties")self.assertEqual(@@ -910,747 +58,6 @@ class TestPropDenormalized(ClickhouseTestMixin, BaseTest):self.assertEqual(string_expr, ('"mat_pp_some_mat_prop2"', True))-def test_parse_prop_clauses_defaults(snapshot):- filter = Filter(- data={- "properties": [- {"key": "event_prop", "value": "value"},- {- "key": "email",- "type": "person",- "value": "posthog",- "operator": "icontains",- },- ]- }- )-- assert (- parse_prop_grouped_clauses(- property_group=filter.property_groups,- allow_denormalized_props=False,- team_id=1,- hogql_context=filter.hogql_context,- )- == snapshot- )- assert (- parse_prop_grouped_clauses(- property_group=filter.property_groups,- person_properties_mode=PersonPropertiesMode.USING_PERSON_PROPERTIES_COLUMN,- allow_denormalized_props=False,- team_id=1,- hogql_context=filter.hogql_context,- )- == snapshot- )---def test_parse_prop_clauses_precalculated_cohort(snapshot):- Cohort.objects.filter(pk=42).delete()- org = Organization.objects.create(name="other org")-- team = Team.objects.create(organization=org)- # force pk for snapshot consistency- cohort = Cohort.objects.create(pk=42, team=team, groups=[{"event_id": "$pageview", "days": 7}], name="cohort")-- filter = Filter(- data={"properties": [{"key": "id", "value": cohort.pk, "type": "precalculated-cohort"}]},- team=team,- )-- assert (- parse_prop_grouped_clauses(- team_id=team.pk,- property_group=filter.property_groups,- person_properties_mode=PersonPropertiesMode.USING_SUBQUERY,- allow_denormalized_props=False,- person_id_joined_alias="pdi.person_id",- hogql_context=filter.hogql_context,- )- == snapshot- )---def test_parse_prop_clauses_cross_project_cohort_produces_impossible_match():- org_a = Organization.objects.create(name="org a")- team_a = Team.objects.create(organization=org_a)-- org_b = Organization.objects.create(name="org b")- team_b = Team.objects.create(organization=org_b)- cohort_b = Cohort.objects.create(team=team_b, groups=[{"properties": [{"key": "$browser", "value": "test"}]}])-- filter = Filter(- data={"properties": [{"key": "id", "value": cohort_b.pk, "type": "cohort"}]},- team=team_a,- )- result, _ = parse_prop_grouped_clauses(- team_id=team_a.pk,- property_group=filter.property_groups,- person_properties_mode=PersonPropertiesMode.USING_SUBQUERY,- allow_denormalized_props=False,- person_id_joined_alias="pdi.person_id",- hogql_context=filter.hogql_context,- )- assert "0 = 13" in result---# Regression test for: https://github.com/PostHog/posthog/pull/9283-def test_parse_prop_clauses_funnel_step_element_prepend_regression(snapshot):- filter = Filter(- data={- "properties": [- {- "key": "text",- "type": "element",- "value": "Insights1",- "operator": "exact",- }- ]- }- )-- assert (- parse_prop_grouped_clauses(- property_group=filter.property_groups,- allow_denormalized_props=False,- team_id=1,- prepend="PREPEND",- hogql_context=filter.hogql_context,- )- == snapshot- )---def test_parse_groups_persons_edge_case_with_single_filter(snapshot):- filter = Filter(- data={- "properties": {- "type": "OR",- "values": [{"key": "email", "type": "person", "value": "[email protected]"}],- }- }- )- assert (- parse_prop_grouped_clauses(- team_id=1,- property_group=filter.property_groups,- person_properties_mode=PersonPropertiesMode.USING_PERSON_PROPERTIES_COLUMN,- allow_denormalized_props=True,- hogql_context=filter.hogql_context,- )- == snapshot- )---def test_events(db, team) -> list[UUID]:- return [- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"email": "[email protected]"},- group2_properties={"email": "[email protected]"},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"email": "[email protected]"},- group2_properties={"email": "[email protected]"},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"attr": "some_val"},- group2_properties={"attr": "some_val"},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"attr": "50"},- group2_properties={"attr": "50"},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"attr": 5},- group2_properties={"attr": 5},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- # unix timestamp in seconds- properties={"unix_timestamp": int(datetime(2021, 4, 1, 18).timestamp())},- group2_properties={"unix_timestamp": int(datetime(2021, 4, 1, 18).timestamp())},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- # unix timestamp in seconds- properties={"unix_timestamp": int(datetime(2021, 4, 1, 19).timestamp())},- group2_properties={"unix_timestamp": int(datetime(2021, 4, 1, 19).timestamp())},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"long_date": f"{datetime(2021, 4, 1, 18):%Y-%m-%d %H:%M:%S%z}"},- group2_properties={"long_date": f"{datetime(2021, 4, 1, 18):%Y-%m-%d %H:%M:%S%z}"},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"long_date": f"{datetime(2021, 4, 1, 19):%Y-%m-%d %H:%M:%S%z}"},- group2_properties={"long_date": f"{datetime(2021, 4, 1, 19):%Y-%m-%d %H:%M:%S%z}"},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"short_date": f"{datetime(2021, 4, 4):%Y-%m-%d}"},- group2_properties={"short_date": f"{datetime(2021, 4, 4):%Y-%m-%d}"},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"short_date": f"{datetime(2021, 4, 6):%Y-%m-%d}"},- group2_properties={"short_date": f"{datetime(2021, 4, 6):%Y-%m-%d}"},- ),- # unix timestamp in seconds with fractions of a second- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"sdk_$time": 1639427152.339},- group2_properties={"sdk_$time": 1639427152.339},- ),- # unix timestamp in milliseconds- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"unix_timestamp_milliseconds": 1641977394339},- group2_properties={"unix_timestamp_milliseconds": 1641977394339},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"rfc_822_time": "Wed, 02 Oct 2002 15:00:00 +0200"},- group2_properties={"rfc_822_time": "Wed, 02 Oct 2002 15:00:00 +0200"},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"iso_8601_$time": f"{datetime(2021, 4, 1, 19):%Y-%m-%dT%H:%M:%S%Z}"},- group2_properties={"iso_8601_$time": f"{datetime(2021, 4, 1, 19):%Y-%m-%dT%H:%M:%S%Z}"},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"full_date_increasing_$time": f"{datetime(2021, 4, 1, 19):%d-%m-%Y %H:%M:%S}"},- group2_properties={"full_date_increasing_$time": f"{datetime(2021, 4, 1, 19):%d-%m-%Y %H:%M:%S}"},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"with_slashes_$time": f"{datetime(2021, 4, 1, 19):%Y/%m/%d %H:%M:%S}"},- group2_properties={"with_slashes_$time": f"{datetime(2021, 4, 1, 19):%Y/%m/%d %H:%M:%S}"},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"with_slashes_increasing_$time": f"{datetime(2021, 4, 1, 19):%d/%m/%Y %H:%M:%S}"},- group2_properties={"with_slashes_increasing_$time": f"{datetime(2021, 4, 1, 19):%d/%m/%Y %H:%M:%S}"},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- # seven digit unix timestamp in seconds - 7840800- # Clickhouse cannot parse this. It isn't matched in tests from TEST_PROPERTIES- properties={"unix_timestamp": int(datetime(1970, 4, 1, 18).timestamp())},- group2_properties={"unix_timestamp": int(datetime(1970, 4, 1, 18).timestamp())},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- # nine digit unix timestamp in seconds - 323460000- properties={"unix_timestamp": int(datetime(1980, 4, 1, 18).timestamp())},- group2_properties={"unix_timestamp": int(datetime(1980, 4, 1, 18).timestamp())},- ),- _create_event(- # matched by exact date test- event="$pageview",- team=team,- distinct_id="whatever",- properties={"date_only": f"{datetime(2021, 4, 1):%d/%m/%Y}"},- group2_properties={"date_only": f"{datetime(2021, 4, 1):%d/%m/%Y}"},- ),- _create_event(- # should not be matched by exact date test- event="$pageview",- team=team,- distinct_id="whatever",- properties={"date_only": f"{datetime(2021, 4, 1, 11):%d/%m/%Y}"},- group2_properties={"date_only": f"{datetime(2021, 4, 1, 11):%d/%m/%Y}"},- ),- _create_event(- # not matched by exact date test- event="$pageview",- team=team,- distinct_id="whatever",- properties={"date_only": f"{datetime(2021, 4, 2):%d/%m/%Y}"},- group2_properties={"date_only": f"{datetime(2021, 4, 2):%d/%m/%Y}"},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"date_only_matched_against_date_and_time": f"{datetime(2021, 3, 31, 18):%d/%m/%Y %H:%M:%S}"},- group2_properties={- "date_only_matched_against_date_and_time": f"{datetime(2021, 3, 31, 18):%d/%m/%Y %H:%M:%S}"- },- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- properties={"date_only_matched_against_date_and_time": int(datetime(2021, 3, 31, 14).timestamp())},- group2_properties={"date_only_matched_against_date_and_time": int(datetime(2021, 3, 31, 14).timestamp())},- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- # include milliseconds, to prove they're ignored in the query- properties={- "date_exact_including_seconds_and_milliseconds": f"{datetime(2021, 3, 31, 18, 12, 12, 12):%d/%m/%Y %H:%M:%S.%f}"- },- group2_properties={- "date_exact_including_seconds_and_milliseconds": f"{datetime(2021, 3, 31, 18, 12, 12, 12):%d/%m/%Y %H:%M:%S.%f}"- },- ),- _create_event(- event="$pageview",- team=team,- distinct_id="whatever",- # include milliseconds, to prove they're don't cause a date to be included in an after filter- properties={- "date_exact_including_seconds_and_milliseconds": f"{datetime(2021, 3, 31, 23, 59, 59, 12):%d/%m/%Y %H:%M:%S.%f}"- },- group2_properties={- "date_exact_including_seconds_and_milliseconds": f"{datetime(2021, 3, 31, 23, 59, 59, 12):%d/%m/%Y %H:%M:%S.%f}"- },- ),- ]---def clean_up_materialised_columns():- try:- yield- finally:- # after test cleanup- cleanup_materialized_columns()---TEST_PROPERTIES = [- pytest.param(Property(key="email", value="[email protected]"), [0]),- pytest.param(Property(key="email", value="[email protected]", operator="exact"), [0]),- pytest.param(- Property(- key="email",- value=["[email protected]", "[email protected]"],- operator="exact",- ),- [1],- ),- pytest.param(- Property(key="attr", value="5"),- [4],- id="matching a number only matches event index 4 from test_events",- ),- pytest.param(- Property(key="email", value="[email protected]", operator="is_not"),- range(1, 27),- id="matching on email is not a value matches all but the first event from test_events",- ),- pytest.param(- Property(- key="email",- value=["[email protected]", "[email protected]"],- operator="is_not",- ),- range(2, 27),- id="matching on email is not a value matches all but the first two events from test_events",- ),- pytest.param(Property(key="email", value=r".*est@.*", operator="regex"), [0]),- pytest.param(Property(key="email", value=r"?.", operator="regex"), []),- pytest.param(Property(key="email", operator="is_set", value="is_set"), [0, 1]),- pytest.param(- Property(key="email", operator="is_not_set", value="is_not_set"),- range(2, 27),- id="matching for email property not being set matches all but the first two events from test_events",- ),- pytest.param(- Property(key="unix_timestamp", operator="is_date_before", value="2021-04-02"),- [5, 6, 19],- id="matching before a unix timestamp only querying by date",- ),- pytest.param(- Property(key="unix_timestamp", operator="is_date_after", value="2021-03-31"),- [5, 6],- id="matching after a unix timestamp only querying by date",- ),- pytest.param(- Property(key="unix_timestamp", operator="is_date_before", value="2021-04-01 18:30:00"),- [5, 19],- id="matching before a unix timestamp querying by date and time",- ),- pytest.param(- Property(key="unix_timestamp", operator="is_date_after", value="2021-04-01 18:30:00"),- [6],- id="matching after a unix timestamp querying by date and time",- ),- pytest.param(Property(key="long_date", operator="is_date_before", value="2021-04-02"), [7, 8]),- pytest.param(- Property(key="long_date", operator="is_date_after", value="2021-03-31"),- [7, 8],- id="match after date only value against date and time formatted property",- ),- pytest.param(- Property(key="long_date", operator="is_date_before", value="2021-04-01 18:30:00"),- [7],- ),- pytest.param(- Property(key="long_date", operator="is_date_after", value="2021-04-01 18:30:00"),- [8],- ),- pytest.param(Property(key="short_date", operator="is_date_before", value="2021-04-05"), [9]),- pytest.param(Property(key="short_date", operator="is_date_after", value="2021-04-05"), [10]),- pytest.param(- Property(key="short_date", operator="is_date_before", value="2021-04-07"),- [9, 10],- ),- pytest.param(- Property(key="short_date", operator="is_date_after", value="2021-04-03"),- [9, 10],- ),- pytest.param(- Property(key="sdk_$time", operator="is_date_before", value="2021-12-25"),- [11],- id="matching a unix timestamp in seconds with fractional seconds after the decimal point",- ),- pytest.param(- Property(- key="unix_timestamp_milliseconds",- operator="is_date_after",- value="2022-01-11",- ),- [12],- id="matching unix timestamp in milliseconds after a given date (which ClickHouse doesn't support)",- ),- pytest.param(- Property(- key="unix_timestamp_milliseconds",- operator="is_date_before",- value="2022-01-13",- ),- [12],- id="matching unix timestamp in milliseconds before a given date (which ClickHouse doesn't support)",- ),- pytest.param(- Property(key="rfc_822_time", operator="is_date_before", value="2002-10-02 17:01:00"),- [13],- id="matching rfc 822 format date with timeszone offset before a given date",- ),- pytest.param(- Property(key="rfc_822_time", operator="is_date_after", value="2002-10-02 14:59:00"),- [],- id="matching rfc 822 format date takes into account timeszone offset after a given date",- ),- pytest.param(- Property(key="rfc_822_time", operator="is_date_after", value="2002-10-02 12:59:00"),- [13],- id="matching rfc 822 format date after a given date",- ),- pytest.param(- Property(key="iso_8601_$time", operator="is_date_before", value="2021-04-01 20:00:00"),- [14],- id="matching ISO 8601 format date before a given date",- ),- pytest.param(- Property(key="iso_8601_$time", operator="is_date_after", value="2021-04-01 18:00:00"),- [14],- id="matching ISO 8601 format date after a given date",- ),- pytest.param(- Property(- key="full_date_increasing_$time",- operator="is_date_before",- value="2021-04-01 20:00:00",- ),- [15],- id="matching full format date with date parts n increasing order before a given date",- ),- pytest.param(- Property(- key="full_date_increasing_$time",- operator="is_date_after",- value="2021-04-01 18:00:00",- ),- [15],- id="matching full format date with date parts in increasing order after a given date",- ),- pytest.param(- Property(- key="with_slashes_$time",- operator="is_date_before",- value="2021-04-01 20:00:00",- ),- [16],- id="matching full format date with date parts separated by slashes before a given date",- ),- pytest.param(- Property(- key="with_slashes_$time",- operator="is_date_after",- value="2021-04-01 18:00:00",- ),- [16],- id="matching full format date with date parts separated by slashes after a given date",- ),- pytest.param(- Property(- key="with_slashes_increasing_$time",- operator="is_date_before",- value="2021-04-01 20:00:00",- ),- [17],- id="matching full format date with date parts increasing in size and separated by slashes before a given date",- ),- pytest.param(- Property(- key="with_slashes_increasing_$time",- operator="is_date_after",- value="2021-04-01 18:00:00",- ),- [17],- id="matching full format date with date parts increasing in size and separated by slashes after a given date",- ),- pytest.param(- Property(key="date_only", operator="is_date_exact", value="2021-04-01"),- [20, 21],- id="can match dates exactly",- ),- pytest.param(- Property(- key="date_only_matched_against_date_and_time",- operator="is_date_exact",- value="2021-03-31",- ),- [23, 24],- id="can match dates exactly against datetimes and unix timestamps",- ),- pytest.param(- Property(- key="date_exact_including_seconds_and_milliseconds",- operator="is_date_exact",- value="2021-03-31 18:12:12",- ),- [25],- id="can match date times exactly against datetimes with milliseconds",- ),- pytest.param(- Property(- key="date_exact_including_seconds_and_milliseconds",- operator="is_date_after",- value="2021-03-31",- ),- [],- id="can match date only filter after against datetime with milliseconds",- ),- pytest.param(- Property(key="date_only", operator="is_date_after", value="2021-04-01"),- [22],- id="can match after date only values",- ),- pytest.param(- Property(key="date_only", operator="is_date_before", value="2021-04-02"),- [20, 21],- id="can match before date only values",- ),-]--[email protected]("property,expected_event_indexes", TEST_PROPERTIES)-@freeze_time("2021-04-01T01:00:00.000Z")-def test_prop_filter_json_extract(test_events, clean_up_materialised_columns, property, expected_event_indexes, team):- use_new = use_new_events_schema(team.pk)- query, params = prop_filter_json_extract(property, 0, allow_denormalized_props=False, use_new_events_schema=use_new)- events_table = events_read_table(use_new)- uuids = sorted(- [- str(uuid)- for (uuid,) in sync_execute(- f"SELECT uuid FROM {events_table} WHERE team_id = %(team_id)s {query}",- {"team_id": team.pk, **params},- )- ]- )- expected = sorted([test_events[index] for index in expected_event_indexes])-- assert len(uuids) == len(expected) # helpful when diagnosing assertion failure below- assert uuids == expected--- "property_filter,expected_fragment",- [- (- Property(key="dynamic_empty", operator="is_set", value="is_set"),- "isNotNull(properties.dynamic_empty)",- ),- (- Property(key="dynamic_datetime", operator="exact", value="2024-01-02T03:04:05"),- "replaceOne(toString(properties.dynamic_datetime), ' ', 'T')",- ),- (- Property(key="a%.b", operator="exact", value="value"),- "getSubcolumn(properties, %(k_0)s)",- ),- ],-)-def test_prop_filter_json_extract_native_json_dynamic_values(property_filter: Property, expected_fragment: str) -> None:- query, _ = prop_filter_json_extract(- property_filter,- 0,- allow_denormalized_props=False,- use_new_events_schema=True,- )-- assert expected_fragment in query- assert "JSONExtractRaw(toJSONString(properties)" not in query--[email protected]("property,expected_event_indexes", TEST_PROPERTIES)-@freeze_time("2021-04-01T01:00:00.000Z")-def test_prop_filter_json_extract_materialized(- test_events, clean_up_materialised_columns, property, expected_event_indexes, team-):- materialize("events", property.key)-- query, params = prop_filter_json_extract(property, 0, allow_denormalized_props=True, use_new_events_schema=False)-- assert "JSONExtract" not in query- events_table = events_read_table(False)-- uuids = sorted(- [- str(uuid)- for (uuid,) in sync_execute(- f"SELECT uuid FROM {events_table} WHERE team_id = %(team_id)s {query}",- {"team_id": team.pk, **params},- )- ]- )- expected = sorted([test_events[index] for index in expected_event_indexes])-- assert uuids == expected---@freeze_time("2021-04-01T01:00:00.000Z")-def test_prop_filter_json_extract_nullable_materialized_is_set_uses_json(- test_events, clean_up_materialised_columns, team-):- column = materialize("events", "email", is_nullable=True)- cases = [- (Property(key="email", operator="is_set", value="is_set"), [0, 1]),- (Property(key="email", operator="is_not_set", value="is_not_set"), range(2, 27)),- ]-- for property, expected_event_indexes in cases:- query, params = prop_filter_json_extract(- property, 0, allow_denormalized_props=True, use_new_events_schema=False- )-- assert column.name not in query- assert "JSONHas" in query- events_table = events_read_table(False)-- uuids = sorted(- [- str(uuid)- for (uuid,) in sync_execute(- f"SELECT uuid FROM {events_table} WHERE team_id = %(team_id)s {query}",- {"team_id": team.pk, **params},- )- ]- )- expected = sorted([test_events[index] for index in expected_event_indexes])-- assert uuids == expected--[email protected]("property,expected_event_indexes", TEST_PROPERTIES)-@freeze_time("2021-04-01T01:00:00.000Z")-def test_prop_filter_json_extract_person_on_events_materialized(- test_events, clean_up_materialised_columns, property, expected_event_indexes, team-):- if not get_instance_setting("PERSON_ON_EVENTS_ENABLED"):- return-- # simulates a group property being materialised- materialize("events", property.key, table_column=cast(Any, "group2_properties"))-- query, params = prop_filter_json_extract(property, 0, allow_denormalized_props=True, use_new_events_schema=False)- # this query uses the `properties` column, thus the materialized column is different.- assert ("JSON" in query) or ("AND 1 = 2" == query)-- query, params = prop_filter_json_extract(- property,- 0,- allow_denormalized_props=True,- use_event_column="group2_properties",- use_new_events_schema=False,- )- assert "JSON" not in query- events_table = events_read_table(False)-- uuids = sorted(- [- str(uuid)- for (uuid,) in sync_execute(- f"SELECT uuid FROM {events_table} WHERE team_id = %(team_id)s {query}",- {"team_id": team.pk, **params},- )- ]- )- expected = sorted([test_events[index] for index in expected_event_indexes])-- assert uuids == expected--def test_combine_group_properties():propertyA = Property(key="a", operator="exact", value=["a", "b", "c"])propertyB = Property(key="b", operator="exact", value=["d", "e", "f"])@@ -1780,85 +187,3 @@ def test_combine_group_properties():},],}---def test_session_property_validation():- # Property key not valid for type session- with pytest.raises(ValidationError):- filter = Filter(- data={- "properties": [- {- "type": "session",- "key": "some_prop",- "value": 0,- "operator": "gt",- }- ]- }- )- parse_prop_grouped_clauses(- team_id=1,- property_group=filter.property_groups,- hogql_context=filter.hogql_context,- )-- # Operator not valid for $session_duration- with pytest.raises(ValidationError):- filter = Filter(- data={- "properties": [- {- "type": "session",- "key": "$session_duration",- "value": 0,- "operator": "is_set",- }- ]- }- )- parse_prop_grouped_clauses(- team_id=1,- property_group=filter.property_groups,- hogql_context=filter.hogql_context,- )-- # Value not valid for $session_duration- with pytest.raises(ValidationError):- filter = Filter(- data={- "properties": [- {- "type": "session",- "key": "$session_duration",- "value": "hey",- "operator": "gt",- }- ]- }- )- parse_prop_grouped_clauses(- team_id=1,- property_group=filter.property_groups,- hogql_context=filter.hogql_context,- )-- # Valid property values- filter = Filter(- data={- "properties": [- {- "type": "session",- "key": "$session_duration",- "value": "100",- "operator": "gt",- }- ]- }- )- parse_prop_grouped_clauses(- team_id=1,- property_group=filter.property_groups,- hogql_context=filter.hogql_context,- )diff --git a/ee/clickhouse/queries/test/__snapshots__/test_person_distinct_id_query.ambr b/ee/clickhouse/queries/test/__snapshots__/test_person_distinct_id_query.ambrdeleted file mode 100644index 112bddef4e64..000000000000--- a/ee/clickhouse/queries/test/__snapshots__/test_person_distinct_id_query.ambr+++ /dev/null@@ -1,13 +0,0 @@-# serializer version: 1-# name: test_person_distinct_id_query- '''-- SELECT distinct_id, argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = %(team_id)s-- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0-- '''-# ---diff --git a/ee/clickhouse/queries/test/test_person_distinct_id_query.py b/ee/clickhouse/queries/test/test_person_distinct_id_query.pydeleted file mode 100644index 52d75ffdd35b..000000000000--- a/ee/clickhouse/queries/test/test_person_distinct_id_query.py+++ /dev/null@@ -1,5 +0,0 @@-from posthog.queries import person_distinct_id_query---def test_person_distinct_id_query(db, snapshot):- assert person_distinct_id_query.get_team_distinct_ids_query(2) == snapshotdiff --git a/posthog/models/entity/util.py b/posthog/models/entity/util.pydeleted file mode 100644index e765d8173a3b..000000000000--- a/posthog/models/entity/util.py+++ /dev/null@@ -1,66 +0,0 @@-from collections.abc import Sequence-from typing import Any--from posthog.hogql.hogql import HogQLContext--from posthog.constants import TREND_FILTER_TYPE_ACTIONS-from posthog.models.entity import Entity-from posthog.queries.util import PersonPropertiesMode--from products.actions.backend.models.util import format_action_filter, format_action_filter_event_only---def get_entity_filtering_params(- allowed_entities: Sequence[Entity],- team_id: int,- hogql_context: HogQLContext,- table_name: str = "",- *,- person_properties_mode: PersonPropertiesMode = PersonPropertiesMode.USING_PERSON_PROPERTIES_COLUMN,- person_id_joined_alias: str = "person_id",- deep_filtering: bool = False,-) -> tuple[dict, dict]:- """Return SQL condition for filtering events by allowed entities (events/actions).-- Events matching _at least one_ entity are included. If no entities are provided, _all_ events are included."""- if not allowed_entities:- return {}, {}-- params: dict[str, Any] = {}- entity_clauses: list[str] = []- action_ids_already_included: set[int] = set() # Avoid duplicating action conditions- events_already_included: set[str] = set() # Avoid duplicating event conditions- for entity in allowed_entities:- if entity.type == TREND_FILTER_TYPE_ACTIONS:- if entity.id in action_ids_already_included or entity.id is None:- continue- action_ids_already_included.add(int(entity.id))- action = entity.get_action(team_id)- action_query, action_params = (- format_action_filter(- team_id=team_id,- action=action,- table_name=table_name,- person_properties_mode=person_properties_mode,- person_id_joined_alias=person_id_joined_alias,- hogql_context=hogql_context,- )- if not deep_filtering- else format_action_filter_event_only(action)- )- params.update(action_params)- entity_clauses.append(action_query)- else:- if entity.id is None: # all events- continue- if entity.id in events_already_included:- continue- events_already_included.add(str(entity.id))- params[f"event_{entity.order}"] = entity.id- entity_clauses.append(f"event = %(event_{entity.order})s")-- if len(entity_clauses) == 0:- return {}, {"entity_query": "AND 1 = 1"}-- combined_entity_clauses = f"({' OR '.join(entity_clauses)})" if len(entity_clauses) > 1 else entity_clauses[0]- return params, {"entity_query": f"AND {combined_entity_clauses}"}diff --git a/posthog/models/event/sql.py b/posthog/models/event/sql.pyindex b2e8e8fd8818..aff6c142fe09 100644--- a/posthog/models/event/sql.py+++ b/posthog/models/event/sql.py@@ -884,9 +884,6 @@ UNION ALLSELECT toUInt16(0) AS total, {date_from_truncated}"""-EVENT_JOIN_PERSON_SQL = """-INNER JOIN ({GET_TEAM_PERSON_DISTINCT_IDS}) as pdi ON events.distinct_id = pdi.distinct_id-"""GET_EVENTS_WITH_PROPERTIES = """SELECT * FROM events WHEREdiff --git a/posthog/models/group/sql.py b/posthog/models/group/sql.pyindex 53a04425ebac..e6dcca8ec8f1 100644--- a/posthog/models/group/sql.py+++ b/posthog/models/group/sql.py@@ -128,11 +128,6 @@ INSERT_GROUP_SQL = """INSERT INTO groups (group_type_index, group_key, team_id, group_properties, created_at, _timestamp, _offset) SELECT %(group_type_index)s, %(group_key)s, %(team_id)s, %(group_properties)s, %(created_at)s, %(_timestamp)s, 0"""-GET_GROUP_IDS_BY_PROPERTY_SQL = """-SELECT DISTINCT group_key-FROM groups-WHERE team_id = %(team_id)s AND group_type_index = %({group_type_index_var})s {filters}-"""## Demo datadiff --git a/posthog/models/person/sql.py b/posthog/models/person/sql.pyindex 2a061c7a55ab..5d63a7afd5e5 100644--- a/posthog/models/person/sql.py+++ b/posthog/models/person/sql.py@@ -572,32 +572,6 @@ SELECT_PERSON_DISTINCT_ID2S_OF_TEAM = """SELECT * FROM {table_name} WHERE team_i# Other queries#-# `relevant_events_filter`` in the form of "AND event IN (...)" allows us to cut down memory usage by a lot at scale-GET_TEAM_PERSON_DISTINCT_IDS = """-SELECT distinct_id, argMax(person_id, version) as person_id-FROM person_distinct_id2-WHERE team_id = %(team_id)s-{relevant_events_filter}-GROUP BY distinct_id-HAVING argMax(is_deleted, version) = 0-"""--GET_PERSON_IDS_BY_FILTER = """-SELECT DISTINCT p.id-FROM ({latest_person_sql}) AS p-INNER JOIN ({GET_TEAM_PERSON_DISTINCT_IDS}) AS pdi ON p.id = pdi.person_id-WHERE team_id = %(team_id)s- {distinct_query}-{limit}-{offset}-""".format(- latest_person_sql=GET_LATEST_PERSON_SQL,- distinct_query="{distinct_query}",- limit="{limit}",- offset="{offset}",- GET_TEAM_PERSON_DISTINCT_IDS="{GET_TEAM_PERSON_DISTINCT_IDS}",-)-INSERT_PERSON_SQL = """INSERT INTO person (id, created_at, team_id, properties, is_identified, _timestamp, _offset, is_deleted, version, last_seen_at) SELECT %(id)s, %(created_at)s, %(team_id)s, %(properties)s, %(is_identified)s, %(_timestamp)s, 0, %(is_deleted)s, %(version)s, %(last_seen_at)s"""@@ -625,54 +599,6 @@ WHERE actor_id NOT IN ()"""-INSERT_COHORT_ALL_PEOPLE_SQL = """-INSERT INTO {cohort_table} SELECT generateUUIDv4(), id, %(cohort_id)s, %(team_id)s, %(_timestamp)s, 0 FROM (- SELECT id FROM (- {latest_person_sql}- ) as person INNER JOIN (- SELECT person_id, distinct_id FROM ({GET_TEAM_PERSON_DISTINCT_IDS}) WHERE person_id IN ({content_sql})- ) as pdi ON person.id = pdi.person_id- WHERE team_id = %(team_id)s- GROUP BY id-)-"""--GET_DISTINCT_IDS_BY_PROPERTY_SQL = """-SELECT distinct_id-FROM (- {GET_TEAM_PERSON_DISTINCT_IDS}-)-WHERE person_id IN-(- SELECT id- FROM (- SELECT id, argMax(properties, person._timestamp) as properties, max(is_deleted) as is_deleted- FROM person- WHERE team_id = %(team_id)s- GROUP BY id- HAVING is_deleted = 0- )- WHERE {filters}-)-"""--GET_DISTINCT_IDS_BY_PERSON_ID_FILTER = """-SELECT distinct_id-FROM ({GET_TEAM_PERSON_DISTINCT_IDS})-WHERE {filters}-"""--GET_ACTORS_FROM_EVENT_QUERY = """-SELECT- {id_field} AS actor_id,- {actor_value_expression} AS actor_value- {matching_events_select_statement}-FROM ({events_query})-GROUP BY actor_id-ORDER BY actor_value DESC, actor_id DESC /* Also sorting by ID for determinism */-{limit}-{offset}-"""COMMENT_DISTINCT_ID_COLUMN_SQL = lambda: ("ALTER TABLE person_distinct_id COMMENT COLUMN distinct_id 'skip_0003_fill_person_distinct_id2'"diff --git a/posthog/models/property/util.py b/posthog/models/property/util.pyindex 13c3ce0292b1..8654b193ce1b 100644--- a/posthog/models/property/util.py+++ b/posthog/models/property/util.py@@ -3,642 +3,23 @@ from collections import (Counter,Counter as TCounter,)-from collections.abc import Callable, Iterable+from collections.abc import Iterablefrom typing import Any, Literal, Optional, Union, cast-from rest_framework import exceptions-from posthog.hogql import astfrom posthog.hogql.database.s3_table import S3Tablefrom posthog.hogql.escape_sql import escape_clickhouse_identifier-from posthog.hogql.hogql import HogQLContextfrom posthog.hogql.parser import parse_exprfrom posthog.hogql.visitor import TraversingVisitorfrom posthog.clickhouse.kafka_engine import trim_quotes_exprfrom posthog.clickhouse.materialized_columns import TableWithProperties, get_materialized_column_for_property-from posthog.constants import PropertyOperatorTypefrom posthog.models.event import Selectorfrom posthog.models.event.sql import EVENTS_PROPERTIES_JSON_SUBCOLUMNS, PERSON_PROPERTIES_JSON_SUBCOLUMNS-from posthog.models.group.sql import GET_GROUP_IDS_BY_PROPERTY_SQL-from posthog.models.person.sql import GET_DISTINCT_IDS_BY_PERSON_ID_FILTER, GET_DISTINCT_IDS_BY_PROPERTY_SQL-from posthog.models.property import (- NEGATED_OPERATORS,- OperatorType,- Property,- PropertyGroup,- PropertyIdentifier,- PropertyName,-)-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.session_recordings.queries.session_query import SessionQuery-from posthog.utils import is_json, is_valid_regex+from posthog.models.property import Property, PropertyGroup, PropertyIdentifier, PropertyNamefrom products.actions.backend.models.action import Actionfrom products.actions.backend.models.util import get_action_tables_and_properties-from products.cohorts.backend.models.cohort import Cohort-from products.cohorts.backend.models.util import (- format_cohort_subquery,- format_filter_query,- format_precalculated_cohort_query,- format_static_cohort_query,- get_count_operator,-)--StringMatching = Literal["selector", "tag_name", "href", "text"]--# Property Groups Example:-# {type: 'AND', groups: [-# {type: 'OR', groups: [A, B, C]},-# {type: 'OR', groups: [D, E, F]},-# ]}--# Example:-# {type: 'AND', groups: [-# A, B, C, D-# ]}---# Property json is of the form:-# { type: 'AND | OR', groups: List[Property] }-# which is parsed and sent to this function ->-def parse_prop_grouped_clauses(- team_id: int,- property_group: Optional[PropertyGroup],- *,- hogql_context: HogQLContext,- prepend: str = "global",- table_name: str = "",- allow_denormalized_props: bool = True,- has_person_id_joined: bool = True,- person_properties_mode: PersonPropertiesMode = PersonPropertiesMode.USING_SUBQUERY,- person_id_joined_alias: str = "person_id",- group_properties_joined: bool = True,- _top_level: bool = True,-) -> tuple[str, dict]:- """Translate the given property filter group into an SQL condition clause (+ SQL params)."""- if not property_group or len(property_group.values) == 0:- return "", {}-- if isinstance(property_group.values[0], PropertyGroup):- group_clauses = []- final_params = {}- for idx, group in enumerate(property_group.values):- if isinstance(group, PropertyGroup):- clause, params = parse_prop_grouped_clauses(- team_id=team_id,- property_group=group,- prepend=f"{prepend}_{idx}",- table_name=table_name,- allow_denormalized_props=allow_denormalized_props,- has_person_id_joined=has_person_id_joined,- person_properties_mode=person_properties_mode,- person_id_joined_alias=person_id_joined_alias,- group_properties_joined=group_properties_joined,- hogql_context=hogql_context,- _top_level=False,- )- group_clauses.append(clause)- final_params.update(params)-- # purge empty returns- group_clauses = [clause for clause in group_clauses if clause]- _final = f"{property_group.type} ".join(group_clauses)- else:- _final, final_params = parse_prop_clauses(- filters=cast(list[Property], property_group.values),- prepend=f"{prepend}",- table_name=table_name,- allow_denormalized_props=allow_denormalized_props,- has_person_id_joined=has_person_id_joined,- person_properties_mode=person_properties_mode,- person_id_joined_alias=person_id_joined_alias,- group_properties_joined=group_properties_joined,- property_operator=property_group.type,- team_id=team_id,- hogql_context=hogql_context,- )-- if not _final:- final = ""- elif _top_level:- final = f"AND ({_final})"- else:- final = f"({_final})"-- return final, final_params---def parse_prop_clauses(- team_id: int,- filters: list[Property],- *,- hogql_context: Optional[HogQLContext],- prepend: str = "global",- table_name: str = "",- allow_denormalized_props: bool = True,- has_person_id_joined: bool = True,- person_properties_mode: PersonPropertiesMode = PersonPropertiesMode.USING_SUBQUERY,- person_id_joined_alias: str = "person_id",- group_properties_joined: bool = True,- property_operator: PropertyOperatorType = PropertyOperatorType.AND,-) -> tuple[str, dict]:- """Translate the given property filter into an SQL condition clause (+ SQL params)."""- final = []- params: dict[str, Any] = {}-- table_formatted = table_name- if table_formatted != "":- table_formatted += "."-- # Resolved once per query via the context so property fragments and the FROM table can't disagree.- use_new_events_schema = hogql_context.uses_new_events_schema() if hogql_context is not None else False-- _team = None-- def get_team():- nonlocal _team- if _team is None:- _team = Team.objects.only("project_id").get(pk=team_id)- return _team-- for idx, prop in enumerate(filters):- if prop.type == "cohort":- try:- cohort = Cohort.objects.get(pk=cast(str | int, prop.value), team__project_id=get_team().project_id)- except Cohort.DoesNotExist:- final.append(- f"{property_operator} 0 = 13"- ) # If cohort doesn't exist, nothing can match, unless an OR operator is used- else:- if person_properties_mode == PersonPropertiesMode.USING_SUBQUERY:- person_id_query, cohort_filter_params = format_filter_query(cohort, idx)- params = {**params, **cohort_filter_params}- final.append(f"{property_operator} {table_formatted}distinct_id IN ({person_id_query})")- else:- person_id_query, cohort_filter_params = format_cohort_subquery(- cohort,- idx,- custom_match_field=person_id_joined_alias,- )- params = {**params, **cohort_filter_params}- final.append(f"{property_operator} {person_id_query}")- elif prop.type == "person" and person_properties_mode in [- PersonPropertiesMode.DIRECT_ON_EVENTS,- PersonPropertiesMode.DIRECT_ON_EVENTS_WITH_POE_V2,- ]:- filter_query, filter_params = prop_filter_json_extract(- prop,- idx,- prepend,- prop_var="{}person_properties".format(table_formatted),- allow_denormalized_props=True,- property_operator=property_operator,- use_event_column="person_properties",- use_new_events_schema=use_new_events_schema,- )- final.append(filter_query)- params.update(filter_params)- elif prop.type == "person":- # :TODO: Clean this up by using PersonQuery over GET_DISTINCT_IDS_BY_PROPERTY_SQL to have access- # to materialized columns- # :TODO: (performance) Avoid subqueries whenever possible, use joins instead- is_direct_query = person_properties_mode == PersonPropertiesMode.USING_PERSON_PROPERTIES_COLUMN- filter_query, filter_params = prop_filter_json_extract(- prop,- idx,- "{}person".format(prepend),- prop_var="person_props" if is_direct_query else "properties",- allow_denormalized_props=allow_denormalized_props and is_direct_query,- property_operator=property_operator,- )- if is_direct_query:- final.append(filter_query)- params.update(filter_params)- else:- # Subquery filter here always should be blank as it's the first- filter_query = filter_query.replace(property_operator, "", 1)- final.append(- " {property_operator} {table_name}distinct_id IN ({filter_query})".format(- filter_query=GET_DISTINCT_IDS_BY_PROPERTY_SQL.format(- filters=filter_query,- GET_TEAM_PERSON_DISTINCT_IDS=get_team_distinct_ids_query(team_id),- ),- table_name=table_formatted,- property_operator=property_operator,- )- )- params.update(filter_params)- elif prop.type == "event":- filter_query, filter_params = prop_filter_json_extract(- prop,- idx,- prepend,- prop_var="{}properties".format(table_formatted),- allow_denormalized_props=allow_denormalized_props,- property_operator=property_operator,- use_new_events_schema=use_new_events_schema,- )- final.append(f" {filter_query}")- params.update(filter_params)- elif prop.type == "element":- query, filter_params = filter_element(- cast(StringMatching, prop.key),- prop.value,- operator=prop.operator,- prepend="{}_".format(prepend),- )- if query:- final.append(f"{property_operator} {query}")- params.update(filter_params)- elif prop.type == "group":- if group_properties_joined:- # Special case: $group_key refers to the actual group_key column, not a JSON property- if prop.key == "$group_key":- filter_query, filter_params = _build_group_key_filter(prop, idx, prepend, property_operator)- final.append(filter_query)- params.update(filter_params)- else:- filter_query, filter_params = prop_filter_json_extract(- prop,- idx,- prepend,- prop_var=f"group_properties_{prop.group_type_index}",- allow_denormalized_props=False,- property_operator=property_operator,- )- final.append(filter_query)- params.update(filter_params)- else:- # :TRICKY: offer groups support for queries which don't support automatically joining with groups table yet (e.g. lifecycle)- filter_query, filter_params = prop_filter_json_extract(- prop,- idx,- prepend,- prop_var=f"group_properties",- allow_denormalized_props=False,- )- group_type_index_var = f"{prepend}_group_type_index_{idx}"- groups_subquery = GET_GROUP_IDS_BY_PROPERTY_SQL.format(- filters=filter_query, group_type_index_var=group_type_index_var- )- final.append(- f"{property_operator} {table_formatted}$group_{prop.group_type_index} IN ({groups_subquery})"- )- params.update(filter_params)- params[group_type_index_var] = prop.group_type_index- elif prop.type in ("static-cohort", "precalculated-cohort"):- cohort_id = cast(int, prop.value)- cohort = Cohort.objects.get(pk=cohort_id, team__project_id=get_team().project_id)-- method = format_static_cohort_query if prop.type == "static-cohort" else format_precalculated_cohort_query- filter_query, filter_params = method(cohort, idx, prepend=prepend)- filter_query = f"""{person_id_joined_alias if not person_properties_mode == PersonPropertiesMode.DIRECT_ON_EVENTS else "person_id"} IN ({filter_query})"""-- if has_person_id_joined or person_properties_mode in [- PersonPropertiesMode.DIRECT_ON_EVENTS,- PersonPropertiesMode.DIRECT_ON_EVENTS_WITH_POE_V2,- ]:- final.append(f"{property_operator} {filter_query}")- else:- # :TODO: (performance) Avoid subqueries whenever possible, use joins instead- subquery = GET_DISTINCT_IDS_BY_PERSON_ID_FILTER.format(- filters=filter_query,- GET_TEAM_PERSON_DISTINCT_IDS=get_team_distinct_ids_query(team_id),- )- final.append(f"{property_operator} {table_formatted}distinct_id IN ({subquery})")- params.update(filter_params)- elif prop.type == "session":- filter_query, filter_params = get_session_property_filter_statement(prop, idx, prepend)- final.append(f"{property_operator} {filter_query}")- params.update(filter_params)- elif prop.type == "hogql":- if hogql_context is None:- raise ValueError("HogQL is not supported here")- from posthog.hogql.hogql import translate_hogql-- filter_query = translate_hogql(prop.key, hogql_context)- final.append(f"{property_operator} {filter_query}")-- if final:- # remove the first operator- return " ".join(final).replace(property_operator, "", 1), params-- return "", params---def negate_operator(operator: OperatorType) -> OperatorType:- return cast(- OperatorType,- {- "is_not": "exact",- "exact": "is_not",- "icontains": "not_icontains",- "not_icontains": "icontains",- "starts_with": "not_starts_with",- "not_starts_with": "starts_with",- "ends_with": "not_ends_with",- "not_ends_with": "ends_with",- "regex": "not_regex",- "not_regex": "regex",- "gt": "lte",- "lt": "gte",- "gte": "lt",- "lte": "gt",- "is_set": "is_not_set",- "is_not_set": "is_set",- "is_date_before": "is_date_after",- "is_date_after": "is_date_before",- # is_date_exact not yet supported- }.get(operator, operator),- )---def prop_filter_json_extract(- prop: Property,- idx: int,- prepend: str = "",- prop_var: str = "properties",- allow_denormalized_props: bool = True,- transform_expression: Optional[Callable[[str], str]] = None,- property_operator: str = PropertyOperatorType.AND,- table_name: Optional[str] = None,- use_event_column: Optional[str] = None,- use_new_events_schema: bool = False,-) -> tuple[str, dict[str, Any]]:- # TODO: Once all queries are migrated over we can get rid of allow_denormalized_props- if transform_expression is not None:- prop_var = transform_expression(prop_var)-- target_table = "events" if use_event_column else property_table(prop)- is_events_json = use_new_events_schema and target_table == "events"-- property_expr, is_denormalized = get_property_string_expr(- target_table,- prop.key,- f"%(k{prepend}_{idx})s",- prop_var,- allow_denormalized_props,- table_name,- materialised_table_column=use_event_column if use_event_column else "properties",- use_new_events_schema=is_events_json,- )- events_json_property_exists_expr: str | None = None- events_json_column = use_event_column or "properties"- if is_events_json and events_json_column in ("properties", "person_properties"):- table_prefix = f"{table_name}." if table_name else ""- events_json_property_exists_expr = _json_events_property_exists_expr(- prop.key,- f"%(k{prepend}_{idx})s",- f"{table_prefix}{prop_var}",- events_json_column,- )-- if is_denormalized and transform_expression:- property_expr = transform_expression(property_expr)-- operator = prop.operator- if prop.negation:- operator = negate_operator(operator or "exact")-- params: dict[str, Any] = {}-- if operator == "is_not":- params = {- "k{}_{}".format(prepend, idx): prop.key,- "v{}_{}".format(prepend, idx): box_value(prop.value),- }- return (- " {property_operator} NOT has(%(v{prepend}_{idx})s, {left})".format(- idx=idx,- prepend=prepend,- left=property_expr,- property_operator=property_operator,- ),- params,- )- elif operator == "icontains":- value = "%{}%".format(prop.value)- params = {- "k{}_{}".format(prepend, idx): prop.key,- "v{}_{}".format(prepend, idx): value,- }- return (- " {property_operator} {left} ILIKE %(v{prepend}_{idx})s".format(- idx=idx,- prepend=prepend,- left=property_expr,- property_operator=property_operator,- ),- params,- )- elif operator == "not_icontains":- value = "%{}%".format(prop.value)- params = {- "k{}_{}".format(prepend, idx): prop.key,- "v{}_{}".format(prepend, idx): value,- }- return (- " {property_operator} NOT ({left} ILIKE %(v{prepend}_{idx})s)".format(- idx=idx,- prepend=prepend,- left=property_expr,- property_operator=property_operator,- ),- params,- )- elif operator in ("starts_with", "not_starts_with", "ends_with", "not_ends_with"):- value = f"{prop.value}%" if operator in ("starts_with", "not_starts_with") else f"%{prop.value}"- params = {- "k{}_{}".format(prepend, idx): prop.key,- "v{}_{}".format(prepend, idx): value,- }- ilike = "{left} ILIKE %(v{prepend}_{idx})s".format(idx=idx, prepend=prepend, left=property_expr)- return (- " {property_operator} {condition}".format(- property_operator=property_operator,- condition=f"NOT ({ilike})" if operator.startswith("not_") else ilike,- ),- params,- )- elif operator in ("regex", "not_regex"):- if not is_valid_regex(str(prop.value)):- # If OR'ing, shouldn't be a problem since nothing will match this specific clause- return f"{property_operator} 1 = 2", {}-- params = {- "k{}_{}".format(prepend, idx): prop.key,- "v{}_{}".format(prepend, idx): prop.value,- }-- return (- " {property_operator} {regex_function}({left}, %(v{prepend}_{idx})s)".format(- regex_function="match" if operator == "regex" else "NOT match",- idx=idx,- prepend=prepend,- left=property_expr,- property_operator=property_operator,- ),- params,- )- elif operator == "is_set":- params = {- "k{}_{}".format(prepend, idx): prop.key,- "v{}_{}".format(prepend, idx): prop.value,- }- if events_json_property_exists_expr is not None:- return (- f" {property_operator} {events_json_property_exists_expr}",- params,- )- if is_denormalized:- return (- " {property_operator} {left} != ''".format(left=property_expr, property_operator=property_operator),- params,- )- return (- " {property_operator} JSONHas({prop_var}, %(k{prepend}_{idx})s)".format(- idx=idx,- prepend=prepend,- prop_var=prop_var,- property_operator=property_operator,- ),- params,- )- elif operator == "is_not_set":- params = {- "k{}_{}".format(prepend, idx): prop.key,- "v{}_{}".format(prepend, idx): prop.value,- }- if events_json_property_exists_expr is not None:- return (- f" {property_operator} NOT ({events_json_property_exists_expr})",- params,- )- if is_denormalized:- return (- " {property_operator} {left} = ''".format(left=property_expr, property_operator=property_operator),- params,- )- return (- " {property_operator} (isNull({left}) OR NOT JSONHas({prop_var}, %(k{prepend}_{idx})s))".format(- idx=idx,- prepend=prepend,- prop_var=prop_var,- left=property_expr,- property_operator=property_operator,- ),- params,- )- elif operator == "is_date_exact":- # TODO introducing duplication in these branches now rather than refactor too early- assert isinstance(prop.value, str)- prop_value_param_key = "v{}_{}".format(prepend, idx)-- # if we're comparing against a date with no time,- # truncate the values in the DB which may have times- granularity = "day" if re.match(r"^\d{4}-\d{2}-\d{2}$", prop.value) else "second"- query = f"""AND date_trunc('{granularity}', coalesce(- parseDateTimeBestEffortOrNull({property_expr}),- parseDateTimeBestEffortOrNull(substring({property_expr}, 1, 10))- )) = %({prop_value_param_key})s"""-- return (- query,- {"k{}_{}".format(prepend, idx): prop.key, prop_value_param_key: prop.value},- )- elif operator == "is_date_after":- # TODO introducing duplication in these branches now rather than refactor too early- assert isinstance(prop.value, str)- prop_value_param_key = "v{}_{}".format(prepend, idx)-- # if we're comparing against a date with no time,- # then instead of 2019-01-01 (implied 00:00:00)- # use 2019-01-01 23:59:59- is_date_only = re.match(r"^\d{4}-\d{2}-\d{2}$", prop.value)-- try_parse_as_date = f"parseDateTimeBestEffortOrNull({property_expr})"- try_parse_as_timestamp = f"parseDateTimeBestEffortOrNull(substring({property_expr}, 1, 10))"- first_of_date_or_timestamp = f"coalesce({try_parse_as_date},{try_parse_as_timestamp})"-- if is_date_only:- adjusted_value = f"subtractSeconds(addDays(toDate(%({prop_value_param_key})s), 1), 1)"- else:- adjusted_value = f"%({prop_value_param_key})s"-- query = f"""{property_operator} {first_of_date_or_timestamp} > {adjusted_value}"""-- return (- query,- {"k{}_{}".format(prepend, idx): prop.key, prop_value_param_key: prop.value},- )- elif operator == "is_date_before":- # TODO introducing duplication in these branches now rather than refactor too early- assert isinstance(prop.value, str)- prop_value_param_key = "v{}_{}".format(prepend, idx)- try_parse_as_date = f"parseDateTimeBestEffortOrNull({property_expr})"- try_parse_as_timestamp = f"parseDateTimeBestEffortOrNull(substring({property_expr}, 1, 10))"- first_of_date_or_timestamp = f"coalesce({try_parse_as_date},{try_parse_as_timestamp})"- query = f"""{property_operator} {first_of_date_or_timestamp} < %({prop_value_param_key})s"""-- return (- query,- {"k{}_{}".format(prepend, idx): prop.key, prop_value_param_key: prop.value},- )- elif operator in ["gt", "lt", "gte", "lte"]:- count_operator = get_count_operator(operator)-- params = {- "k{}_{}".format(prepend, idx): prop.key,- "v{}_{}".format(prepend, idx): prop.value,- }- extract_property_expr = trim_quotes_expr(f"replaceRegexpAll({property_expr}, ' ', '')")- return (- f" {property_operator} toFloat64OrNull({extract_property_expr}) {count_operator} %(v{prepend}_{idx})s",- params,- )- else:- if is_json(prop.value) and not is_denormalized:- if is_events_json:- clause = " {property_operator} has(arrayMap(value -> toJSONString(JSONExtract(value, 'Dynamic')), %(v{prepend}_{idx})s), {left})"- values = box_value(prop.value)- else:- clause = " {property_operator} has(%(v{prepend}_{idx})s, replaceRegexpAll(visitParamExtractRaw({prop_var}, %(k{prepend}_{idx})s),' ', ''))"- values = box_value(prop.value, remove_spaces=True)- params = {- "k{}_{}".format(prepend, idx): prop.key,- "v{}_{}".format(prepend, idx): values,- }- else:- clause = " {property_operator} has(%(v{prepend}_{idx})s, {left})"- params = {- "k{}_{}".format(prepend, idx): prop.key,- "v{}_{}".format(prepend, idx): box_value(prop.value),- }- return (- clause.format(- left=property_expr,- idx=idx,- prepend=prepend,- prop_var=prop_var,- property_operator=property_operator,- ),- params,- )---def property_table(property: Property) -> TableWithProperties:- if property.type == "event":- return "events"- elif property.type == "person":- return "person"- elif property.type == "group":- return "groups"- else:- raise ValueError(f"Property type does not have a table: {property.type}")def get_property_string_expr(@@ -733,24 +114,6 @@ def _json_events_property_expr(return trim_quotes_expr(f"ifNull({raw_value}, '')"), False-def _json_events_property_exists_expr(- property_name: PropertyName, var: str, column_ref: str, materialised_table_column: str-) -> str:- subcolumns = (- EVENTS_PROPERTIES_JSON_SUBCOLUMNS- if materialised_table_column == "properties"- else PERSON_PROPERTIES_JSON_SUBCOLUMNS- )- scalar_value = _json_events_subcolumn_expr(property_name, var, column_ref)- if property_name in subcolumns:- if subcolumns[property_name].startswith(("Array(", "Map(")):- return f"notEmpty({scalar_value})"- return f"isNotNull({scalar_value})"-- object_value = f"toJSONString({_json_events_subcolumn_expr(property_name, var, column_ref, sub_object=True)})"- return f"(isNotNull({scalar_value}) OR {object_value} != '{{}}')"--def _json_events_subcolumn_expr(property_name: PropertyName, var: str, column_ref: str, *, sub_object: bool = False) -> str:@@ -770,141 +133,6 @@ def box_value(value: Any, remove_spaces=False) -> list[Any]:return [str(value).replace(" ", "") if remove_spaces else str(value) for value in value]-def filter_element(- key: StringMatching,- value: ValueT,- *,- operator: Optional[OperatorType] = None,- prepend: str = "",-) -> tuple[str, dict]:- if operator is None:- operator = "exact"-- params = {}- combination_conditions: list[str] = []-- if key == "selector":- if operator not in ("exact", "is_not"):- raise exceptions.ValidationError(- 'Filtering by element selector only supports operators "equals" and "doesn\'t equal" currently.'- )- selectors = cast(list[str | int], value) if isinstance(value, list) else [value]- for idx, query in enumerate(selectors):- if not query: # Skip empty selectors- continue- if not isinstance(query, str):- raise exceptions.ValidationError("Selector must be a string")- selector = Selector(query, escape_slashes=False)- param_key = f"{prepend}_{idx}_selector_regex"- params[param_key] = build_selector_regex(selector)- combination_conditions.append(f"match(elements_chain, %({param_key})s)")-- elif key == "tag_name":- if operator not in ("exact", "is_not"):- raise exceptions.ValidationError(- 'Filtering by element tag only supports operators "equals" and "doesn\'t equal" currently.'- )- tag_names = cast(list[str | int], value) if isinstance(value, list) else [value]- for idx, tag_name in enumerate(tag_names):- if not tag_name: # Skip empty tags- continue- if not isinstance(tag_name, str):- raise exceptions.ValidationError("Tag name must be a string")- param_key = f"{prepend}_{idx}_tag_name_regex"- params[param_key] = rf"(^|;){tag_name}(\.|$|;|:)"- combination_conditions.append(f"match(elements_chain, %({param_key})s)")-- elif key in ["href", "text"]:- ok_values = process_ok_values(value, operator)- for idx, value in enumerate(ok_values):- optional_flag = "(?i)" if operator.endswith("icontains") else ""- param_key = f"{prepend}_{key}_{idx}_attributes_regex"- params[param_key] = f'{optional_flag}({key}="{value}")'- combination_conditions.append(f"match(elements_chain, %({param_key})s)")-- else:- raise ValueError(f'Invalid element filtering key "{key}"')-- if combination_conditions:- return (- f"{'NOT ' if operator in NEGATED_OPERATORS else ''}({' OR '.join(combination_conditions)})",- params,- )- else:- # If there are no values to filter by, this either matches nothing (for non-negated operators like "equals"),- # or everything (for negated operators like "doesn't equal")- return "0 = 191" if operator not in NEGATED_OPERATORS else "", {}---def _build_group_key_filter(- prop: Property, idx: int, prepend: str, property_operator: str-) -> tuple[str, dict[str, Any]]:- """- Build SQL filter for $group_key property targeting the group_key column directly.-- Args:- prop: Property object with $group_key- idx: Index for parameter naming- prepend: Prefix for parameter keys- property_operator: SQL operator (AND/OR)-- Returns:- Tuple of (filter_query, filter_params)- """- operator = prop.operator or "exact"- if prop.negation:- operator = negate_operator(operator)-- param_key = f"{prepend}_group_key_{idx}"- param_value = prop.value-- if operator == "exact":- filter_query = f"{property_operator} group_key = %({param_key})s"- elif operator == "is_not":- filter_query = f"{property_operator} group_key != %({param_key})s"- elif operator == "icontains":- filter_query = f"{property_operator} group_key ILIKE %({param_key})s"- param_value = f"%{prop.value}%"- elif operator == "not_icontains":- filter_query = f"{property_operator} NOT (group_key ILIKE %({param_key})s)"- param_value = f"%{prop.value}%"- elif operator in ("starts_with", "ends_with"):- filter_query = f"{property_operator} group_key ILIKE %({param_key})s"- param_value = f"{prop.value}%" if operator == "starts_with" else f"%{prop.value}"- elif operator in ("not_starts_with", "not_ends_with"):- filter_query = f"{property_operator} NOT (group_key ILIKE %({param_key})s)"- param_value = f"{prop.value}%" if operator == "not_starts_with" else f"%{prop.value}"- elif operator in ("regex", "not_regex"):- regex_func = "match" if operator == "regex" else "NOT match"- filter_query = f"{property_operator} {regex_func}(group_key, %({param_key})s)"- else:- # Default to exact match for unsupported operators- filter_query = f"{property_operator} group_key = %({param_key})s"-- filter_params = {param_key: param_value}- return filter_query, filter_params---def process_ok_values(ok_values: Any, operator: OperatorType) -> list[str]:- if operator.endswith("_set"):- return [r'[^"]+']- else:- # Make sure ok_values is a list- ok_values = cast(list[str], [str(val) for val in ok_values]) if isinstance(ok_values, list) else [ok_values]- # Escape double quote characters, since e.g. text 'foo="bar"' is represented as text="foo=\"bar\""- # in the elements chain- ok_values = [text.replace('"', r"\"") for text in ok_values]- if operator.endswith("icontains"):- # Process values for case-insensitive-contains matching by way of regex,- # making sure matching scope is limited to between double quotes- return [rf'[^"]*{re.escape(text)}[^"]*' for text in ok_values]- if operator.endswith("regex"):- # Use values as-is in case of regex matching- return ok_values- # For all other operators escape regex-meaningful sequences- return [re.escape(text) for text in ok_values]--def _chain_escaped_value(value: str) -> str:# A quoted value in the chain escapes double quotes as \" (_escape in# posthog/models/element/element.py). A selector can write the quote either@@ -989,24 +217,6 @@ def count_hogql_properties(return counter-def get_session_property_filter_statement(prop: Property, idx: int, prepend: str = "") -> tuple[str, dict[str, Any]]:- if prop.key == "$session_duration":- try:- duration = float(cast(str | int, prop.value))- except ValueError:- raise (exceptions.ValidationError(f"$session_duration value must be a number. Received '{prop.value}'"))- value = f"session_duration_value{prepend}_{idx}"-- operator = get_count_operator(prop.operator)- return (- f"{SessionQuery.SESSION_TABLE_ALIAS}.session_duration {operator} %({value})s",- {value: duration},- )-- else:- raise exceptions.ValidationError(f"Session property '{prop.key}' is only valid in HogQL queries.")--def clear_excess_levels(prop: Union["PropertyGroup", "Property"], skip=False):if isinstance(prop, PropertyGroup):if len(prop.values) == 1:diff --git a/posthog/models/test/test_event_model.py b/posthog/models/test/test_event_model.pyindex 335d477c365b..7209bdb615d5 100644--- a/posthog/models/test/test_event_model.py+++ b/posthog/models/test/test_event_model.py@@ -6,683 +6,11 @@ from django.test import SimpleTestCasefrom parameterized import parameterized-from posthog.models import Element, Organization+from posthog.models import Elementfrom posthog.models.element.element import elements_to_stringfrom posthog.models.event import Selectorfrom posthog.models.property.util import build_selector_regex-from products.actions.backend.models.action import Action---def _create_action(team, steps):- return Action.objects.create(team=team, steps_json=steps)---# :TODO: Move ee/clickhouse/models/test/test_action.py here-def filter_by_actions_factory(_create_event, _create_person, _get_events_for_action):- class TestFilterByActions(BaseTest):- def test_filter_with_selector_direct_decendant_ordering(self):- all_events = self._setup_action_selector_events()- action = _create_action(- self.team,- [- {"event": "$autocapture", "selector": "div > div > a"},- {- "event": "$autocapture",- "selector": "div > a.somethingthatdoesntexist",- },- ],- )-- self.assertActionEventsMatch(action, [all_events[1]])-- def test_filter_with_selector_nth_child(self):- all_events = self._setup_action_selector_events()- action = _create_action(- self.team,- [{"event": "$autocapture", "selector": "div > a:nth-child(2)"}],- )-- self.assertActionEventsMatch(action, [all_events[1]])-- def test_filter_with_selector_id(self):- all_events = self._setup_action_selector_events()- action = _create_action(self.team, [{"event": "$autocapture", "selector": "[id='someId']"}])-- self.assertActionEventsMatch(action, [all_events[1]])-- def test_filter_with_selector_nested(self):- all_events = self._setup_action_selector_events()- action = _create_action(self.team, [{"event": "$autocapture", "selector": "[id='nested'] a"}])-- self.assertActionEventsMatch(action, [all_events[0]])-- def test_filter_with_selector_star(self):- all_events = self._setup_action_selector_events()- action = _create_action(self.team, [{"event": "$autocapture", "selector": "div *"}])-- self.assertActionEventsMatch(action, all_events)-- def _setup_action_selector_events(self):- _create_person(distinct_ids=["whatever"], team=self.team)-- event1 = _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- elements=[- Element(- tag_name="a",- href="/a-url",- nth_child=1,- nth_of_type=0,- attr_class=["one-class"],- ),- Element(tag_name="button", nth_child=0, nth_of_type=0),- Element(- # Important that in this hierarchy the div is sandwiched between button and section.- # This way makes sure that any conditions which should match this element also work- # if the element is neither first nor last in the hierarchy.- tag_name="div",- nth_child=0,- nth_of_type=0,- ),- Element(tag_name="section", nth_child=0, nth_of_type=0, attr_id="nested"),- ],- )-- event2 = _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- elements=[- Element(tag_name="a", nth_child=2, nth_of_type=0, attr_id="someId"),- Element(tag_name="div", nth_child=0, nth_of_type=0),- Element(tag_name="div", nth_child=0, nth_of_type=0),- Element(tag_name="div", nth_child=0, nth_of_type=0),- Element(tag_name="div", nth_child=0, nth_of_type=0),- Element(tag_name="div", nth_child=0, nth_of_type=0),- Element(tag_name="div", nth_child=0, nth_of_type=0),- # make sure elements don't get double counted if they're part of the same event- Element(href="/a-url-2", nth_child=0, nth_of_type=0),- ],- )-- event3 = _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- elements=[- Element(tag_name="a", nth_child=3, nth_of_type=0),- Element(tag_name="div", nth_child=0, nth_of_type=0),- ],- )-- # make sure other teams' data doesn't get mixed in- team2 = Organization.objects.bootstrap(None)[2]- _create_event(- event="$autocapture",- team=team2,- distinct_id="whatever",- elements=[- Element(tag_name="a", nth_child=2, nth_of_type=0, attr_id="someId"),- Element(tag_name="div", nth_child=0, nth_of_type=0),- ],- )-- return event1, event2, event3-- def assertActionEventsMatch(self, action, expected_events):- events = _get_events_for_action(action)-- self.assertCountEqual([e.uuid for e in events], list(expected_events))-- def test_with_normal_filters(self):- # this test also specifically tests the back to back receipt of- # the same type of events by action to test the query cache- _create_person(distinct_ids=["whatever"], team=self.team)- # _create_person(distinct_ids=["whatever2"], team=self.team)-- action1 = Action.objects.create(- team=self.team,- steps_json=[- {"event": "$autocapture", "href": "/a-url", "selector": "a"},- {"event": "$autocapture", "href": "/a-url-2"},- ],- )-- team2 = Organization.objects.bootstrap(None)[2]- event1_uuid = _create_event(- team=self.team,- event="$autocapture",- distinct_id="whatever",- elements=[- Element(- tag_name="a",- href="/a-url",- text="some_text",- nth_child=0,- nth_of_type=0,- )- ],- )-- event2_uuid = _create_event(- team=self.team,- event="$autocapture",- distinct_id="whatever2",- elements=[- Element(- tag_name="a",- href="/a-url",- text="some_text",- nth_child=0,- nth_of_type=0,- )- ],- )-- event3_uuid = _create_event(- team=self.team,- event="$autocapture",- distinct_id="whatever",- elements=[- Element(- tag_name="a",- href="/a-url-2",- text="some_other_text",- nth_child=0,- nth_of_type=0,- ),- # make sure elements don't get double counted if they're part of the same event- Element(- tag_name="div",- text="some_other_text",- nth_child=0,- nth_of_type=0,- ),- ],- )-- event4_uuid = _create_event(- team=self.team,- event="$autocapture",- distinct_id="whatever2",- elements=[- Element(- tag_name="a",- href="/a-url-2",- text="some_other_text",- nth_child=0,- nth_of_type=0,- ),- # make sure elements don't get double counted if they're part of the same event- Element(- tag_name="div",- text="some_other_text",- nth_child=0,- nth_of_type=0,- ),- ],- )-- # team leakage- _create_event(- team=team2,- event="$autocapture",- distinct_id="whatever2",- elements=[- Element(- tag_name="a",- href="/a-url",- text="some_other_text",- nth_child=0,- nth_of_type=0,- )- ],- )- _create_event(- team=team2,- event="$autocapture",- distinct_id="whatever2",- elements=[- Element(- tag_name="a",- href="/a-url-2",- text="some_other_text",- nth_child=0,- nth_of_type=0,- )- ],- )-- events = _get_events_for_action(action1)- self.assertEqual(len(events), 4)- self.assertEqual(events[0].uuid, event4_uuid)- self.assertEqual(events[1].uuid, event3_uuid)- self.assertEqual(events[2].uuid, event2_uuid)- self.assertEqual(events[3].uuid, event1_uuid)-- def test_with_href_contains(self):- _create_person(distinct_ids=["whatever"], team=self.team)-- action1 = Action.objects.create(- team=self.team,- steps_json=[- {- "event": "$autocapture",- "href": "/a-url",- "href_matching": "contains",- "selector": "a",- }- ],- )-- event1_uuid = _create_event(- team=self.team,- event="$autocapture",- distinct_id="whatever",- elements=[- Element(- tag_name="a",- href="/a-url",- text="some_text",- nth_child=0,- nth_of_type=0,- )- ],- )-- event2_uuid = _create_event(- team=self.team,- event="$autocapture",- distinct_id="whatever2",- elements=[- Element(- tag_name="a",- href="https://google.com/a-url",- text="some_text",- nth_child=0,- nth_of_type=0,- )- ],- )-- event3_uuid = _create_event(- team=self.team,- event="$autocapture",- distinct_id="whatever",- elements=[- Element(- tag_name="a",- href="/a-url-2",- text="some_other_text",- nth_child=0,- nth_of_type=0,- ),- # make sure elements don't get double counted if they're part of the same event- Element(- tag_name="div",- text="some_other_text",- nth_child=0,- nth_of_type=0,- ),- ],- )-- _create_event( # Not matched because href is /b-url not /a-url- team=self.team,- event="$autocapture",- distinct_id="whatever2",- elements=[- Element(- tag_name="a",- href="/b-url",- text="some_other_text",- nth_child=0,- nth_of_type=0,- ),- # make sure elements don't get double counted if they're part of the same event- Element(- tag_name="div",- text="some_other_text",- nth_child=0,- nth_of_type=0,- ),- ],- )-- events = _get_events_for_action(action1)- self.assertEqual(len(events), 3)- self.assertEqual(events[0].uuid, event3_uuid)- self.assertEqual(events[1].uuid, event2_uuid)- self.assertEqual(events[2].uuid, event1_uuid)-- def test_with_class(self):- _create_person(distinct_ids=["whatever"], team=self.team)- action1 = Action.objects.create(- team=self.team,- steps_json=[- {- "event": "$autocapture",- "selector": "a.nav-link.active",- "tag_name": "a",- }- ],- )- event1_uuid = _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- elements=[- Element(tag_name="span", attr_class=None),- # crazy-class makes sure we don't require exact matching of the entire class string- Element(tag_name="a", attr_class=["active", "crazy-class", "nav-link"]),- ],- )- # no class- _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- elements=[- Element(tag_name="span", attr_class=None),- Element(tag_name="a", attr_class=None),- ],- )-- events = _get_events_for_action(action1)- self.assertEqual(events[0].uuid, event1_uuid)- self.assertEqual(len(events), 1)-- def test_with_class_with_escaped_symbols(self):- _create_person(distinct_ids=["whatever"], team=self.team)- action1 = Action.objects.create(- team=self.team,- steps_json=[- {- "event": "$autocapture",- "selector": "a.na\\v-link:b@ld",- "tag_name": "a",- }- ],- )- event1_uuid = _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- elements=[- Element(tag_name="span", attr_class=None),- Element(tag_name="a", attr_class=["na\\v-link:b@ld"]),- ],- )-- events = _get_events_for_action(action1)- self.assertEqual(events[0].uuid, event1_uuid)- self.assertEqual(len(events), 1)-- def test_with_class_with_escaped_slashes(self):- _create_person(distinct_ids=["whatever"], team=self.team)- action1 = Action.objects.create(- team=self.team,- steps_json=[- {- "event": "$autocapture",- "selector": "a.na\\\\\\v-link:b@ld",- "tag_name": "a",- }- ],- )- event1_uuid = _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- elements=[- Element(tag_name="span", attr_class=None),- Element(tag_name="a", attr_class=["na\\\\\\v-link:b@ld"]),- ],- )-- events = _get_events_for_action(action1)- self.assertEqual(events[0].uuid, event1_uuid)- self.assertEqual(len(events), 1)-- def test_with_tag_matching_class_selector(self):- _create_person(distinct_ids=["whatever"], team=self.team)- action1 = Action.objects.create(- team=self.team,- steps_json=[- {- "event": "$autocapture",- "selector": "input", # This should ONLY match the tag, but not a class named `input`- }- ],- )- event_matching_tag_uuid = _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- elements=[- Element(tag_name="span", attr_class=None),- Element(tag_name="input", attr_class=["button"]), # Should match- ],- )- _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- elements=[- Element(tag_name="span", attr_class=None),- Element(tag_name="button", attr_class=["input"]), # Cannot match- ],- )-- events = _get_events_for_action(action1)- self.assertEqual(len(events), 1)- self.assertEqual(events[0].uuid, event_matching_tag_uuid)-- def test_attributes(self):- _create_person(distinct_ids=["whatever"], team=self.team)- event1_uuid = _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- elements=[Element(tag_name="button", attributes={"attr__data-id": "123"})],- )-- action1 = Action.objects.create(- team=self.team, steps_json=[{"event": "$autocapture", "selector": '[data-id="123"]'}]- )-- events = _get_events_for_action(action1)- self.assertEqual(len(events), 1)- self.assertEqual(events[0].uuid, event1_uuid)-- def test_filter_events_by_url(self):- _create_person(distinct_ids=["whatever"], team=self.team)- action1 = Action.objects.create(- team=self.team,- steps_json=[- {- "event": "$autocapture",- "url": "https://posthog.com/feedback/123",- "url_matching": "exact",- },- {"event": "$autocapture", "href": "/a-url-2"},- ],- )-- action2 = Action.objects.create(- team=self.team,- steps_json=[- {- "event": "$autocapture",- "url": "123",- "url_matching": "contains",- }- ],- )-- action3 = Action.objects.create(- team=self.team,- steps_json=[- {- "event": "$autocapture",- "url": "https://posthog.com/%/123",- "url_matching": "contains",- }- ],- )-- action4 = Action.objects.create(- team=self.team,- steps_json=[- {- "event": "$autocapture",- "url": "/123$",- "url_matching": "regex",- }- ],- )-- _create_event(team=self.team, distinct_id="whatever", event="$autocapture")- event2_uuid = _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- properties={"$current_url": "https://posthog.com/feedback/123"},- elements=[- Element(- tag_name="div",- text="some_other_text",- nth_child=0,- nth_of_type=0,- )- ],- )-- events = _get_events_for_action(action1)- self.assertEqual(events[0].uuid, event2_uuid)- self.assertEqual(len(events), 1)-- events = _get_events_for_action(action2)- self.assertEqual(events[0].uuid, event2_uuid)- self.assertEqual(len(events), 1)-- events = _get_events_for_action(action3)- self.assertEqual(events[0].uuid, event2_uuid)- self.assertEqual(len(events), 1)-- events = _get_events_for_action(action4)- self.assertEqual(events[0].uuid, event2_uuid)- self.assertEqual(len(events), 1)-- def test_person_with_different_distinct_id(self):- action_watch_movie = Action.objects.create(- team=self.team,- name="watched movie",- steps_json=[- {- "tag_name": "a",- "href": "/movie",- "event": "$autocapture",- }- ],- )-- _create_person(distinct_ids=["anonymous_user", "is_now_signed_up"], team=self.team)- _create_event(- distinct_id="anonymous_user",- team=self.team,- elements=[Element(tag_name="a", href="/movie")],- event="$autocapture",- )-- event_watched_movie_uuid = _create_event(- distinct_id="is_now_signed_up",- team=self.team,- elements=[Element(tag_name="a", href="/movie")],- event="$autocapture",- )-- events = _get_events_for_action(action_watch_movie)- self.assertEqual(events[0].uuid, event_watched_movie_uuid)- self.assertEqual(events[0].distinct_id, "is_now_signed_up")-- def test_no_person_leakage_from_other_teams(self):- action_watch_movie = Action.objects.create(- team=self.team, name="watched movie", steps_json=[{"event": "user signed up"}]- )-- _create_person(distinct_ids=["anonymous_user"], team=self.team)- _create_event(event="user signed up", distinct_id="anonymous_user", team=self.team)-- team2 = Organization.objects.bootstrap(None)[2]- _create_person(distinct_ids=["anonymous_user2"], team=team2)-- events = _get_events_for_action(action_watch_movie)- self.assertEqual(len(events), 1)- self.assertEqual(events[0].distinct_id, "anonymous_user")-- def test_person_property(self):- _create_person(- team=self.team,- distinct_ids=["person1"],- properties={"$browser": "Chrome"},- )- _create_person(team=self.team, distinct_ids=["person2"])- _create_event(event="$pageview", distinct_id="person1", team=self.team)- _create_event(event="$pageview", distinct_id="person2", team=self.team)- action = Action.objects.create(- name="pageview",- team=self.team,- steps_json=[- {- "event": "$pageview",- "properties": [{"key": "$browser", "value": "Chrome", "type": "person"}],- }- ],- )- events = _get_events_for_action(action)- self.assertEqual(len(events), 1)-- def test_no_steps(self):- _create_person(distinct_ids=["whatever"], team=self.team)- _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- elements=[Element(tag_name="button", attributes={"attr__data-id": "123"})],- )- action1 = Action.objects.create(team=self.team)-- events = _get_events_for_action(action1)- self.assertEqual(len(events), 0)-- def test_empty_selector_same_as_null(self):- _create_person(distinct_ids=["whatever"], team=self.team)- action_null_selector = Action.objects.create(- team=self.team, steps_json=[{"event": "$autocapture", "selector": None}]- )- action_empty_selector = Action.objects.create(- team=self.team, steps_json=[{"event": "$autocapture", "selector": ""}]- )- event1_uuid = _create_event(- event="$autocapture",- team=self.team,- distinct_id="whatever",- elements=[Element(tag_name="span", attr_class=None)],- )-- events_null_selector = _get_events_for_action(action_null_selector)- self.assertEqual(events_null_selector[0].uuid, event1_uuid)- self.assertEqual(len(events_null_selector), 1)-- events_empty_selector = _get_events_for_action(action_empty_selector)- self.assertEqual(events_empty_selector, events_null_selector)-- return TestFilterByActions-class TestSelectors(BaseTest):def test_selector_splitting(self):diff --git a/posthog/queries/base.py b/posthog/queries/base.pyindex 9efdd263006e..647c5c95fc95 100644--- a/posthog/queries/base.py+++ b/posthog/queries/base.py@@ -1,109 +1,13 @@import reimport datetime-from collections.abc import Callable-from typing import Any, Optional, TypeVar+from typing import Optionalfrom zoneinfo import ZoneInfofrom dateutil import parserfrom dateutil.relativedelta import relativedelta-from rest_framework.exceptions import ValidationError-from posthog.models.filters.filter import Filter-from posthog.models.filters.path_filter import PathFilterfrom posthog.models.property.property import ValueT-from posthog.models.team import Teamfrom posthog.queries.util import convert_to_datetime_aware-from posthog.utils import get_compare_period_dates--FilterType = TypeVar("FilterType", Filter, PathFilter)---def determine_compared_filter(filter: FilterType) -> FilterType:- if not filter.date_to or not filter.date_from:- raise ValidationError("You need date_from and date_to to compare")- date_from, date_to = get_compare_period_dates(- filter.date_from,- filter.date_to,- filter.date_from_delta_mapping,- filter.date_to_delta_mapping,- filter.interval,- )-- return filter.shallow_clone({"date_from": date_from.isoformat(), "date_to": date_to.isoformat()})---def convert_to_comparison(trend_entities: list[dict[str, Any]], filter, label: str) -> list[dict[str, Any]]:- for entity in trend_entities:- labels = [- "{} {}".format(filter.interval if filter.interval is not None else "day", i)- for i in range(len(entity["labels"]))- ]- entity.update(- {- "labels": labels,- "days": entity["days"],- "label": entity["label"],- "compare_label": label,- "compare": True,- }- )- return trend_entities---"""- handle_compare takes an Entity, Filter and a callable.- It'll automatically create a new entity with the 'current' and 'previous' labels and automatically pick the right date_from and date_to filters .- It will then call func(entity, filter, team_id).-"""---def handle_compare(filter, func: Callable, team: Team, **kwargs) -> list:- all_entities = []- base_entitites = func(filter=filter, team=team, **kwargs)- if filter.compare:- base_entitites = convert_to_comparison(base_entitites, filter, "current")- all_entities.extend(base_entitites)-- compared_filter = determine_compared_filter(filter)- comparison_entities = func(filter=compared_filter, team=team, **kwargs)- comparison_entities = convert_to_comparison(comparison_entities, compared_filter, "previous")- all_entities.extend(comparison_entities)- else:- all_entities.extend(base_entitites)- return all_entities---def determine_parsed_incoming_date(- value: ValueT | datetime.date | datetime.datetime | float,-) -> datetime.datetime | None:- # This parses the incoming date value. The range of possibilities is only limited by our customers imagination, but usually- # take the form of a string, a unix timestamp, or a datetime object.- if isinstance(value, datetime.datetime):- return convert_to_datetime_aware(value)-- if isinstance(value, datetime.date):- return convert_to_datetime_aware(datetime.datetime.combine(value, datetime.time.min))-- if isinstance(value, int) or isinstance(value, float):- return datetime.datetime.fromtimestamp(value, tz=ZoneInfo("UTC"))- if isinstance(value, str):- try:- parsed = parser.parse(value)- return convert_to_datetime_aware(parsed)- except Exception:- try:- # This might be a Unix timestamp passed as a string in milliseconds- parsed_date = float(value)- return datetime.datetime.fromtimestamp(parsed_date, tz=ZoneInfo("UTC"))- except Exception:- try:- # This might be a Unix timestamp passed as a string in seconds- parsed_date = int(value)- return datetime.datetime.fromtimestamp(parsed_date, tz=ZoneInfo("UTC"))- except Exception:- pass-- return Nonedef determine_parsed_date_for_property_matching(value: ValueT) -> datetime.datetime | None:diff --git a/posthog/queries/person_distinct_id_query.py b/posthog/queries/person_distinct_id_query.pydeleted file mode 100644index 5cf86f88c3b8..000000000000--- a/posthog/queries/person_distinct_id_query.py+++ /dev/null@@ -1,16 +0,0 @@-from posthog.models.event.new_events_schema import events_read_table-from posthog.models.person.sql import GET_TEAM_PERSON_DISTINCT_IDS---# TODO: Remove the `team_id` param, which is no longer needed – we do all the value interpolation at query time-def get_team_distinct_ids_query(- team_id: int, *, relevant_events_conditions: str = "", use_new_events_schema: bool = False-) -> str:- events_table = events_read_table(use_new_events_schema)- relevant_events_filter = (- f"AND distinct_id IN (SELECT distinct_id FROM {events_table} WHERE team_id = %(team_id)s {relevant_events_conditions})"- if relevant_events_conditions- else ""- )-- return GET_TEAM_PERSON_DISTINCT_IDS.format(relevant_events_filter=relevant_events_filter)diff --git a/posthog/queries/test/test_base.py b/posthog/queries/test/test_base.pyindex 282360e2bc59..0c647e5374bd 100644--- a/posthog/queries/test/test_base.py+++ b/posthog/queries/test/test_base.py@@ -1,63 +1,11 @@import datetime-from zoneinfo import ZoneInfoimport unittestfrom freezegun import freeze_time-from posthog.test.base import APIBaseTestfrom dateutil import tz-from posthog.models.filters.path_filter import PathFilter-from posthog.queries.base import determine_parsed_incoming_date, relative_date_parse_for_feature_flag_matching---class TestBase(APIBaseTest):- def test_determine_compared_filter(self):- from posthog.queries.base import determine_compared_filter-- filter = PathFilter(data={"date_from": "2020-05-23", "date_to": "2020-05-29"}, team=self.team)- compared_filter = determine_compared_filter(filter)-- self.assertIsInstance(compared_filter, PathFilter)- self.assertLessEqual(- {- "date_from": "2020-05-16T00:00:00+00:00",- "date_to": "2020-05-22T23:59:59.999999+00:00",- }.items(),- compared_filter.to_dict().items(),- )---class TestDetermineParsedIncomingDate(unittest.TestCase):- def test_determine_parsed_incoming_date_with_int_timestamp(self):- self.assertEqual(- determine_parsed_incoming_date(1836277747), datetime.datetime(2028, 3, 10, 5, 9, 7, tzinfo=ZoneInfo("UTC"))- )-- def test_determine_parsed_incoming_date_with_float_timestamp(self):- timestamp = 1836277747.867530- expected = datetime.datetime(2028, 3, 10, 5, 9, 7, 867530, tzinfo=ZoneInfo("UTC"))- self.assertEqual(determine_parsed_incoming_date(timestamp), expected)-- def test_determine_parsed_incoming_date_with_string_timestamp(self):- parsed_date = determine_parsed_incoming_date("1836277747")- expected = datetime.datetime(2028, 3, 10, 5, 9, 7, tzinfo=ZoneInfo("UTC"))- self.assertEqual(parsed_date, expected)-- def test_determine_parsed_incoming_date_with_datetime(self):- parsed_date = determine_parsed_incoming_date(datetime.datetime(2028, 3, 10, 5, 9, 7, tzinfo=ZoneInfo("UTC")))- expected = datetime.datetime(2028, 3, 10, 5, 9, 7, tzinfo=ZoneInfo("UTC"))- self.assertEqual(parsed_date, expected)-- def test_determine_parsed_incoming_date_with_string_date(self):- parsed_date = determine_parsed_incoming_date("2028-03-10T05:09:07Z")- expected = datetime.datetime(2028, 3, 10, 5, 9, 7, tzinfo=ZoneInfo("UTC"))- self.assertEqual(parsed_date, expected)-- def test_determine_parsed_date_for_property_matching_with_string_fractional_timestamp(self):- timestamp = "1836277747.867530"- expected = datetime.datetime(2028, 3, 10, 5, 9, 7, 867530, tzinfo=ZoneInfo("UTC"))- self.assertEqual(determine_parsed_incoming_date(timestamp), expected)+from posthog.queries.base import relative_date_parse_for_feature_flag_matchingclass TestRelativeDateParsing(unittest.TestCase):diff --git a/posthog/queries/util.py b/posthog/queries/util.pyindex f2baf580c18f..fd29115b7759 100644--- a/posthog/queries/util.py+++ b/posthog/queries/util.py@@ -1,31 +1,14 @@-import jsonfrom datetime import UTC, datetime-from enum import Enum, autofrom typing import Any, Optional, Union, overloadfrom zoneinfo import ZoneInfofrom rest_framework.exceptions import ValidationError-from posthog.interval_specs import UnsupportedIntervalError, get_interval_func, get_trunc_func+from posthog.interval_specs import UnsupportedIntervalError, get_trunc_funcfrom posthog.models.team.team import Team, WeekStartDayfrom posthog.schema_enums import PersonsOnEventsMode-class PersonPropertiesMode(Enum):- USING_SUBQUERY = auto()- USING_PERSON_PROPERTIES_COLUMN = auto()- DIRECT_ON_EVENTS = auto()- """- Get person property from the events table (persons-on-events v1 - no person ID overrides),- selecting the latest version of the person.- """- DIRECT_ON_EVENTS_WITH_POE_V2 = auto()- """- Get person property from the events table (persons-on-events v2 - accounting for person ID overrides),- selecting the latest version of the person.- """--@overloaddef alias_poe_mode_for_legacy(persons_on_events_mode: PersonsOnEventsMode) -> PersonsOnEventsMode: ...@overload@@ -85,29 +68,6 @@ def get_trunc_func_ch(period: Optional[str]) -> str:raise ValidationError(f"Period {period} is unsupported.")-def get_interval_func_ch(period: Optional[str]) -> str:- try:- return get_interval_func(period)- except UnsupportedIntervalError:- raise ValidationError(f"Interval {period} is unsupported.")---def get_time_in_seconds_for_period(period: Optional[str]) -> str:- if period is None:- period = "day"- seconds_in_period = TIME_IN_SECONDS.get(period.lower())- if seconds_in_period is None:- raise ValidationError(f"Interval {period} is unsupported.")- return seconds_in_period---def deep_dump_object(params: dict[str, Any]) -> dict[str, Any]:- for key in params:- if isinstance(params[key], dict) or isinstance(params[key], list):- params[key] = json.dumps(params[key])- return params--def convert_to_datetime_aware(date_obj):if date_obj.tzinfo is None:date_obj = date_obj.replace(tzinfo=UTC)@@ -135,11 +95,3 @@ def correct_result_for_sampling(result = round(value * (1 / sampling_factor))return result---def get_person_properties_mode(team: Team) -> PersonPropertiesMode:- if team.person_on_events_mode == PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS:- return PersonPropertiesMode.DIRECT_ON_EVENTS_WITH_POE_V2- if team.person_on_events_mode == PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS:- return PersonPropertiesMode.DIRECT_ON_EVENTS- return PersonPropertiesMode.USING_PERSON_PROPERTIES_COLUMNdiff --git a/posthog/session_recordings/queries/session_query.py b/posthog/session_recordings/queries/session_query.pydeleted file mode 100644index eb856194806d..000000000000--- a/posthog/session_recordings/queries/session_query.py+++ /dev/null@@ -1,75 +0,0 @@-from typing import Optional, Union--from posthog.models import Filter-from posthog.models.filters.path_filter import PathFilter-from posthog.models.filters.retention_filter import RetentionFilter-from posthog.models.filters.stickiness_filter import StickinessFilter-from posthog.models.team import Team-from posthog.queries.query_date_range import QueryDateRange---class SessionQuery:- """- Query class responsible for creating and joining sessions- """-- SESSION_TABLE_ALIAS = "sessions"-- _filter: Union[Filter, PathFilter, RetentionFilter, StickinessFilter]- _team_id: int- _session_id_alias: Optional[str]-- def __init__(- self,- filter: Union[Filter, PathFilter, RetentionFilter, StickinessFilter],- team: Team,- session_id_alias=None,- ) -> None:- self._filter = filter- self._team = team- self._session_id_alias = session_id_alias-- def get_query(self) -> tuple[str, dict]:- params = {"team_id": self._team.pk}-- query_date_range = QueryDateRange(filter=self._filter, team=self._team, should_round=False)- parsed_date_from, date_from_params = query_date_range.date_from- parsed_date_to, date_to_params = query_date_range.date_to- params.update(date_from_params)- params.update(date_to_params)-- return (- f"""- SELECT- "$session_id"{f" AS {self._session_id_alias}" if self._session_id_alias else ""},- dateDiff('second',min(timestamp), max(timestamp)) as session_duration- FROM- events- WHERE- {self._session_id_alias or '"$session_id"'} != ''- AND team_id = %(team_id)s- {parsed_date_from} - INTERVAL 24 HOUR- {parsed_date_to} + INTERVAL 24 HOUR- GROUP BY {self._session_id_alias or '"$session_id"'}- """,- params,- )-- @property- def is_used(self):- "Returns whether any columns from session are actually being queried"- if (- not isinstance(self._filter, StickinessFilter) and self._filter.breakdown_type == "session"- ): # stickiness doesn't have breakdown_type- return True-- if any(prop.type == "session" for prop in self._filter.property_groups.flat):- return True- if any(prop.type == "session" for entity in self._filter.entities for prop in entity.property_groups.flat):- return True-- if any(entity.math_property == "$session_duration" for entity in self._filter.entities):- # TODO: generalise this to work for math_property_type, not just sessions, when we add more properties- return True-- return Falsediff --git a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambrindex bf5602936621..93302c011230 100644--- a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr+++ b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr@@ -5619,55 +5619,12 @@# name: TestSessionRecordingsListFromQuery_0.test_filter_users_from_excluded_cohort.1'''- SELECT DISTINCT p.id- FROM- (SELECT *- FROM person- JOIN- (SELECT id,- max(version) as version,- max(is_deleted) as is_deleted- FROM person- WHERE team_id = 99999- GROUP BY id) as person_max ON person.id = person_max.id- AND person.version = person_max.version- WHERE team_id = 99999- AND person_max.is_deleted = 0) AS p- INNER JOIN- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0) AS pdi ON p.id = pdi.person_id+ SELECT DISTINCT person_id+ FROM cohortpeopleWHERE team_id = 99999- AND (pdi.distinct_id IN- (SELECT distinct_id- FROM- (SELECT person_distinct_ids.distinct_id AS distinct_id- FROM- (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id,- person_distinct_id2.distinct_id AS distinct_id- FROM person_distinct_id2- WHERE equals(person_distinct_id2.team_id, 99999)- GROUP BY person_distinct_id2.distinct_id- HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids- WHERE in(person_distinct_ids.person_id, (- (SELECT persons.id AS id- FROM- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, '$is_internal'), ''), 'null'), '^"|"$', '')), person.version), 1) AS `properties___$is_internal`,- person.id AS id- FROM person- WHERE and(equals(person.team_id, 99999), in(id,- (SELECT where_optimization.id AS id- FROM person AS where_optimization- WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, '$is_internal'), ''), 'null'), '^"|"$', ''), 'yes'), 0)))))- GROUP BY person.id- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons- WHERE ifNull(equals(persons.`properties___$is_internal`, 'yes'), 0)- ORDER BY persons.id ASC SETTINGS optimize_aggregation_in_order=1,- join_algorithm='auto')))- LIMIT 1000000000)))+ AND cohort_id = 99999+ AND version = 0+ ORDER BY person_id'''# ---# name: TestSessionRecordingsListFromQuery_0.test_filter_users_from_excluded_cohort.2@@ -5781,55 +5738,12 @@# name: TestSessionRecordingsListFromQuery_0.test_filter_users_from_excluded_cohort_no_events.1'''- SELECT DISTINCT p.id- FROM- (SELECT *- FROM person- JOIN- (SELECT id,- max(version) as version,- max(is_deleted) as is_deleted- FROM person- WHERE team_id = 99999- GROUP BY id) as person_max ON person.id = person_max.id- AND person.version = person_max.version- WHERE team_id = 99999- AND person_max.is_deleted = 0) AS p- INNER JOIN- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0) AS pdi ON p.id = pdi.person_id+ SELECT DISTINCT person_id+ FROM cohortpeopleWHERE team_id = 99999- AND (pdi.distinct_id IN- (SELECT distinct_id- FROM- (SELECT person_distinct_ids.distinct_id AS distinct_id- FROM- (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id,- person_distinct_id2.distinct_id AS distinct_id- FROM person_distinct_id2- WHERE equals(person_distinct_id2.team_id, 99999)- GROUP BY person_distinct_id2.distinct_id- HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids- WHERE in(person_distinct_ids.person_id, (- (SELECT persons.id AS id- FROM- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, '$is_internal'), ''), 'null'), '^"|"$', '')), person.version), 1) AS `properties___$is_internal`,- person.id AS id- FROM person- WHERE and(equals(person.team_id, 99999), in(id,- (SELECT where_optimization.id AS id- FROM person AS where_optimization- WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, '$is_internal'), ''), 'null'), '^"|"$', ''), 'yes'), 0)))))- GROUP BY person.id- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons- WHERE ifNull(equals(persons.`properties___$is_internal`, 'yes'), 0)- ORDER BY persons.id ASC SETTINGS optimize_aggregation_in_order=1,- join_algorithm='auto')))- LIMIT 1000000000)))+ AND cohort_id = 99999+ AND version = 0+ ORDER BY person_id'''# ---# name: TestSessionRecordingsListFromQuery_0.test_filter_users_from_excluded_cohort_no_events.2@@ -11610,55 +11524,12 @@# name: TestSessionRecordingsListFromQuery_1.test_filter_users_from_excluded_cohort.1'''- SELECT DISTINCT p.id- FROM- (SELECT *- FROM person- JOIN- (SELECT id,- max(version) as version,- max(is_deleted) as is_deleted- FROM person- WHERE team_id = 99999- GROUP BY id) as person_max ON person.id = person_max.id- AND person.version = person_max.version- WHERE team_id = 99999- AND person_max.is_deleted = 0) AS p- INNER JOIN- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0) AS pdi ON p.id = pdi.person_id+ SELECT DISTINCT person_id+ FROM cohortpeopleWHERE team_id = 99999- AND (pdi.distinct_id IN- (SELECT distinct_id- FROM- (SELECT person_distinct_ids.distinct_id AS distinct_id- FROM- (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id,- person_distinct_id2.distinct_id AS distinct_id- FROM person_distinct_id2- WHERE equals(person_distinct_id2.team_id, 99999)- GROUP BY person_distinct_id2.distinct_id- HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids- WHERE in(person_distinct_ids.person_id, (- (SELECT persons.id AS id- FROM- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, '$is_internal'), ''), 'null'), '^"|"$', '')), person.version), 1) AS `properties___$is_internal`,- person.id AS id- FROM person- WHERE and(equals(person.team_id, 99999), in(id,- (SELECT where_optimization.id AS id- FROM person AS where_optimization- WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, '$is_internal'), ''), 'null'), '^"|"$', ''), 'yes'), 0)))))- GROUP BY person.id- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons- WHERE ifNull(equals(persons.`properties___$is_internal`, 'yes'), 0)- ORDER BY persons.id ASC SETTINGS optimize_aggregation_in_order=1,- join_algorithm='auto')))- LIMIT 1000000000)))+ AND cohort_id = 99999+ AND version = 0+ ORDER BY person_id'''# ---# name: TestSessionRecordingsListFromQuery_1.test_filter_users_from_excluded_cohort.2@@ -11772,55 +11643,12 @@# name: TestSessionRecordingsListFromQuery_1.test_filter_users_from_excluded_cohort_no_events.1'''- SELECT DISTINCT p.id- FROM- (SELECT *- FROM person- JOIN- (SELECT id,- max(version) as version,- max(is_deleted) as is_deleted- FROM person- WHERE team_id = 99999- GROUP BY id) as person_max ON person.id = person_max.id- AND person.version = person_max.version- WHERE team_id = 99999- AND person_max.is_deleted = 0) AS p- INNER JOIN- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0) AS pdi ON p.id = pdi.person_id+ SELECT DISTINCT person_id+ FROM cohortpeopleWHERE team_id = 99999- AND (pdi.distinct_id IN- (SELECT distinct_id- FROM- (SELECT person_distinct_ids.distinct_id AS distinct_id- FROM- (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id,- person_distinct_id2.distinct_id AS distinct_id- FROM person_distinct_id2- WHERE equals(person_distinct_id2.team_id, 99999)- GROUP BY person_distinct_id2.distinct_id- HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids- WHERE in(person_distinct_ids.person_id, (- (SELECT persons.id AS id- FROM- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, '$is_internal'), ''), 'null'), '^"|"$', '')), person.version), 1) AS `properties___$is_internal`,- person.id AS id- FROM person- WHERE and(equals(person.team_id, 99999), in(id,- (SELECT where_optimization.id AS id- FROM person AS where_optimization- WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, '$is_internal'), ''), 'null'), '^"|"$', ''), 'yes'), 0)))))- GROUP BY person.id- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons- WHERE ifNull(equals(persons.`properties___$is_internal`, 'yes'), 0)- ORDER BY persons.id ASC SETTINGS optimize_aggregation_in_order=1,- join_algorithm='auto')))- LIMIT 1000000000)))+ AND cohort_id = 99999+ AND version = 0+ ORDER BY person_id'''# ---# name: TestSessionRecordingsListFromQuery_1.test_filter_users_from_excluded_cohort_no_events.2diff --git a/products/actions/backend/models/util.py b/products/actions/backend/models/util.pyindex 5053f998b991..c7b261012943 100644--- a/products/actions/backend/models/util.py+++ b/products/actions/backend/models/util.py@@ -2,168 +2,11 @@ from collections import (Counter,Counter as TCounter,)-from typing import Literal, Optional-from posthog.hogql.hogql import HogQLContext--from posthog.constants import AUTOCAPTURE_EVENTfrom posthog.models import Filter-from posthog.models.property import Property, PropertyIdentifier-from posthog.models.property.property import OperatorType-from posthog.queries.util import PersonPropertiesMode--from products.actions.backend.models.action import Action, ActionStepJSON---def format_action_filter_event_only(- action: Action,- prepend: str = "action",-) -> tuple[str, dict]:- """Return SQL for prefiltering events by action, i.e. down to only the events and without any other filters."""- events = action.get_step_events()- if not events:- # If no steps, it shouldn't match this part of the query- return "1=2", {}- if None in events:- # If selecting for "All events", disable entity pre-filtering- return "1 = 1", {}- entity_name = f"{prepend}_{action.pk}"- return f"event IN %({entity_name})s", {entity_name: sorted([x for x in events if x])}---def format_action_filter(- team_id: int,- action: Action,- hogql_context: HogQLContext,- prepend: str = "action",- filter_by_team: bool = True,- table_name: str = "",- person_properties_mode: PersonPropertiesMode = PersonPropertiesMode.USING_SUBQUERY,- person_id_joined_alias: str = "person_id",-) -> tuple[str, dict]:- """Return SQL for filtering events by action."""- # get action steps- params = {"team_id": action.team.pk} if filter_by_team else {}- steps = action.steps- if len(steps) == 0:- # If no steps, it shouldn't match this part of the query- return "1=2", {}-- or_queries = []- for index, step in enumerate(steps):- conditions: list[str] = []- # filter element- if step.event == AUTOCAPTURE_EVENT:- from posthog.models.property.util import filter_element # prevent circular import-- if step.selector:- element_condition, element_params = filter_element(- "selector", step.selector, prepend=f"{action.pk}_{index}{prepend}"- )- if element_condition:- conditions.append(element_condition)- params.update(element_params)- if step.tag_name:- element_condition, element_params = filter_element(- "tag_name", step.tag_name, prepend=f"{action.pk}_{index}{prepend}"- )- if element_condition:- conditions.append(element_condition)- params.update(element_params)- if step.href:- element_condition, element_params = filter_element(- "href",- step.href,- operator=string_matching_to_operator(step.href_matching, "exact"),- prepend=f"{action.pk}_{index}{prepend}",- )- if element_condition:- conditions.append(element_condition)- params.update(element_params)- if step.text:- element_condition, element_params = filter_element(- "text",- step.text,- operator=string_matching_to_operator(step.text_matching, "exact"),- prepend=f"{action.pk}_{index}{prepend}",- )- if element_condition:- conditions.append(element_condition)- params.update(element_params)-- # filter event conditions (ie URL)- event_conditions, event_params = filter_event(- step,- f"{action.pk}_{index}{prepend}",- index,- table_name,- use_new_events_schema=hogql_context.uses_new_events_schema(),- )- params.update(event_params)- conditions += event_conditions-- if step.properties:- from posthog.models.property.util import parse_prop_grouped_clauses-- prop_query, prop_params = parse_prop_grouped_clauses(- team_id=team_id,- property_group=Filter(data={"properties": step.properties}).property_groups,- prepend=f"action_props_{action.pk}_{index}",- table_name=table_name,- person_properties_mode=person_properties_mode,- person_id_joined_alias=person_id_joined_alias,- hogql_context=hogql_context,- )- conditions.append(prop_query.replace("AND", "", 1))- params.update(prop_params)-- if len(conditions) > 0:- or_queries.append(" AND ".join(conditions))- formatted_query = "(({}))".format(") OR (".join(or_queries))- return formatted_query, params+from posthog.models.property import PropertyIdentifier--def filter_event(- step: ActionStepJSON,- prepend: str = "event",- index: int = 0,- table_name: str = "",- use_new_events_schema: bool = False,-) -> tuple[list[str], dict]:- from posthog.models.property.util import get_property_string_expr-- params = {}- conditions = []-- if table_name != "":- table_name += "."-- if step.url:- value_expr, _ = get_property_string_expr(- "events",- "$current_url",- "'$current_url'",- f"{table_name}properties",- use_new_events_schema=use_new_events_schema,- )- prop_name = f"{prepend}_prop_val_{index}"- if step.url_matching == "exact":- conditions.append(f"{value_expr} = %({prop_name})s")- params.update({prop_name: step.url})- elif step.url_matching == "regex":- conditions.append(f"match({value_expr}, %({prop_name})s)")- params.update({prop_name: step.url})- else:- conditions.append(f"{value_expr} LIKE %({prop_name})s")- params.update({prop_name: f"%{step.url}%"})-- if step.event:- params.update({f"{prepend}_{index}": step.event})- conditions.append(f"event = %({prepend}_{index})s")- else:- conditions.append("44 = 44") # Allow "All events"-- return conditions, params+from products.actions.backend.models.action import Actiondef get_action_tables_and_properties(action: Action) -> TCounter[PropertyIdentifier]:@@ -180,20 +23,3 @@ def get_action_tables_and_properties(action: Action) -> TCounter[PropertyIdentif)return result---def uses_elements_chain(action: Action) -> bool:- for action_step in action.steps:- if any(Property(**prop).type == "element" for prop in (action_step.properties or [])):- return True- if any(getattr(action_step, attribute) is not None for attribute in ["selector", "tag_name", "href", "text"]):- return True- return False---def string_matching_to_operator(- matching: Optional[Literal["exact", "contains", "regex"]], default: OperatorType-) -> OperatorType:- if matching == "contains":- return "icontains"- return matching or defaultdiff --git a/products/cohorts/backend/models/sql.py b/products/cohorts/backend/models/sql.pyindex fb9c0cf67812..8e6e1d7d4382 100644--- a/products/cohorts/backend/models/sql.py+++ b/products/cohorts/backend/models/sql.py@@ -2,10 +2,6 @@ from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSEfrom posthog.clickhouse.table_engines import CollapsingMergeTreefrom posthog.models.person.sql import PERSON_STATIC_COHORT_TABLE-CALCULATE_COHORT_PEOPLE_SQL = """-SELECT {id_column} FROM ({GET_TEAM_PERSON_DISTINCT_IDS}) WHERE {query}-"""-def COHORTPEOPLE_TABLE_ENGINE():return CollapsingMergeTree("cohortpeople", ver="sign")@@ -47,13 +43,6 @@ FROM (SETTINGS optimize_aggregation_in_order = 1, join_algorithm = 'auto'"""-# NOTE: Group by version id to ensure that signs are summed between corresponding rows.-# Version filtering is not necessary as only positive rows of the latest version will be selected by sum(sign) > 0--GET_PERSON_ID_BY_PRECALCULATED_COHORT_ID = """-SELECT DISTINCT person_id FROM cohortpeople WHERE team_id = %(team_id)s AND cohort_id = %({prepend}_cohort_id_{index})s AND version = %({prepend}_version_{index})s-"""-GET_COHORTS_BY_PERSON_UUID = """SELECT cohort_id, argMax(version, version) as latest_versionFROM cohortpeoplediff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.pyindex ba751136c7c3..368f501535fb 100644--- a/products/cohorts/backend/models/util.py+++ b/products/cohorts/backend/models/util.py@@ -3,9 +3,9 @@ from __future__ import annotationsimport copyimport uuidfrom collections.abc import Callable, Sequence-from datetime import datetime, timedelta+from datetime import datetimefrom enum import StrEnum-from typing import TYPE_CHECKING, Any, Optional, Union, cast+from typing import TYPE_CHECKING, Any, Optional, castfrom django.conf import settingsfrom django.db import DEFAULT_DB_ALIAS, InterfaceError, OperationalError, connections@@ -21,7 +21,6 @@ from posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettings, LimitContext, get_default_hogql_global_settingsfrom posthog.hogql.hogql import HogQLContextfrom posthog.hogql.modifiers import create_default_modifiers_for_team-from posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import prepare_and_print_astfrom posthog.hogql.resolver_utils import extract_select_queriesfrom posthog.hogql.visitor import clone_expr@@ -46,27 +45,21 @@ from posthog.models.person.sql import (PERSON_STATIC_COHORT_TABLE,)from posthog.models.property import Property, PropertyGroup-from posthog.schema_enums import ChartDisplayType, PersonsOnEventsMode, ProductKey+from posthog.schema_enums import ChartDisplayType, ProductKeyfrom posthog.schema_migrations.upgrade import upgrade-from products.actions.backend.models.action import Action-from products.actions.backend.models.util import format_action_filterfrom products.cohorts.backend.models.calculation_history import CohortCalculationHistoryfrom products.cohorts.backend.models.cohort import Cohort, CohortOrEmptyfrom products.cohorts.backend.models.dependencies import get_cohort_dependentsfrom products.cohorts.backend.models.sql import (GET_COHORT_SIZE_SQL,GET_COHORTS_BY_PERSON_UUID,- GET_PERSON_ID_BY_PRECALCULATED_COHORT_ID,GET_STATIC_COHORTPEOPLE_BY_PERSON_UUID,RECALCULATE_COHORT_BY_ID,)if TYPE_CHECKING:- from posthog.schema import HogQLQueryModifiers-from posthog.personhog_client import ReadConsistency-from posthog.queries.util import PersonPropertiesMode# temporary marker to denote when cohortpeople table started being populatedTEMP_PRECALCULATED_MARKER = parser.parse("2021-06-07T15:00:00+00:00")@@ -308,23 +301,6 @@ def get_clickhouse_query_stats(tag_matcher: str, cohort_id: int, start_time: datreturn None-def format_person_query(cohort: Cohort, index: int) -> tuple[str, dict[str, Any]]:- if cohort.is_static:- return format_static_cohort_query(cohort, index, prepend="")-- if not cohort.properties.values:- # No person can match an empty cohort- return "SELECT generateUUIDv4() as id WHERE 0 = 19", {}-- # Compile the cohort criteria via HogQLCohortQuery and embed the result as a person-id subquery.- # SECURITY-SENSITIVE: executes a saved, team-owned cohort definition with no acting user in- # scope - warehouse access is enforced when the definition is saved (CohortSerializer).- cohort_query, cohort_context = hogql_cohort_subquery_sql(- cohort, team=cohort.team, bypass_warehouse_access_control=True- )- return _prefix_cohort_hogql_params(cohort_query, cohort_context.values, cohort=cohort, index=index)--def validate_actors_query_for_cohort(query_dict: dict[str, Any]) -> None:"""Reject actor queries that would only fail once the populate task compiles them.@@ -577,17 +553,6 @@ def format_static_cohort_query(cohort: Cohort, index: int, prepend: str) -> tupl)-def format_precalculated_cohort_query(cohort: Cohort, index: int, prepend: str = "") -> tuple[str, dict[str, Any]]:- filter_query = GET_PERSON_ID_BY_PRECALCULATED_COHORT_ID.format(index=index, prepend=prepend)- return (- filter_query,- {- f"{prepend}_cohort_id_{index}": cohort.pk,- f"{prepend}_version_{index}": cohort.version,- },- )--def get_count_operator(count_operator: Optional[str]) -> str:if count_operator == "gte":return ">="@@ -618,76 +583,6 @@ def get_count_operator_ast(count_operator: Optional[str]) -> ast.CompareOperatioraise ValidationError("count_operator must be gte, lte, eq, or None")-def get_entity_query(- event_id: Optional[str],- action_id: Optional[int],- team_id: int,- group_idx: Union[int, str],- hogql_context: HogQLContext,- person_properties_mode: Optional[PersonPropertiesMode] = None,-) -> tuple[str, dict[str, str]]:- if event_id:- return f"event = %({f'event_{group_idx}'})s", {f"event_{group_idx}": event_id}- elif action_id:- action = Action.objects.get(pk=action_id)- action_filter_query, action_params = format_action_filter(- team_id=team_id,- action=action,- prepend="_{}_action".format(group_idx),- hogql_context=hogql_context,- person_properties_mode=(- person_properties_mode if person_properties_mode else PersonPropertiesMode.USING_SUBQUERY- ),- )- return action_filter_query, action_params- else:- raise ValidationError("Cohort query requires action_id or event_id")---def get_date_query(- days: Optional[str], start_time: Optional[str], end_time: Optional[str]-) -> tuple[str, dict[str, str]]:- date_query: str = ""- date_params: dict[str, str] = {}- if days:- date_query, date_params = parse_entity_timestamps_in_days(int(days))- elif start_time or end_time:- date_query, date_params = parse_cohort_timestamps(start_time, end_time)-- return date_query, date_params---def parse_entity_timestamps_in_days(days: int) -> tuple[str, dict[str, str]]:- curr_time = timezone.now()- start_time = curr_time - timedelta(days=days)-- return (- "AND timestamp >= %(date_from)s AND timestamp <= %(date_to)s",- {- "date_from": start_time.strftime("%Y-%m-%d %H:%M:%S"),- "date_to": curr_time.strftime("%Y-%m-%d %H:%M:%S"),- },- )---def parse_cohort_timestamps(start_time: Optional[str], end_time: Optional[str]) -> tuple[str, dict[str, str]]:- clause = "AND "- params: dict[str, str] = {}-- if start_time:- clause += "timestamp >= %(date_from)s"-- params = {"date_from": datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%S").strftime("%Y-%m-%d %H:%M:%S")}- if end_time:- clause += "timestamp <= %(date_to)s"- params = {- **params,- "date_to": datetime.strptime(end_time, "%Y-%m-%dT%H:%M:%S").strftime("%Y-%m-%d %H:%M:%S"),- }-- return clause, params--def is_precalculated_query(cohort: Cohort) -> bool:if (cohort.last_calculation@@ -705,88 +600,6 @@ def _trim_trailing_settings(sql: str) -> str:return sql[: sql.rfind("SETTINGS")]-def _prefix_cohort_hogql_params(- sql: str, values: dict[str, Any], *, cohort: Cohort, index: int-) -> tuple[str, dict[str, Any]]:- # HogQLCohortQuery builds its own HogQLContext, so its %(hogql_val_N)s placeholders would collide with- # the parent query's context and with sibling cohort subqueries in the same query. Prefix them per- # cohort+index so they stay unique once embedded in the legacy parent query. The `)s` terminator in the- # search string keeps hogql_val_1 from also matching hogql_val_10.- prefix = f"cohort_{cohort.pk}_{index}_"- params: dict[str, Any] = {}- for key, value in values.items():- prefixed_key = f"{prefix}{key}"- sql = sql.replace(f"%({key})s", f"%({prefixed_key})s")- params[prefixed_key] = value- return sql, params---def _cohort_distinct_ids_sql(cohort: Cohort, index: int, *, team: Team) -> tuple[str, dict[str, Any]]:- # Distinct_ids of the cohort's members, via HogQL's person_distinct_ids table — it owns the- # argMax(person_id, version)/is_deleted dedup and the team scoping, so this path no longer- # hand-rolls them. Members come from the cohortpeople tables for static/precalculated cohorts- # and from evaluating the criteria (HogQLCohortQuery) otherwise.- from posthog.hogql.query import HogQLQueryExecutor-- from posthog.hogql_queries.hogql_cohort_query import HogQLCohortQuery-- if cohort.is_static:- members: ast.SelectQuery | ast.SelectSetQuery = parse_select(- "SELECT person_id FROM static_cohort_people WHERE cohort_id = {id}",- {"id": ast.Constant(value=cohort.pk)},- )- elif is_precalculated_query(cohort):- members = parse_select(- "SELECT person_id FROM raw_cohort_people WHERE cohort_id = {id} AND version = {version}",- {"id": ast.Constant(value=cohort.pk), "version": ast.Constant(value=cohort.version)},- )- else:- members = HogQLCohortQuery(cohort=cohort, team=team).get_query()-- query = parse_select(- "SELECT distinct_id FROM person_distinct_ids WHERE person_id IN {members}",- {"members": members},- )- sql, context = HogQLQueryExecutor(- query_type="CohortFilterDistinctIds",- query=query,- modifiers=_cohort_calculation_modifiers(),- team=team,- limit_context=LimitContext.COHORT_CALCULATION,- # SECURITY-SENSITIVE: executes a saved, team-owned cohort definition with no acting user- # in scope - warehouse access is enforced when the definition is saved (CohortSerializer).- bypass_warehouse_access_control=True,- settings=HogQLGlobalSettings(),- ).generate_clickhouse_sql()- sql = _trim_trailing_settings(sql)- return _prefix_cohort_hogql_params(sql, context.values, cohort=cohort, index=index)---def _cohort_calculation_modifiers() -> HogQLQueryModifiers:- # Deferred: posthog.schema (the pydantic models) stays off django.setup(), where this- # module loads in every process via the cohort model.- from posthog.schema import HogQLQueryModifiers # noqa: PLC0415-- return HogQLQueryModifiers(personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED)---def format_filter_query(cohort: Cohort, index: int) -> tuple[str, dict[str, Any]]:- distinct_ids_sql, params = _cohort_distinct_ids_sql(cohort, index, team=cohort.team)- # Callers embed this in `distinct_id IN (...)`, so it must select exactly distinct_id.- return f"SELECT distinct_id FROM ({distinct_ids_sql})", params---def format_cohort_subquery(cohort: Cohort, index: int, custom_match_field="person_id") -> tuple[str, dict[str, Any]]:- is_precalculated = is_precalculated_query(cohort)- if is_precalculated:- query, params = format_precalculated_cohort_query(cohort, index)- else:- query, params = format_person_query(cohort, index)-- person_query = f"{custom_match_field} IN ({query})"- return person_query, params--def insert_static_cohort(person_uuids: Sequence[Optional[uuid.UUID]], cohort_id: int, *, team_id: int):tag_queries(product=ProductKey.COHORTS,