Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(cohorts): remove legacy CohortQuery builder, HogQL is sole engine (#61332)

Sandy Spicer1757fb62280b
diff --git a/ee/clickhouse/models/test/__snapshots__/test_cohort.ambr b/ee/clickhouse/models/test/__snapshots__/test_cohort.ambr
index e96c8f5b27f6..327a6aa0c958 100644
--- a/ee/clickhouse/models/test/__snapshots__/test_cohort.ambr
+++ b/ee/clickhouse/models/test/__snapshots__/test_cohort.ambr
@@ -231,50 +231,49 @@
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 if(behavior_query.person_id = '00000000-0000-0000-0000-000000000000', person.person_id, behavior_query.person_id) AS id
- FROM
- (SELECT if(not(empty(pdi.distinct_id)), pdi.person_id, e.person_id) AS person_id,
- countIf(timestamp > now() - INTERVAL 2 year
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_X_level_level_0_level_0_level_0_0
- FROM events e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 2 year
- GROUP BY person_id) behavior_query
- FULL OUTER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = behavior_query.person_id
- WHERE 1 = 1
- AND ((((coalesce(performed_event_condition_X_level_level_0_level_0_level_0_0, false)))
- AND ((id NOT IN
- (SELECT person_id
- FROM cohortpeople
- WHERE cohort_id = 99999
- AND team_id = 99999))))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto')))
+ (SELECT person_distinct_ids.distinct_id AS distinct_id
+ FROM
+ (SELECT tupleElement(argMax(tuple(person_distinct_id2.person_id), person_distinct_id2.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id2.is_deleted), person_distinct_id2.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
+ WHERE in(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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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(ifNull(equals(cohort_people.cohort_id, 99999), 0), ifNull(equals(cohort_people.team_id, 99999), 0))))))
+ LIMIT 1000000000)))
'''
# ---
# name: TestCohort.test_cohortpeople_with_not_in_cohort_operator_for_behavioural_cohorts
@@ -459,19 +458,20 @@
# ---
# name: TestCohort.test_static_cohort_precalculated
'''
-
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 person_id as id
- FROM person_static_cohort
- WHERE cohort_id = %(_cohort_id_0)s
- AND team_id = %(team_id)s)
+ (SELECT person_distinct_ids.distinct_id AS distinct_id
+ FROM
+ (SELECT tupleElement(argMax(tuple(person_distinct_id2.person_id), person_distinct_id2.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id2.is_deleted), person_distinct_id2.version), 1), 0), 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/test_cohort.py b/ee/clickhouse/models/test/test_cohort.py
index 511b19c5b065..e430d6384ba3 100644
--- a/ee/clickhouse/models/test/test_cohort.py
+++ b/ee/clickhouse/models/test/test_cohort.py
@@ -23,7 +23,6 @@ from rest_framework.exceptions import ValidationError
from posthog.schema import PersonsOnEventsMode
from posthog.hogql.constants import MAX_SELECT_COHORT_CALCULATION_LIMIT
-from posthog.hogql.hogql import HogQLContext
from posthog.clickhouse.client import sync_execute
from posthog.models.cohort import Cohort
@@ -502,7 +501,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):
hogql_context=filter.hogql_context,
)
final_query = "SELECT uuid FROM events WHERE team_id = %(team_id)s {}".format(query)
- self.assertIn("\nFROM person_distinct_id2\n", final_query)
+ self.assertIn("person_distinct_id2", final_query)
result = sync_execute(
final_query,
@@ -926,7 +925,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):
self.calculate_cohort_hogql_test_harness(cohort, 0)
with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- sql, _ = format_filter_query(cohort, 0, HogQLContext(team_id=self.team.pk))
+ sql, _ = format_filter_query(cohort, 0)
self.assertQueryMatchesSnapshot(sql)
def test_cohortpeople_with_valid_other_cohort_filter(self):
@@ -1118,7 +1117,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):
hogql_context=filter.hogql_context,
)
final_query = "SELECT uuid, distinct_id FROM events WHERE team_id = %(team_id)s {}".format(query)
- self.assertIn("\nFROM person_distinct_id2\n", final_query)
+ self.assertIn("person_distinct_id2", final_query)
result = sync_execute(
final_query,
diff --git a/ee/clickhouse/queries/enterprise_cohort_query.py b/ee/clickhouse/queries/enterprise_cohort_query.py
deleted file mode 100644
index 50cd4527c666..000000000000
--- a/ee/clickhouse/queries/enterprise_cohort_query.py
+++ /dev/null
@@ -1,425 +0,0 @@
-from typing import Any, cast
-
-from posthog.schema import PersonsOnEventsMode
-
-from posthog.constants import PropertyOperatorType
-from posthog.models.cohort.util import get_count_operator
-from posthog.models.filters.mixins.utils import cached_property
-from posthog.models.property.property import Property, PropertyGroup
-from posthog.queries.foss_cohort_query import (
- FOSSCohortQuery,
- parse_and_validate_positive_integer,
- validate_entity,
- validate_interval,
- validate_seq_date_more_recent_than_date,
-)
-from posthog.queries.util import PersonPropertiesMode
-
-
-def check_negation_clause(prop: PropertyGroup) -> tuple[bool, bool]:
- has_negation_clause = False
- has_primary_clase = False
- if len(prop.values):
- if isinstance(prop.values[0], PropertyGroup):
- for p in cast(list[PropertyGroup], prop.values):
- has_neg, has_primary = check_negation_clause(p)
- has_negation_clause = has_negation_clause or has_neg
- has_primary_clase = has_primary_clase or has_primary
-
- else:
- for property in cast(list[Property], prop.values):
- if property.negation:
- has_negation_clause = True
- else:
- has_primary_clase = True
-
- if prop.type == PropertyOperatorType.AND and has_negation_clause and has_primary_clase:
- # this negation is valid, since all conditions are met.
- # So, we don't need to pair this with anything in the rest of the tree
- # return no negations, and yes to primary clauses
- return False, True
-
- return has_negation_clause, has_primary_clase
-
-
-class EnterpriseCohortQuery(FOSSCohortQuery):
- def get_query(self) -> tuple[str, dict[str, Any]]:
- if not self._outer_property_groups:
- # everything is pushed down, no behavioral stuff to do
- # thus, use personQuery directly
- return self._person_query.get_query(prepend=self._cohort_pk)
-
- # TODO: clean up this kludge. Right now, get_conditions has to run first so that _fields is populated for _get_behavioral_subquery()
- conditions, condition_params = self._get_conditions()
- self.params.update(condition_params)
-
- subq = []
-
- if self.sequence_filters_to_query:
- (
- sequence_query,
- sequence_params,
- sequence_query_alias,
- ) = self._get_sequence_query()
- subq.append((sequence_query, sequence_query_alias))
- self.params.update(sequence_params)
- else:
- (
- behavior_subquery,
- behavior_subquery_params,
- behavior_query_alias,
- ) = self._get_behavior_subquery()
- subq.append((behavior_subquery, behavior_query_alias))
- self.params.update(behavior_subquery_params)
-
- person_query, person_params, person_query_alias = self._get_persons_query(prepend=str(self._cohort_pk))
- subq.append((person_query, person_query_alias))
- self.params.update(person_params)
-
- # Since we can FULL OUTER JOIN, we may end up with pairs of uuids where one side is blank. Always try to choose the non blank ID
- q, fields = self._build_sources(subq)
-
- # optimize_aggregation_in_order slows down this query but massively decreases memory usage
- # this is fine for offline cohort calculation
- final_query = f"""
- SELECT {fields} AS id FROM
- {q}
- WHERE 1 = 1
- {conditions}
- SETTINGS optimize_aggregation_in_order = 1, join_algorithm = 'auto'
- """
-
- return final_query, self.params
-
- def _get_condition_for_property(self, prop: Property, prepend: str, idx: int) -> tuple[str, dict[str, Any]]:
- res: str = ""
- params: dict[str, Any] = {}
-
- if prop.type == "behavioral":
- if prop.value == "performed_event":
- res, params = self.get_performed_event_condition(prop, prepend, idx)
- elif prop.value == "performed_event_multiple":
- res, params = self.get_performed_event_multiple(prop, prepend, idx)
- elif prop.value == "stopped_performing_event":
- res, params = self.get_stopped_performing_event(prop, prepend, idx)
- elif prop.value == "restarted_performing_event":
- res, params = self.get_restarted_performing_event(prop, prepend, idx)
- elif prop.value == "performed_event_first_time":
- res, params = self.get_performed_event_first_time(prop, prepend, idx)
- elif prop.value == "performed_event_sequence":
- res, params = self.get_performed_event_sequence(prop, prepend, idx)
- elif prop.value == "performed_event_regularly":
- res, params = self.get_performed_event_regularly(prop, prepend, idx)
- elif prop.type == "person":
- res, params = self.get_person_condition(prop, prepend, idx)
- elif (
- prop.type == "static-cohort"
- ): # "cohort" and "precalculated-cohort" are handled by flattening during initialization
- res, params = self.get_static_cohort_condition(prop, prepend, idx)
- elif prop.type == "dynamic-cohort":
- res, params = self.get_dynamic_cohort_condition(prop, prepend, idx)
- else:
- raise ValueError(f"Invalid property type for Cohort queries: {prop.type}")
-
- return res, params
-
- def get_stopped_performing_event(self, prop: Property, prepend: str, idx: int) -> tuple[str, dict[str, Any]]:
- event = (prop.event_type, prop.key)
- column_name = f"stopped_event_condition_{prepend}_{idx}"
-
- entity_query, entity_params = self._get_entity(event, prepend, idx)
- date_value = parse_and_validate_positive_integer(prop.time_value, "time_value")
- date_param = f"{prepend}_date_{idx}"
- date_interval = validate_interval(prop.time_interval)
-
- seq_date_value = parse_and_validate_positive_integer(prop.seq_time_value, "time_value")
- seq_date_param = f"{prepend}_seq_date_{idx}"
- seq_date_interval = validate_interval(prop.seq_time_interval)
-
- validate_seq_date_more_recent_than_date((seq_date_value, seq_date_interval), (date_value, date_interval))
-
- self._check_earliest_date((date_value, date_interval))
-
- # The user was doing the event in this time period
- event_was_happening_period = f"countIf(timestamp > now() - INTERVAL %({date_param})s {date_interval} AND timestamp <= now() - INTERVAL %({seq_date_param})s {seq_date_interval} AND {entity_query})"
- # Then stopped in this time period
- event_stopped_period = f"countIf(timestamp > now() - INTERVAL %({seq_date_param})s {seq_date_interval} AND timestamp <= now() AND {entity_query})"
-
- full_condition = f"({event_was_happening_period} > 0 AND {event_stopped_period} = 0) as {column_name}"
-
- self._fields.append(full_condition)
-
- return (
- f"{'NOT' if prop.negation else ''} coalesce({column_name}, false)",
- {
- f"{date_param}": date_value,
- f"{seq_date_param}": seq_date_value,
- **entity_params,
- },
- )
-
- def get_restarted_performing_event(self, prop: Property, prepend: str, idx: int) -> tuple[str, dict[str, Any]]:
- event = (prop.event_type, prop.key)
- column_name = f"restarted_event_condition_{prepend}_{idx}"
-
- entity_query, entity_params = self._get_entity(event, prepend, idx)
- date_value = parse_and_validate_positive_integer(prop.time_value, "time_value")
- date_param = f"{prepend}_date_{idx}"
- date_interval = validate_interval(prop.time_interval)
-
- seq_date_value = parse_and_validate_positive_integer(prop.seq_time_value, "time_value")
- seq_date_param = f"{prepend}_seq_date_{idx}"
- seq_date_interval = validate_interval(prop.seq_time_interval)
-
- validate_seq_date_more_recent_than_date((seq_date_value, seq_date_interval), (date_value, date_interval))
-
- self._restrict_event_query_by_time = False
-
- # Events should have been fired in the initial_period
- initial_period = f"countIf(timestamp <= now() - INTERVAL %({date_param})s {date_interval} AND {entity_query})"
- # Then stopped in the event_stopped_period
- event_stopped_period = f"countIf(timestamp > now() - INTERVAL %({date_param})s {date_interval} AND timestamp <= now() - INTERVAL %({seq_date_param})s {seq_date_interval} AND {entity_query})"
- # Then restarted in the final event_restart_period
- event_restarted_period = f"countIf(timestamp > now() - INTERVAL %({seq_date_param})s {seq_date_interval} AND timestamp <= now() AND {entity_query})"
-
- full_condition = (
- f"({initial_period} > 0 AND {event_stopped_period} = 0 AND {event_restarted_period} > 0) as {column_name}"
- )
-
- self._fields.append(full_condition)
-
- return (
- f"{'NOT' if prop.negation else ''} coalesce({column_name}, false)",
- {
- f"{date_param}": date_value,
- f"{seq_date_param}": seq_date_value,
- **entity_params,
- },
- )
-
- def get_performed_event_first_time(self, prop: Property, prepend: str, idx: int) -> tuple[str, dict[str, Any]]:
- event = (prop.event_type, prop.key)
- entity_query, entity_params = self._get_entity(event, prepend, idx)
-
- column_name = f"first_time_condition_{prepend}_{idx}"
-
- date_value = parse_and_validate_positive_integer(prop.time_value, "time_value")
- date_param = f"{prepend}_date_{idx}"
- date_interval = validate_interval(prop.time_interval)
-
- self._restrict_event_query_by_time = False
-
- field = f"minIf(timestamp, {entity_query}) >= now() - INTERVAL %({date_param})s {date_interval} AND minIf(timestamp, {entity_query}) < now() as {column_name}"
-
- self._fields.append(field)
-
- return (
- f"{'NOT' if prop.negation else ''} coalesce({column_name}, false)",
- {f"{date_param}": date_value, **entity_params},
- )
-
- def get_performed_event_regularly(self, prop: Property, prepend: str, idx: int) -> tuple[str, dict[str, Any]]:
- event = (prop.event_type, prop.key)
- entity_query, entity_params = self._get_entity(event, prepend, idx)
-
- column_name = f"performed_event_regularly_{prepend}_{idx}"
-
- date_interval = validate_interval(prop.time_interval)
-
- time_value_param = f"{prepend}_time_value_{idx}"
- time_value = parse_and_validate_positive_integer(prop.time_value, "time_value")
-
- operator_value_param = f"{prepend}_operator_value_{idx}"
- operator_value = parse_and_validate_positive_integer(prop.operator_value, "operator_value")
-
- min_periods_param = f"{prepend}_min_periods_{idx}"
- min_period_count = parse_and_validate_positive_integer(prop.min_periods, "min_periods")
-
- total_period_count = parse_and_validate_positive_integer(prop.total_periods, "total_periods")
-
- if min_period_count > total_period_count:
- raise (
- ValueError(
- f"min_periods ({min_period_count}) cannot be greater than total_periods ({total_period_count})"
- )
- )
-
- params = {
- time_value_param: time_value,
- operator_value_param: operator_value,
- min_periods_param: min_period_count,
- }
- periods = []
-
- if total_period_count:
- for period in range(total_period_count):
- start_time_value = f"%({time_value_param})s * {period}"
- end_time_value = f"%({time_value_param})s * ({period} + 1)"
- # Clause that returns 1 if the event was performed the expected number of times in the given time interval, otherwise 0
- periods.append(
- f"if(countIf({entity_query} and timestamp <= now() - INTERVAL {start_time_value} {date_interval} and timestamp > now() - INTERVAL {end_time_value} {date_interval}) {get_count_operator(prop.operator)} %({operator_value_param})s, 1, 0)"
- )
- earliest_date = (total_period_count * time_value, date_interval)
- self._check_earliest_date(earliest_date)
-
- field = "+".join(periods) + f">= %({min_periods_param})s" + f" as {column_name}"
-
- self._fields.append(field)
-
- return (
- f"{'NOT' if prop.negation else ''} coalesce({column_name}, false)",
- {**entity_params, **params},
- )
-
- @cached_property
- def sequence_filters_to_query(self) -> list[Property]:
- props = []
- for prop in self._filter.property_groups.flat:
- if prop.value == "performed_event_sequence":
- props.append(prop)
- return props
-
- @cached_property
- def sequence_filters_lookup(self) -> dict[str, str]:
- lookup = {}
- for idx, prop in enumerate(self.sequence_filters_to_query):
- lookup[str(prop.to_dict())] = f"{idx}"
- return lookup
-
- def _get_sequence_query(self) -> tuple[str, dict[str, Any], str]:
- params = {}
-
- materialized_columns = list(self._column_optimizer.event_columns_to_query)
- names = [
- "event",
- "properties",
- "distinct_id",
- "timestamp",
- *materialized_columns,
- ]
-
- person_prop_query = ""
- person_prop_params: dict = {}
-
- _inner_fields = [f"{self._person_id_alias} AS person_id"]
- _intermediate_fields = ["person_id"]
- _outer_fields = ["person_id"]
-
- _inner_fields.extend(names)
- _intermediate_fields.extend(names)
-
- for idx, prop in enumerate(self.sequence_filters_to_query):
- (
- step_cols,
- intermediate_cols,
- aggregate_cols,
- seq_params,
- ) = self._get_sequence_filter(prop, idx)
- _inner_fields.extend(step_cols)
- _intermediate_fields.extend(intermediate_cols)
- _outer_fields.extend(aggregate_cols)
- params.update(seq_params)
-
- date_condition, date_params = self._get_date_condition()
- params.update(date_params)
-
- event_param_name = f"{self._cohort_pk}_event_ids"
-
- if self.should_pushdown_persons and self._person_on_events_mode != PersonsOnEventsMode.DISABLED:
- person_prop_query, person_prop_params = self._get_prop_groups(
- self._inner_property_groups,
- person_properties_mode=PersonPropertiesMode.DIRECT_ON_EVENTS,
- person_id_joined_alias=self._person_id_alias,
- )
-
- new_query = f"""
- SELECT {", ".join(_inner_fields)} FROM events AS {self.EVENT_TABLE_ALIAS}
- {self._get_person_ids_query()}
- WHERE team_id = %(team_id)s
- AND event IN %({event_param_name})s
- {date_condition}
- {person_prop_query}
- """
-
- intermediate_query = f"""
- SELECT {", ".join(_intermediate_fields)} FROM ({new_query})
- """
-
- _outer_fields.extend(self._fields)
-
- outer_query = f"""
- SELECT {", ".join(_outer_fields)} FROM ({intermediate_query})
- GROUP BY person_id
- """
- return (
- outer_query,
- {
- "team_id": self._team_id,
- event_param_name: self._events,
- **params,
- **person_prop_params,
- },
- self.FUNNEL_QUERY_ALIAS,
- )
-
- def _get_sequence_filter(self, prop: Property, idx: int) -> tuple[list[str], list[str], list[str], dict[str, Any]]:
- event = validate_entity((prop.event_type, prop.key))
- entity_query, entity_params = self._get_entity(event, f"event_sequence_{self._cohort_pk}", idx)
- seq_event = validate_entity((prop.seq_event_type, prop.seq_event))
-
- seq_entity_query, seq_entity_params = self._get_entity(seq_event, f"seq_event_sequence_{self._cohort_pk}", idx)
-
- time_value = parse_and_validate_positive_integer(prop.time_value, "time_value")
- time_interval = validate_interval(prop.time_interval)
- seq_date_value = parse_and_validate_positive_integer(prop.seq_time_value, "time_value")
- seq_date_interval = validate_interval(prop.seq_time_interval)
- self._check_earliest_date((time_value, time_interval))
-
- event_prepend = f"event_{idx}"
-
- duplicate_event = 0
- if event == seq_event:
- duplicate_event = 1
-
- aggregate_cols = []
- aggregate_condition = f"{'NOT' if prop.negation else ''} max(if({entity_query} AND {event_prepend}_latest_0 < {event_prepend}_latest_1 AND {event_prepend}_latest_1 <= {event_prepend}_latest_0 + INTERVAL {seq_date_value} {seq_date_interval}, 2, 1)) = 2 AS {self.SEQUENCE_FIELD_ALIAS}_{self.sequence_filters_lookup[str(prop.to_dict())]}"
- aggregate_cols.append(aggregate_condition)
-
- condition_cols = []
- timestamp_condition = f"min({event_prepend}_latest_1) over (PARTITION by person_id ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND {duplicate_event} PRECEDING) {event_prepend}_latest_1"
- condition_cols.append(f"{event_prepend}_latest_0")
- condition_cols.append(timestamp_condition)
-
- step_cols = []
- step_cols.append(
- f"if({entity_query} AND timestamp > now() - INTERVAL {time_value} {time_interval}, 1, 0) AS {event_prepend}_step_0"
- )
- step_cols.append(f"if({event_prepend}_step_0 = 1, timestamp, null) AS {event_prepend}_latest_0")
-
- step_cols.append(
- f"if({seq_entity_query} AND timestamp > now() - INTERVAL {time_value} {time_interval}, 1, 0) AS {event_prepend}_step_1"
- )
- step_cols.append(f"if({event_prepend}_step_1 = 1, timestamp, null) AS {event_prepend}_latest_1")
-
- return (
- step_cols,
- condition_cols,
- aggregate_cols,
- {
- **entity_params,
- **seq_entity_params,
- },
- )
-
- def get_performed_event_sequence(self, prop: Property, prepend: str, idx: int) -> tuple[str, dict[str, Any]]:
- return (
- f"{self.SEQUENCE_FIELD_ALIAS}_{self.sequence_filters_lookup[str(prop.to_dict())]}",
- {},
- )
-
- # Check if negations are always paired with a positive filter
- # raise a value error warning that this is an invalid cohort
- def _validate_negations(self) -> None:
- has_pending_negation, has_primary_clause = check_negation_clause(self._filter.property_groups)
- if has_pending_negation:
- raise ValueError("Negations must be paired with a positive filter.")
diff --git a/ee/clickhouse/queries/test/__snapshots__/test_cohort_query.ambr b/ee/clickhouse/queries/test/__snapshots__/test_cohort_query.ambr
deleted file mode 100644
index 67b2f2ec7ae5..000000000000
--- a/ee/clickhouse/queries/test/__snapshots__/test_cohort_query.ambr
+++ /dev/null
@@ -1,2635 +0,0 @@
-# serializer version: 1
-# name: TestCohortQuery.test_basic_query
- '''
- (
- (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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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('today', 6, 'UTC')), lessOrEquals(timestamp, toDateTime64('today', 6, 'UTC')), equals(e.event, '$pageview')))
- GROUP BY actor_id) AS source
- ORDER BY source.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')
- UNION DISTINCT
- (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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')) INTERSECT DISTINCT (
- (SELECT source.id AS id
- FROM
- (SELECT actor_id AS actor_id,
- count() AS event_count,
- groupUniqArray(distinct_id) AS event_distinct_ids,
- actor_id AS id
- FROM
- (SELECT min(toTimeZone(e.timestamp, 'UTC')) AS min_timestamp,
- minIf(toTimeZone(e.timestamp, 'UTC'), greaterOrEquals(toTimeZone(e.timestamp, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))) AS min_timestamp_with_condition,
- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS actor_id,
- argMin(e.uuid, toTimeZone(e.timestamp, 'UTC')) AS uuid,
- argMin(e.distinct_id, toTimeZone(e.timestamp, 'UTC')) AS distinct_id
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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), lessOrEquals(e.timestamp, toDateTime64('today', 6, 'UTC')), and(equals(e.event, '$autocapture'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://posthog.com/feedback/123'), 0)))
- GROUP BY if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)
- HAVING and(ifNull(equals(min_timestamp, min_timestamp_with_condition), isNull(min_timestamp)
- and isNull(min_timestamp_with_condition)), ifNull(notEquals(min_timestamp, fromUnixTimestamp(0)), isNotNull(min_timestamp)
- or isNotNull(fromUnixTimestamp(0)))))
- GROUP BY actor_id) AS source
- ORDER BY source.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') INTERSECT DISTINCT
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
- 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, 'email'), ''), 'null'), '^"|"$', ''), '[email protected]'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.properties___email, '[email protected]'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')) SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_basic_query.1
- '''
-
- SELECT person.person_id AS id
- FROM
- (SELECT if(not(empty(pdi.distinct_id)), pdi.person_id, e.person_id) AS person_id,
- countIf(timestamp > now() - INTERVAL 1 day
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_None_level_level_0_level_0_level_0_0,
- countIf(timestamp > now() - INTERVAL 2 week
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_None_level_level_0_level_0_level_1_0,
- minIf(timestamp, ((replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', '') = 'https://posthog.com/feedback/123'
- AND event = '$autocapture'))) >= now() - INTERVAL 2 week
- AND minIf(timestamp, ((replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', '') = 'https://posthog.com/feedback/123'
- AND event = '$autocapture'))) < now() as first_time_condition_None_level_level_0_level_1_level_0_0
- FROM events e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview', '$pageview', '$autocapture']
- GROUP BY person_id) behavior_query
- INNER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (((has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', ''))))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (((has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', ''))))) SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = behavior_query.person_id
- WHERE 1 = 1
- AND ((((coalesce(performed_event_condition_None_level_level_0_level_0_level_0_0, false))
- OR (coalesce(performed_event_condition_None_level_level_0_level_0_level_1_0, false)))
- AND ((coalesce(first_time_condition_None_level_level_0_level_1_level_0_0, false))))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_another_cohort_with_event_sequence
- '''
-
- SELECT count(DISTINCT person_id)
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 0
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_another_cohort_with_event_sequence.1
- '''
-
- (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 and(equals(cohortpeople.team_id, 99999), in(tuple(cohortpeople.cohort_id, cohortpeople.version), [(99999, 0)]))) AS cohort_people
- WHERE and(ifNull(equals(cohort_people.cohort_id, 99999), 0), ifNull(equals(cohort_people.team_id, 99999), 0))
- LIMIT 1000000000) INTERSECT DISTINCT
- (SELECT source.id AS id
- FROM
- (SELECT aggregation_target AS actor_id,
- actor_id AS id
- FROM
- (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1)])))) AS events_array,
- [''] AS prop,
- arrayJoin(aggregate_funnel(2, 691200, 'first_touch', 'ordered', prop, [], arrayFilter((x, x_before, x_after) -> not(and(ifNull(lessOrEquals(length(x.4), 1), 0), ifNull(equals(x.4, x_before.4), isNull(x.4)
- and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)
- and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)
- and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)
- and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,
- af_tuple.1 AS step_reached,
- plus(af_tuple.1, 1) AS steps,
- af_tuple.2 AS breakdown,
- af_tuple.3 AS timings,
- af_tuple.5 AS steps_bitfield,
- aggregation_target AS aggregation_target
- FROM
- (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,
- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,
- e.uuid AS uuid,
- e.`$session_id` AS `$session_id`,
- e.`$window_id` AS `$window_id`,
- if(equals(e.event, '$new_view'), 1, 0) AS step_0,
- if(equals(e.event, '$new_view'), 1, 0) AS step_1
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('today', 6, 'UTC'))), in(e.event, tuple('$new_view'))), or(ifNull(equals(step_0, 1), 0), ifNull(equals(step_1, 1), 0))))
- GROUP BY aggregation_target
- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
- WHERE bitTest(steps_bitfield, 1)
- ORDER BY aggregation_target ASC SETTINGS join_algorithm='auto') AS source
- ORDER BY source.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_another_cohort_with_event_sequence.2
- '''
-
- SELECT if(funnel_query.person_id = '00000000-0000-0000-0000-000000000000', person.person_id, funnel_query.person_id) AS id
- FROM
- (SELECT person_id,
- max(if(event = '$new_view'
- AND event_0_latest_0 < event_0_latest_1
- AND event_0_latest_1 <= event_0_latest_0 + INTERVAL 8 day, 2, 1)) = 2 AS steps_0
- FROM
- (SELECT person_id,
- event,
- properties,
- distinct_id, timestamp, event_0_latest_0,
- min(event_0_latest_1) over (PARTITION by person_id
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) event_0_latest_1
- FROM
- (SELECT if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) AS person_id,
- event,
- properties,
- distinct_id, timestamp, if(event = '$new_view'
- AND timestamp > now() - INTERVAL 8 day, 1, 0) AS event_0_step_0,
- if(event_0_step_0 = 1, timestamp, null) AS event_0_latest_0,
- if(event = '$new_view'
- AND timestamp > now() - INTERVAL 8 day, 1, 0) AS event_0_step_1,
- if(event_0_step_1 = 1, timestamp, null) AS event_0_latest_1
- FROM events AS e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$new_view', '$new_view']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 8 day))
- GROUP BY person_id) funnel_query
- FULL OUTER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = funnel_query.person_id
- WHERE 1 = 1
- AND (((id IN
- (SELECT person_id
- FROM cohortpeople
- WHERE cohort_id = 99999
- AND team_id = 99999))
- AND (steps_0))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_another_cohort_with_event_sequence.3
- '''
-
- (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 and(equals(cohortpeople.team_id, 99999), in(tuple(cohortpeople.cohort_id, cohortpeople.version), [(99999, 0)]))) AS cohort_people
- WHERE and(ifNull(equals(cohort_people.cohort_id, 99999), 0), ifNull(equals(cohort_people.team_id, 99999), 0))
- LIMIT 1000000000) INTERSECT DISTINCT
- (SELECT source.id AS id
- FROM
- (SELECT aggregation_target AS actor_id,
- actor_id AS id
- FROM
- (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1)])))) AS events_array,
- [''] AS prop,
- arrayJoin(aggregate_funnel_v9(2, 691200, 'first_touch', 'ordered', prop, [], arrayFilter((x, x_before, x_after) -> not(and(ifNull(lessOrEquals(length(x.4), 1), 0), ifNull(equals(x.4, x_before.4), isNull(x.4)
- and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)
- and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)
- and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)
- and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,
- af_tuple.1 AS step_reached,
- plus(af_tuple.1, 1) AS steps,
- af_tuple.2 AS breakdown,
- af_tuple.3 AS timings,
- af_tuple.5 AS steps_bitfield,
- aggregation_target AS aggregation_target
- FROM
- (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,
- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,
- e.uuid AS uuid,
- e.`$session_id` AS `$session_id`,
- e.`$window_id` AS `$window_id`,
- if(equals(e.event, '$new_view'), 1, 0) AS step_0,
- if(equals(e.event, '$new_view'), 1, 0) AS step_1
- 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 ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 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), and(and(greaterOrEquals(toTimeZone(e.timestamp, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(toTimeZone(e.timestamp, 'UTC'), toDateTime64('today', 6, 'UTC'))), in(e.event, tuple('$new_view'))), or(ifNull(equals(step_0, 1), 0), ifNull(equals(step_1, 1), 0))))
- GROUP BY aggregation_target
- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
- WHERE bitTest(steps_bitfield, 1)
- ORDER BY aggregation_target ASC SETTINGS join_algorithm='auto') AS source
- ORDER BY source.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_another_cohort_with_event_sequence.4
- '''
-
- SELECT if(funnel_query.person_id = '00000000-0000-0000-0000-000000000000', person.person_id, funnel_query.person_id) AS id
- FROM
- (SELECT person_id,
- max(if(event = '$new_view'
- AND event_0_latest_0 < event_0_latest_1
- AND event_0_latest_1 <= event_0_latest_0 + INTERVAL 8 day, 2, 1)) = 2 AS steps_0
- FROM
- (SELECT person_id,
- event,
- properties,
- distinct_id, timestamp, event_0_latest_0,
- min(event_0_latest_1) over (PARTITION by person_id
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) event_0_latest_1
- FROM
- (SELECT if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) AS person_id,
- event,
- properties,
- distinct_id, timestamp, if(event = '$new_view'
- AND timestamp > now() - INTERVAL 8 day, 1, 0) AS event_0_step_0,
- if(event_0_step_0 = 1, timestamp, null) AS event_0_latest_0,
- if(event = '$new_view'
- AND timestamp > now() - INTERVAL 8 day, 1, 0) AS event_0_step_1,
- if(event_0_step_1 = 1, timestamp, null) AS event_0_latest_1
- FROM events AS e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$new_view', '$new_view']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 8 day ))
- GROUP BY person_id) funnel_query
- FULL OUTER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = funnel_query.person_id
- WHERE 1 = 1
- AND (((id IN
- (SELECT person_id
- FROM cohortpeople
- WHERE cohort_id = 99999
- AND team_id = 99999 ))
- AND (steps_0))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_extra
- '''
-
- SELECT count(DISTINCT person_id)
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 0
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_extra.1
- '''
-
- (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 and(equals(cohortpeople.team_id, 99999), in(tuple(cohortpeople.cohort_id, cohortpeople.version), [(99999, 0)]))) AS cohort_people
- WHERE and(ifNull(equals(cohort_people.cohort_id, 99999), 0), ifNull(equals(cohort_people.team_id, 99999), 0))
- LIMIT 1000000000) INTERSECT DISTINCT
- (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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_extra.10
- '''
- (
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
- 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, 'name'), ''), 'null'), '^"|"$', ''), 'test'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.properties___name, 'test'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto'))
- UNION DISTINCT (
- (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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')) SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_extra.11
- '''
-
- SELECT if(behavior_query.person_id = '00000000-0000-0000-0000-000000000000', person.person_id, behavior_query.person_id) AS id
- FROM
- (SELECT if(not(empty(pdi.distinct_id)), pdi.person_id, e.person_id) AS person_id,
- countIf(timestamp > now() - INTERVAL 1 week
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_None_level_level_0_level_1_level_0_0
- FROM events e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 1 week
- GROUP BY person_id) behavior_query
- FULL OUTER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = behavior_query.person_id
- WHERE 1 = 1
- AND ((((has(['test'], replaceRegexpAll(JSONExtractRaw(person_props, 'name'), '^"|"$', ''))))
- OR ((coalesce(performed_event_condition_None_level_level_0_level_1_level_0_0, false))))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_extra.12
- '''
- (
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
- 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, 'name'), ''), 'null'), '^"|"$', ''), 'test'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.properties___name, 'test'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto'))
- UNION DISTINCT (
- (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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')) SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_extra.13
- '''
-
- SELECT if(behavior_query.person_id = '00000000-0000-0000-0000-000000000000', person.person_id, behavior_query.person_id) AS id
- FROM
- (SELECT if(not(empty(pdi.distinct_id)), pdi.person_id, e.person_id) AS person_id,
- countIf(timestamp > now() - INTERVAL 1 week
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_None_level_level_0_level_1_level_0_0
- FROM events e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 1 week
- GROUP BY person_id) behavior_query
- FULL OUTER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = behavior_query.person_id
- WHERE 1 = 1
- AND ((((has(['test'], replaceRegexpAll(JSONExtractRaw(person_props, 'name'), '^"|"$', ''))))
- OR ((coalesce(performed_event_condition_None_level_level_0_level_1_level_0_0, false))))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_extra.14
- '''
- (
- (SELECT persons.id AS id
- FROM
- (SELECT argMax(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', ''), person.version) AS properties___name,
- 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, 'name'), ''), 'null'), '^"|"$', ''), 'test'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.properties___name, 'test'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto'))
- UNION DISTINCT (
- (SELECT source.id AS id
- FROM
- (SELECT actor_id AS actor_id,
- count() AS event_count,
- groupUniqArray(distinct_id) AS event_distinct_ids,
- 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 ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 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
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')) SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_extra.2
- '''
-
- SELECT if(behavior_query.person_id = '00000000-0000-0000-0000-000000000000', person.person_id, behavior_query.person_id) AS id
- FROM
- (SELECT if(not(empty(pdi.distinct_id)), pdi.person_id, e.person_id) AS person_id,
- countIf(timestamp > now() - INTERVAL 1 week
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_None_level_level_0_level_1_0
- FROM events e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 1 week
- GROUP BY person_id) behavior_query
- FULL OUTER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = behavior_query.person_id
- WHERE 1 = 1
- AND (((id IN
- (SELECT person_id
- FROM cohortpeople
- WHERE cohort_id = 99999
- AND team_id = 99999))
- AND (coalesce(performed_event_condition_None_level_level_0_level_1_0, false)))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_extra.3
- '''
-
- SELECT count(DISTINCT person_id)
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 0
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_extra.4
- '''
- (
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
- 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, 'name'), ''), 'null'), '^"|"$', ''), 'test'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.properties___name, 'test'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto'))
- UNION DISTINCT (
- (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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')) SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_extra.5
- '''
-
- SELECT if(behavior_query.person_id = '00000000-0000-0000-0000-000000000000', person.person_id, behavior_query.person_id) AS id
- FROM
- (SELECT if(not(empty(pdi.distinct_id)), pdi.person_id, e.person_id) AS person_id,
- countIf(timestamp > now() - INTERVAL 1 week
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_None_level_level_0_level_1_level_0_0
- FROM events e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 1 week
- GROUP BY person_id) behavior_query
- FULL OUTER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = behavior_query.person_id
- WHERE 1 = 1
- AND ((((has(['test'], replaceRegexpAll(JSONExtractRaw(person_props, 'name'), '^"|"$', ''))))
- OR ((coalesce(performed_event_condition_None_level_level_0_level_1_level_0_0, false))))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_extra.6
- '''
- (
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
- 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, 'name'), ''), 'null'), '^"|"$', ''), 'test'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.properties___name, 'test'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto'))
- UNION DISTINCT (
- (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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')) SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_extra.7
- '''
-
- SELECT if(behavior_query.person_id = '00000000-0000-0000-0000-000000000000', person.person_id, behavior_query.person_id) AS id
- FROM
- (SELECT if(not(empty(pdi.distinct_id)), pdi.person_id, e.person_id) AS person_id,
- countIf(timestamp > now() - INTERVAL 1 week
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_None_level_level_0_level_1_level_0_0
- FROM events e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 1 week
- GROUP BY person_id) behavior_query
- FULL OUTER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = behavior_query.person_id
- WHERE 1 = 1
- AND ((((has(['test'], replaceRegexpAll(JSONExtractRaw(person_props, 'name'), '^"|"$', ''))))
- OR ((coalesce(performed_event_condition_None_level_level_0_level_1_level_0_0, false))))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_extra.8
- '''
- (
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
- 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, 'name'), ''), 'null'), '^"|"$', ''), 'test'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.properties___name, 'test'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto'))
- UNION DISTINCT (
- (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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')) SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_cohort_filter_with_extra.9
- '''
-
- SELECT if(behavior_query.person_id = '00000000-0000-0000-0000-000000000000', person.person_id, behavior_query.person_id) AS id
- FROM
- (SELECT if(not(empty(pdi.distinct_id)), pdi.person_id, e.person_id) AS person_id,
- countIf(timestamp > now() - INTERVAL 1 week
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_None_level_level_0_level_1_level_0_0
- FROM events e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 1 week
- GROUP BY person_id) behavior_query
- FULL OUTER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = behavior_query.person_id
- WHERE 1 = 1
- AND ((((has(['test'], replaceRegexpAll(JSONExtractRaw(person_props, 'name'), '^"|"$', ''))))
- OR ((coalesce(performed_event_condition_None_level_level_0_level_1_level_0_0, false))))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_performed_event_poe_override
- '''
-
- (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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_performed_event_poe_override.1
- '''
-
- SELECT behavior_query.person_id AS id
- FROM
- (SELECT if(not(empty(overrides.distinct_id)), overrides.person_id, e.person_id) AS person_id,
- countIf(timestamp > 'explicit_redacted_timestamp'
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_None_level_level_0_level_0_0
- FROM events 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 ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 8 day
- GROUP BY person_id) behavior_query
- WHERE 1 = 1
- AND (((coalesce(performed_event_condition_None_level_level_0_level_0_0, false)))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_performed_event_sequence
- '''
-
- (SELECT source.id AS id
- FROM
- (SELECT aggregation_target AS actor_id,
- actor_id AS id
- FROM
- (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1)])))) AS events_array,
- [''] AS prop,
- arrayJoin(aggregate_funnel(2, 259200, 'first_touch', 'ordered', prop, [], arrayFilter((x, x_before, x_after) -> not(and(ifNull(lessOrEquals(length(x.4), 1), 0), ifNull(equals(x.4, x_before.4), isNull(x.4)
- and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)
- and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)
- and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)
- and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,
- af_tuple.1 AS step_reached,
- plus(af_tuple.1, 1) AS steps,
- af_tuple.2 AS breakdown,
- af_tuple.3 AS timings,
- af_tuple.5 AS steps_bitfield,
- aggregation_target AS aggregation_target
- FROM
- (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,
- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,
- e.uuid AS uuid,
- e.`$session_id` AS `$session_id`,
- e.`$window_id` AS `$window_id`,
- if(equals(e.event, '$pageview'), 1, 0) AS step_0,
- if(equals(e.event, '$pageview'), 1, 0) AS step_1
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('today', 6, 'UTC'))), in(e.event, tuple('$pageview'))), or(ifNull(equals(step_0, 1), 0), ifNull(equals(step_1, 1), 0))))
- GROUP BY aggregation_target
- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
- WHERE bitTest(steps_bitfield, 1)
- ORDER BY aggregation_target ASC SETTINGS join_algorithm='auto') AS source
- ORDER BY source.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_performed_event_sequence.1
- '''
-
- SELECT funnel_query.person_id AS id
- FROM
- (SELECT person_id,
- max(if(event = '$pageview'
- AND event_0_latest_0 < event_0_latest_1
- AND event_0_latest_1 <= event_0_latest_0 + INTERVAL 3 day, 2, 1)) = 2 AS steps_0
- FROM
- (SELECT person_id,
- event,
- properties,
- distinct_id, timestamp, event_0_latest_0,
- min(event_0_latest_1) over (PARTITION by person_id
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) event_0_latest_1
- FROM
- (SELECT if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) AS person_id,
- event,
- properties,
- distinct_id, timestamp, if(event = '$pageview'
- AND timestamp > now() - INTERVAL 7 day, 1, 0) AS event_0_step_0,
- if(event_0_step_0 = 1, timestamp, null) AS event_0_latest_0,
- if(event = '$pageview'
- AND timestamp > now() - INTERVAL 7 day, 1, 0) AS event_0_step_1,
- if(event_0_step_1 = 1, timestamp, null) AS event_0_latest_1
- FROM events AS e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview', '$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 7 day))
- GROUP BY person_id) funnel_query
- WHERE 1 = 1
- AND (((steps_0))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_performed_event_sequence_and_clause_with_additional_event
- '''
-
- (SELECT source.id AS id
- FROM
- (SELECT aggregation_target AS actor_id,
- actor_id AS id
- FROM
- (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1)])))) AS events_array,
- [''] AS prop,
- arrayJoin(aggregate_funnel(2, 259200, 'first_touch', 'ordered', prop, [], arrayFilter((x, x_before, x_after) -> not(and(ifNull(lessOrEquals(length(x.4), 1), 0), ifNull(equals(x.4, x_before.4), isNull(x.4)
- and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)
- and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)
- and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)
- and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,
- af_tuple.1 AS step_reached,
- plus(af_tuple.1, 1) AS steps,
- af_tuple.2 AS breakdown,
- af_tuple.3 AS timings,
- af_tuple.5 AS steps_bitfield,
- aggregation_target AS aggregation_target
- FROM
- (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,
- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,
- e.uuid AS uuid,
- e.`$session_id` AS `$session_id`,
- e.`$window_id` AS `$window_id`,
- if(equals(e.event, '$pageview'), 1, 0) AS step_0,
- if(equals(e.event, '$pageview'), 1, 0) AS step_1
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('today', 6, 'UTC'))), in(e.event, tuple('$pageview'))), or(ifNull(equals(step_0, 1), 0), ifNull(equals(step_1, 1), 0))))
- GROUP BY aggregation_target
- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
- WHERE bitTest(steps_bitfield, 1)
- ORDER BY aggregation_target ASC SETTINGS join_algorithm='auto') AS source
- ORDER BY source.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')
- UNION DISTINCT
- (SELECT person_id AS id
- FROM
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id,
- count() AS `count()`
- FROM events
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), equals(events.event, '$new_view'), less(events.timestamp, toDateTime64('today', 6, 'UTC')), greater(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))
- GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)
- HAVING ifNull(greaterOrEquals(count(), 1), 0)
- ORDER BY count() DESC)
- LIMIT 1000000000) SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_performed_event_sequence_and_clause_with_additional_event.1
- '''
-
- SELECT funnel_query.person_id AS id
- FROM
- (SELECT person_id,
- max(if(event = '$pageview'
- AND event_0_latest_0 < event_0_latest_1
- AND event_0_latest_1 <= event_0_latest_0 + INTERVAL 3 day, 2, 1)) = 2 AS steps_0,
- countIf(timestamp > now() - INTERVAL 1 week
- AND timestamp < now()
- AND event = '$new_view'
- AND 1=1) >= 1 AS performed_event_multiple_condition_None_level_level_0_level_1_0
- FROM
- (SELECT person_id,
- event,
- properties,
- distinct_id, timestamp, event_0_latest_0,
- min(event_0_latest_1) over (PARTITION by person_id
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) event_0_latest_1
- FROM
- (SELECT if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) AS person_id,
- event,
- properties,
- distinct_id, timestamp, if(event = '$pageview'
- AND timestamp > now() - INTERVAL 7 day, 1, 0) AS event_0_step_0,
- if(event_0_step_0 = 1, timestamp, null) AS event_0_latest_0,
- if(event = '$pageview'
- AND timestamp > now() - INTERVAL 7 day, 1, 0) AS event_0_step_1,
- if(event_0_step_1 = 1, timestamp, null) AS event_0_latest_1
- FROM events AS e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$new_view', '$pageview', '$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 1 week))
- GROUP BY person_id) funnel_query
- WHERE 1 = 1
- AND (((steps_0)
- OR (coalesce(performed_event_multiple_condition_None_level_level_0_level_1_0, false)))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_performed_event_sequence_with_person_properties
- '''
-
- (SELECT source.id AS id
- FROM
- (SELECT aggregation_target AS actor_id,
- actor_id AS id
- FROM
- (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1)])))) AS events_array,
- [''] AS prop,
- arrayJoin(aggregate_funnel(2, 259200, 'first_touch', 'ordered', prop, [], arrayFilter((x, x_before, x_after) -> not(and(ifNull(lessOrEquals(length(x.4), 1), 0), ifNull(equals(x.4, x_before.4), isNull(x.4)
- and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)
- and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)
- and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)
- and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,
- af_tuple.1 AS step_reached,
- plus(af_tuple.1, 1) AS steps,
- af_tuple.2 AS breakdown,
- af_tuple.3 AS timings,
- af_tuple.5 AS steps_bitfield,
- aggregation_target AS aggregation_target
- FROM
- (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,
- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,
- e.uuid AS uuid,
- e.`$session_id` AS `$session_id`,
- e.`$window_id` AS `$window_id`,
- if(equals(e.event, '$pageview'), 1, 0) AS step_0,
- if(equals(e.event, '$pageview'), 1, 0) AS step_1
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('today', 6, 'UTC'))), in(e.event, tuple('$pageview'))), or(ifNull(equals(step_0, 1), 0), ifNull(equals(step_1, 1), 0))))
- GROUP BY aggregation_target
- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
- WHERE bitTest(steps_bitfield, 1)
- ORDER BY aggregation_target ASC SETTINGS join_algorithm='auto') AS source
- ORDER BY source.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') INTERSECT DISTINCT
- (SELECT person_id AS id
- FROM
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id,
- count() AS `count()`
- FROM events
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), equals(events.event, '$pageview'), less(events.timestamp, toDateTime64('today', 6, 'UTC')), greater(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))
- GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)
- HAVING ifNull(greaterOrEquals(count(), 1), 0)
- ORDER BY count() DESC)
- LIMIT 1000000000) INTERSECT DISTINCT
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
- 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, 'email'), ''), 'null'), '^"|"$', ''), '[email protected]'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.properties___email, '[email protected]'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_performed_event_sequence_with_person_properties.1
- '''
-
- SELECT person.person_id AS id
- FROM
- (SELECT person_id,
- max(if(event = '$pageview'
- AND event_0_latest_0 < event_0_latest_1
- AND event_0_latest_1 <= event_0_latest_0 + INTERVAL 3 day, 2, 1)) = 2 AS steps_0,
- countIf(timestamp > now() - INTERVAL 1 week
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) >= 1 AS performed_event_multiple_condition_None_level_level_0_level_1_0
- FROM
- (SELECT person_id,
- event,
- properties,
- distinct_id, timestamp, event_0_latest_0,
- min(event_0_latest_1) over (PARTITION by person_id
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) event_0_latest_1
- FROM
- (SELECT if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) AS person_id,
- event,
- properties,
- distinct_id, timestamp, if(event = '$pageview'
- AND timestamp > now() - INTERVAL 7 day, 1, 0) AS event_0_step_0,
- if(event_0_step_0 = 1, timestamp, null) AS event_0_latest_0,
- if(event = '$pageview'
- AND timestamp > now() - INTERVAL 7 day, 1, 0) AS event_0_step_1,
- if(event_0_step_1 = 1, timestamp, null) AS event_0_latest_1
- FROM events AS e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview', '$pageview', '$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 1 week))
- GROUP BY person_id) funnel_query
- INNER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = funnel_query.person_id
- WHERE 1 = 1
- AND (((steps_0)
- AND (coalesce(performed_event_multiple_condition_None_level_level_0_level_1_0, false)))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_performed_event_with_event_filters_and_explicit_date
- '''
-
- (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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$filter_prop'), ''), 'null'), '^"|"$', ''), 'something'), 0), 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
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_performed_event_with_event_filters_and_explicit_date.1
- '''
-
- SELECT behavior_query.person_id AS id
- FROM
- (SELECT if(not(empty(pdi.distinct_id)), pdi.person_id, e.person_id) AS person_id,
- countIf(timestamp > 'explicit_redacted_timestamp'
- AND timestamp < now()
- AND event = '$pageview'
- AND (has(['something'], replaceRegexpAll(JSONExtractRaw(properties, '$filter_prop'), '^"|"$', '')))) > 0 AS performed_event_condition_None_level_level_0_level_0_0
- FROM events e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 4 day
- GROUP BY person_id) behavior_query
- WHERE 1 = 1
- AND (((coalesce(performed_event_condition_None_level_level_0_level_0_0, false)))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_person
- '''
-
- (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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')
- UNION DISTINCT
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, '$sample_field'), ''), 'null'), '^"|"$', '')), person.version), 1) AS `properties___$sample_field`,
- 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, '$sample_field'), ''), 'null'), '^"|"$', ''), '[email protected]'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.`properties___$sample_field`, '[email protected]'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_person.1
- '''
-
- SELECT if(behavior_query.person_id = '00000000-0000-0000-0000-000000000000', person.person_id, behavior_query.person_id) AS id
- FROM
- (SELECT if(not(empty(pdi.distinct_id)), pdi.person_id, e.person_id) AS person_id,
- countIf(timestamp > now() - INTERVAL 1 week
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_None_level_level_0_level_0_0
- FROM events e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 1 week
- GROUP BY person_id) behavior_query
- FULL OUTER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = behavior_query.person_id
- WHERE 1 = 1
- AND (((coalesce(performed_event_condition_None_level_level_0_level_0_0, false))
- OR (has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(person_props, '$sample_field'), '^"|"$', ''))))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_person_materialized
- '''
-
- (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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')
- UNION DISTINCT
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(nullIf(nullIf(person.`pmat_$sample_field`, ''), 'null')), person.version), 1) AS `properties___$sample_field`,
- 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), equals(where_optimization.`pmat_$sample_field`, '[email protected]')))))
- GROUP BY person.id
- HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.`properties___$sample_field`, '[email protected]'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_person_materialized.1
- '''
-
- SELECT if(behavior_query.person_id = '00000000-0000-0000-0000-000000000000', person.person_id, behavior_query.person_id) AS id
- FROM
- (SELECT if(not(empty(pdi.distinct_id)), pdi.person_id, e.person_id) AS person_id,
- countIf(timestamp > now() - INTERVAL 1 week
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_None_level_level_0_level_0_0
- FROM events e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 1 week
- GROUP BY person_id) behavior_query
- FULL OUTER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id,
- argMax(pmat_$sample_field, version) as pmat_$sample_field
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = behavior_query.person_id
- WHERE 1 = 1
- AND (((coalesce(performed_event_condition_None_level_level_0_level_0_0, false))
- OR (has(['[email protected]'], "pmat_$sample_field")))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_person_properties_with_pushdowns
- '''
- (
- (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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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('today', 6, 'UTC')), lessOrEquals(timestamp, toDateTime64('today', 6, 'UTC')), equals(e.event, '$pageview')))
- GROUP BY actor_id) AS source
- ORDER BY source.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')
- UNION DISTINCT
- (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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')
- UNION DISTINCT
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
- 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, 'name'), ''), 'null'), '^"|"$', ''), 'special'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.properties___name, 'special'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')) INTERSECT DISTINCT (
- (SELECT source.id AS id
- FROM
- (SELECT actor_id AS actor_id,
- count() AS event_count,
- groupUniqArray(distinct_id) AS event_distinct_ids,
- actor_id AS id
- FROM
- (SELECT min(toTimeZone(e.timestamp, 'UTC')) AS min_timestamp,
- minIf(toTimeZone(e.timestamp, 'UTC'), greaterOrEquals(toTimeZone(e.timestamp, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))) AS min_timestamp_with_condition,
- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS actor_id,
- argMin(e.uuid, toTimeZone(e.timestamp, 'UTC')) AS uuid,
- argMin(e.distinct_id, toTimeZone(e.timestamp, 'UTC')) AS distinct_id
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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), lessOrEquals(e.timestamp, toDateTime64('today', 6, 'UTC')), and(equals(e.event, '$autocapture'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://posthog.com/feedback/123'), 0)))
- GROUP BY if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)
- HAVING and(ifNull(equals(min_timestamp, min_timestamp_with_condition), isNull(min_timestamp)
- and isNull(min_timestamp_with_condition)), ifNull(notEquals(min_timestamp, fromUnixTimestamp(0)), isNotNull(min_timestamp)
- or isNotNull(fromUnixTimestamp(0)))))
- GROUP BY actor_id) AS source
- ORDER BY source.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') INTERSECT DISTINCT
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
- 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, 'email'), ''), 'null'), '^"|"$', ''), '[email protected]'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.properties___email, '[email protected]'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')) SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_person_properties_with_pushdowns.1
- '''
-
- SELECT if(behavior_query.person_id = '00000000-0000-0000-0000-000000000000', person.person_id, behavior_query.person_id) AS id
- FROM
- (SELECT if(not(empty(pdi.distinct_id)), pdi.person_id, e.person_id) AS person_id,
- countIf(timestamp > now() - INTERVAL 1 day
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_None_level_level_0_level_0_level_0_0,
- countIf(timestamp > now() - INTERVAL 2 week
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_None_level_level_0_level_0_level_1_0,
- minIf(timestamp, ((replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', '') = 'https://posthog.com/feedback/123'
- AND event = '$autocapture'))) >= now() - INTERVAL 2 week
- AND minIf(timestamp, ((replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', '') = 'https://posthog.com/feedback/123'
- AND event = '$autocapture'))) < now() as first_time_condition_None_level_level_0_level_1_level_0_0
- FROM events e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview', '$pageview', '$autocapture']
- GROUP BY person_id) behavior_query
- FULL OUTER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (((has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', ''))))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (((has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', ''))))) SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = behavior_query.person_id
- WHERE 1 = 1
- AND ((((coalesce(performed_event_condition_None_level_level_0_level_0_level_0_0, false))
- OR (coalesce(performed_event_condition_None_level_level_0_level_0_level_1_0, false))
- OR (has(['special'], replaceRegexpAll(JSONExtractRaw(person_props, 'name'), '^"|"$', ''))))
- AND ((coalesce(first_time_condition_None_level_level_0_level_1_level_0_0, false))))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_person_props_only
- '''
- (
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
- 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, 'email'), ''), 'null'), '^"|"$', ''), '[email protected]'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.properties___email, '[email protected]'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')
- UNION DISTINCT
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
- 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, 'email'), ''), 'null'), '^"|"$', ''), '[email protected]'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.properties___email, '[email protected]'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto'))
- UNION DISTINCT (
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
- 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, 'name'), ''), 'null'), '^"|"$', ''), 'test3'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.properties___name, 'test3'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') INTERSECT DISTINCT
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
- 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, 'email'), ''), 'null'), '^"|"$', ''), '[email protected]'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.properties___email, '[email protected]'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')) SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_person_props_only.1
- '''
-
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (((has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '')))
- OR (has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', ''))))
- OR ((has(['test3'], replaceRegexpAll(JSONExtractRaw(properties, 'name'), '^"|"$', '')))
- AND (has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', ''))))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (((has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '')))
- OR (has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', ''))))
- OR ((has(['test3'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'name'), '^"|"$', '')))
- AND (has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', ''))))) SETTINGS optimize_aggregation_in_order = 1
- '''
-# ---
-# name: TestCohortQuery.test_precalculated_cohort_filter_with_extra_filters
- '''
-
- SELECT count(DISTINCT person_id)
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 0
- '''
-# ---
-# name: TestCohortQuery.test_precalculated_cohort_filter_with_extra_filters.1
- '''
-
- (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 and(equals(cohortpeople.team_id, 99999), in(tuple(cohortpeople.cohort_id, cohortpeople.version), [(99999, 0)]))) AS cohort_people
- WHERE and(ifNull(equals(cohort_people.cohort_id, 99999), 0), ifNull(equals(cohort_people.team_id, 99999), 0))
- LIMIT 1000000000)
- UNION DISTINCT
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
- 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, 'name'), ''), 'null'), '^"|"$', ''), 'test2'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.properties___name, 'test2'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_precalculated_cohort_filter_with_extra_filters.2
- '''
-
- (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 and(equals(cohortpeople.team_id, 99999), in(tuple(cohortpeople.cohort_id, cohortpeople.version), [(99999, 0)]))) AS cohort_people
- WHERE and(ifNull(equals(cohort_people.cohort_id, 99999), 0), ifNull(equals(cohort_people.team_id, 99999), 0))
- LIMIT 1000000000)
- UNION DISTINCT
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
- 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, 'name'), ''), 'null'), '^"|"$', ''), 'test2'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.properties___name, 'test2'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_precalculated_cohort_filter_with_extra_filters.3
- '''
-
- SELECT person.person_id AS id
- FROM
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person
- WHERE 1 = 1
- AND (((id IN
- (SELECT person_id
- FROM cohortpeople
- WHERE cohort_id = 99999
- AND team_id = 99999))
- OR (has(['test2'], replaceRegexpAll(JSONExtractRaw(person_props, 'name'), '^"|"$', ''))))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_precalculated_cohort_filter_with_extra_filters.4
- '''
-
- (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 and(equals(cohortpeople.team_id, 99999), in(tuple(cohortpeople.cohort_id, cohortpeople.version), [(99999, 0)]))) AS cohort_people
- WHERE and(ifNull(equals(cohort_people.cohort_id, 99999), 0), ifNull(equals(cohort_people.team_id, 99999), 0))
- LIMIT 1000000000)
- UNION DISTINCT
- (SELECT persons.id AS id
- FROM
- (SELECT argMax(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', ''), person.version) AS properties___name,
- 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, 'name'), ''), 'null'), '^"|"$', ''), 'test2'), 0)))))
- GROUP BY person.id
- HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
- WHERE ifNull(equals(persons.properties___name, 'test2'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1
- '''
-# ---
-# name: TestCohortQuery.test_precalculated_cohort_filter_with_extra_filters.5
- '''
-
- SELECT person.person_id AS id
- FROM
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person
- WHERE 1 = 1
- AND (((id IN
- (SELECT person_id
- FROM cohortpeople
- WHERE cohort_id = 99999
- AND team_id = 99999 ))
- OR (has(['test2'], replaceRegexpAll(JSONExtractRaw(person_props, 'name'), '^"|"$', ''))))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_static_cohort_filter
- '''
-
- (SELECT person_static_cohort.person_id AS id
- FROM person_static_cohort
- WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999), equals(person_static_cohort.team_id, 99999))
- LIMIT 1000000000) SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_static_cohort_filter.1
- '''
-
- SELECT person.person_id AS id
- FROM
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person
- WHERE 1 = 1
- AND (((id IN
- (SELECT person_id as id
- FROM person_static_cohort
- WHERE cohort_id = 99999
- AND team_id = 99999)))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_static_cohort_filter_with_extra
- '''
-
- (SELECT person_static_cohort.person_id AS id
- FROM person_static_cohort
- WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999), equals(person_static_cohort.team_id, 99999))
- LIMIT 1000000000) INTERSECT DISTINCT
- (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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_static_cohort_filter_with_extra.1
- '''
-
- SELECT if(behavior_query.person_id = '00000000-0000-0000-0000-000000000000', person.person_id, behavior_query.person_id) AS id
- FROM
- (SELECT if(not(empty(pdi.distinct_id)), pdi.person_id, e.person_id) AS person_id,
- countIf(timestamp > now() - INTERVAL 1 week
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_None_level_level_0_level_1_0
- FROM events e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 1 week
- GROUP BY person_id) behavior_query
- FULL OUTER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = behavior_query.person_id
- WHERE 1 = 1
- AND (((id IN
- (SELECT person_id as id
- FROM person_static_cohort
- WHERE cohort_id = 99999
- AND team_id = 99999))
- AND (coalesce(performed_event_condition_None_level_level_0_level_1_0, false)))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_static_cohort_filter_with_extra.2
- '''
- (
- (SELECT person_static_cohort.person_id AS id
- FROM person_static_cohort
- WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999), equals(person_static_cohort.team_id, 99999))
- LIMIT 1000000000))
- UNION DISTINCT (
- (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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')) SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_static_cohort_filter_with_extra.3
- '''
-
- SELECT if(behavior_query.person_id = '00000000-0000-0000-0000-000000000000', person.person_id, behavior_query.person_id) AS id
- FROM
- (SELECT if(not(empty(pdi.distinct_id)), pdi.person_id, e.person_id) AS person_id,
- countIf(timestamp > now() - INTERVAL 1 week
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_None_level_level_0_level_1_level_0_0
- FROM events e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 1 week
- GROUP BY person_id) behavior_query
- FULL OUTER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = behavior_query.person_id
- WHERE 1 = 1
- AND ((((id IN
- (SELECT person_id as id
- FROM person_static_cohort
- WHERE cohort_id = 99999
- AND team_id = 99999)))
- OR ((coalesce(performed_event_condition_None_level_level_0_level_1_level_0_0, false))))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_unwrapping_static_cohort_filter_hidden_in_layers_of_cohorts
- '''
-
- SELECT count(DISTINCT person_id)
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 0
- '''
-# ---
-# name: TestCohortQuery.test_unwrapping_static_cohort_filter_hidden_in_layers_of_cohorts.1
- '''
-
- (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 and(equals(cohortpeople.team_id, 99999), in(tuple(cohortpeople.cohort_id, cohortpeople.version), [(99999, 0)]))) AS cohort_people
- WHERE and(ifNull(equals(cohort_people.cohort_id, 99999), 0), ifNull(equals(cohort_people.team_id, 99999), 0))
- LIMIT 1000000000)
- UNION DISTINCT
- (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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestCohortQuery.test_unwrapping_static_cohort_filter_hidden_in_layers_of_cohorts.2
- '''
-
- SELECT if(behavior_query.person_id = '00000000-0000-0000-0000-000000000000', person.person_id, behavior_query.person_id) AS id
- FROM
- (SELECT if(not(empty(pdi.distinct_id)), pdi.person_id, e.person_id) AS person_id,
- countIf(timestamp > now() - INTERVAL 1 week
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_None_level_level_0_level_1_0
- FROM events e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 1 week
- GROUP BY person_id) behavior_query
- FULL OUTER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = behavior_query.person_id
- WHERE 1 = 1
- AND (((id IN
- (SELECT person_id
- FROM cohortpeople
- WHERE cohort_id = 99999
- AND team_id = 99999))
- OR (coalesce(performed_event_condition_None_level_level_0_level_1_0, false)))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
-# name: TestCohortQuery.test_unwrapping_static_cohort_filter_hidden_in_layers_of_cohorts.3
- '''
-
- (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 and(equals(cohortpeople.team_id, 99999), in(tuple(cohortpeople.cohort_id, cohortpeople.version), [(99999, 0)]))) AS cohort_people
- WHERE and(ifNull(equals(cohort_people.cohort_id, 99999), 0), ifNull(equals(cohort_people.team_id, 99999), 0))
- LIMIT 1000000000)
- UNION DISTINCT
- (SELECT source.id AS id
- FROM
- (SELECT actor_id AS actor_id,
- count() AS event_count,
- groupUniqArray(distinct_id) AS event_distinct_ids,
- 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 ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 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
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto') SETTINGS readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1
- '''
-# ---
-# name: TestCohortQuery.test_unwrapping_static_cohort_filter_hidden_in_layers_of_cohorts.4
- '''
-
- SELECT if(behavior_query.person_id = '00000000-0000-0000-0000-000000000000', person.person_id, behavior_query.person_id) AS id
- FROM
- (SELECT if(not(empty(pdi.distinct_id)), pdi.person_id, e.person_id) AS person_id,
- countIf(timestamp > now() - INTERVAL 1 week
- AND timestamp < now()
- AND event = '$pageview'
- AND 1=1) > 0 AS performed_event_condition_None_level_level_0_level_1_0
- FROM events e
- LEFT OUTER 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 e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview']
- AND timestamp <= now()
- AND timestamp >= now() - INTERVAL 1 week
- GROUP BY person_id) behavior_query
- FULL OUTER JOIN
- (SELECT *,
- id AS person_id
- FROM
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)) person ON person.person_id = behavior_query.person_id
- WHERE 1 = 1
- AND (((id IN
- (SELECT person_id
- FROM cohortpeople
- WHERE cohort_id = 99999
- AND team_id = 99999 ))
- OR (coalesce(performed_event_condition_None_level_level_0_level_1_0, false)))) SETTINGS optimize_aggregation_in_order = 1,
- join_algorithm = 'auto'
- '''
-# ---
diff --git a/ee/clickhouse/queries/test/__snapshots__/test_event_query.ambr b/ee/clickhouse/queries/test/__snapshots__/test_event_query.ambr
index ff28059325fa..f78fc85ee64a 100644
--- a/ee/clickhouse/queries/test/__snapshots__/test_event_query.ambr
+++ b/ee/clickhouse/queries/test/__snapshots__/test_event_query.ambr
@@ -85,18 +85,22 @@
AND event = 'viewed'
AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2021-05-01 00:00:00', 'UTC')), 'UTC')
AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC')
- AND (if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((has(['test'], replaceRegexpAll(JSONExtractRaw(properties, 'name'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((has(['test'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'name'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1))
+ AND (if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) IN (
+ (SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
+ 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, 'name'), ''), 'null'), '^"|"$', ''), 'test'), 0)))))
+ GROUP BY person.id
+ HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
+ WHERE ifNull(equals(persons.properties___name, 'test'), 0)
+ ORDER BY persons.id ASC
+ LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto')))
'''
# ---
# name: TestEventQuery.test_denormalised_props
@@ -163,18 +167,22 @@
AND event = '$pageview'
AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2021-05-01 00:00:00', 'UTC')), 'UTC')
AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC')
- AND (if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((has(['test'], replaceRegexpAll(JSONExtractRaw(properties, 'name'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((has(['test'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'name'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1))
+ AND (if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) IN (
+ (SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
+ 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, 'name'), ''), 'null'), '^"|"$', ''), 'test'), 0)))))
+ GROUP BY person.id
+ HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
+ WHERE ifNull(equals(persons.properties___name, 'test'), 0)
+ ORDER BY persons.id ASC
+ LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto')))
'''
# ---
# name: TestEventQuery.test_entity_filtered_by_multiple_session_duration_filters
diff --git a/ee/clickhouse/queries/test/test_cohort_query.py b/ee/clickhouse/queries/test/test_cohort_query.py
index 0aa3bce05f1d..78b1b3797d81 100644
--- a/ee/clickhouse/queries/test/test_cohort_query.py
+++ b/ee/clickhouse/queries/test/test_cohort_query.py
@@ -11,24 +11,21 @@ from posthog.test.base import (
_create_person,
also_test_with_materialized_columns,
flush_persons_and_events,
- snapshot_clickhouse_queries,
)
+from rest_framework.exceptions import ValidationError
+
from posthog.schema import PersonsOnEventsMode
from posthog.clickhouse.client import sync_execute
-from posthog.constants import PropertyOperatorType
from posthog.hogql_queries.hogql_cohort_query import TestWrapperCohortQuery as CohortQuery
from posthog.models import Team
from posthog.models.cohort import Cohort
from posthog.models.filters.filter import Filter
-from posthog.models.property import Property, PropertyGroup
from products.actions.backend.models.action import Action
from products.event_definitions.backend.models.property_definition import PropertyDefinition
-from ee.clickhouse.queries.enterprise_cohort_query import check_negation_clause
-
def _make_event_sequence(
team,
@@ -62,37 +59,20 @@ def _create_cohort(**kwargs):
return cohort
-def execute(filter: Filter, team: Team, max_retries: int = 5):
- # Ensure tables are fully merged before comparing HogQL and raw SQL results.
- # Due to ClickHouse's eventual consistency with CollapsingMergeTree and other
- # MergeTree variants, HogQL and raw SQL queries may see slightly different states.
- # We retry the comparison to handle transient inconsistencies.
+def execute(filter: Filter, team: Team):
+ # Ensure tables are fully merged before reading membership. ClickHouse's eventual
+ # consistency (CollapsingMergeTree and other MergeTree variants) means cohortpeople /
+ # person / events may not be fully merged immediately after the test writes.
sync_execute("OPTIMIZE TABLE cohortpeople FINAL")
sync_execute("OPTIMIZE TABLE person FINAL")
sync_execute("OPTIMIZE TABLE sharded_events FINAL")
- last_error: AssertionError | None = None
- for attempt in range(max_retries):
- cohort_query = CohortQuery(filter=filter, team=team)
- q, params = cohort_query.get_query()
- res = sync_execute(q, {**params, **filter.hogql_context.values})
- try:
- unittest.TestCase().assertCountEqual(res, cohort_query.hogql_result.results)
- assert ["id"] == cohort_query.hogql_result.columns
- return res, q, params
- except AssertionError as e:
- last_error = e
- if attempt < max_retries - 1:
- # Force another merge before retrying
- sync_execute("OPTIMIZE TABLE cohortpeople FINAL")
- sync_execute("OPTIMIZE TABLE person FINAL")
- sync_execute("OPTIMIZE TABLE sharded_events FINAL")
- assert last_error is not None # Always set since loop runs at least once
- raise last_error
+ cohort_query = CohortQuery(filter=filter, team=team)
+ assert ["id"] == cohort_query.hogql_result.columns
+ return cohort_query.hogql_result.results
class TestCohortQuery(ClickhouseTestMixin, BaseTest):
- @snapshot_clickhouse_queries
def test_basic_query(self):
action1 = Action.objects.create(
team=self.team,
@@ -219,10 +199,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
filter = Filter(data=data)
- res, q, params = execute(filter, self.team)
-
- # Since all props should be pushed down here, there should be no full outer join!
- assert "FULL OUTER JOIN" not in q
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
@@ -239,10 +216,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
filter = Filter(data=data)
- res, q, params = execute(filter, self.team)
-
- # No push down because of the person property in an OR
- assert "FULL OUTER JOIN" in q
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
"""
@@ -292,11 +266,10 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
- @snapshot_clickhouse_queries
def test_performed_event_poe_override(self):
p1 = _create_person(
team_id=self.team.pk,
@@ -344,12 +317,10 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
self.team.modifiers = {"personsOnEventsMode": PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS}
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
- assert "if(not(empty(overrides.distinct_id)), overrides.person_id, e.person_id) AS person_id" in q
- @snapshot_clickhouse_queries
def test_performed_event_with_event_filters_and_explicit_date(self):
with freeze_time(datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)):
p1 = _create_person(
@@ -411,7 +382,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
@@ -480,7 +451,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, _, _ = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
@@ -540,7 +511,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
@@ -611,7 +582,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
@@ -676,7 +647,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert {p2.uuid} == {r[0] for r in res}
@@ -758,7 +729,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert {p1.uuid, p2.uuid, p3.uuid} == {r[0] for r in res}
@@ -833,34 +804,10 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
- def test_stopped_performing_event_raises_if_seq_date_later_than_date(self):
- filter = Filter(
- data={
- "properties": {
- "type": "AND",
- "values": [
- {
- "key": "$pageview",
- "event_type": "events",
- "time_value": 1,
- "time_interval": "day",
- "seq_time_value": 2,
- "seq_time_interval": "day",
- "value": "stopped_performing_event",
- "type": "behavioral",
- }
- ],
- }
- }
- )
-
- with pytest.raises(ValueError):
- CohortQuery(filter=filter, team=self.team).get_query()
-
def test_restarted_performing_event(self):
p1 = _create_person(
team_id=self.team.pk,
@@ -947,34 +894,10 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
- def test_restarted_performing_event_raises_if_seq_date_later_than_date(self):
- filter = Filter(
- data={
- "properties": {
- "type": "AND",
- "values": [
- {
- "key": "$pageview",
- "event_type": "events",
- "time_value": 1,
- "time_interval": "day",
- "seq_time_value": 2,
- "seq_time_interval": "day",
- "value": "restarted_performing_event",
- "type": "behavioral",
- }
- ],
- }
- }
- )
-
- with pytest.raises(ValueError):
- CohortQuery(filter=filter, team=self.team).get_query()
-
def test_performed_event_first_time(self):
_create_person(
team_id=self.team.pk,
@@ -1025,7 +948,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p2.uuid] == [r[0] for r in res]
@@ -1063,7 +986,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
@@ -1101,7 +1024,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
@@ -1155,11 +1078,11 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
filter = Filter(data=data)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert sorted([p1.uuid, p2.uuid, p3.uuid]) == sorted([r[0] for r in res])
data["properties"]["values"][0] |= {"time_value": 2, "total_periods": 3, "min_periods": 3}
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert sorted([p1.uuid, p2.uuid]) == sorted([r[0] for r in res])
def test_performed_event_regularly_with_variable_event_counts_in_each_period(self):
@@ -1203,7 +1126,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p2.uuid] == [r[0] for r in res]
flush_persons_and_events()
@@ -1232,10 +1155,9 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert sorted([p1.uuid, p2.uuid]) == sorted([r[0] for r in res])
- @snapshot_clickhouse_queries
def test_person_props_only(self):
p1 = _create_person(
team_id=self.team.pk,
@@ -1295,14 +1217,10 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
-
- # Since all props should be pushed down here, there should be no full outer join!
- assert "FULL OUTER JOIN" not in q
+ res = execute(filter, self.team)
assert sorted([p1.uuid, p2.uuid, p3.uuid]) == sorted([r[0] for r in res])
- @snapshot_clickhouse_queries
def test_person_properties_with_pushdowns(self):
action1 = Action.objects.create(
team=self.team,
@@ -1427,12 +1345,11 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert sorted([p1.uuid, p3.uuid]) == sorted([r[0] for r in res])
@also_test_with_materialized_columns(person_properties=["$sample_field"])
- @snapshot_clickhouse_queries
def test_person(self):
# satiesfies all conditions
p1 = _create_person(
@@ -1464,107 +1381,10 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events()
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
- def test_earliest_date_clause(self):
- filter = Filter(
- data={
- "properties": {
- "type": "AND",
- "values": [
- {
- "key": "$pageview",
- "event_type": "events",
- "time_value": 1,
- "time_interval": "week",
- "value": "performed_event",
- "type": "behavioral",
- },
- {
- "key": "$pageview",
- "event_type": "events",
- "time_value": 2,
- "time_interval": "week",
- "value": "performed_event_multiple",
- "operator_value": 1,
- "type": "behavioral",
- },
- {
- "key": "$pageview",
- "event_type": "events",
- "time_value": 4,
- "time_interval": "week",
- "seq_time_value": 1,
- "seq_time_interval": "week",
- "value": "stopped_performing_event",
- "type": "behavioral",
- },
- {
- "key": "$pageview",
- "event_type": "events",
- "time_value": 1,
- "time_interval": "week",
- "value": "performed_event",
- "type": "behavioral",
- },
- {
- "key": "$pageview",
- "event_type": "events",
- "operator": "gte",
- "operator_value": 2,
- "time_interval": "week",
- "time_value": 3,
- "total_periods": 3,
- "min_periods": 2,
- "value": "performed_event_regularly",
- "type": "behavioral",
- },
- ],
- }
- }
- )
-
- res, q, params = execute(filter, self.team)
-
- assert "timestamp >= now() - INTERVAL 9 week" in (q % params)
-
- def test_earliest_date_clause_removed_for_started_at_query(self):
- filter = Filter(
- data={
- "properties": {
- "type": "AND",
- "values": [
- {
- "key": "$pageview",
- "event_type": "events",
- "time_value": 2,
- "time_interval": "week",
- "value": "performed_event_first_time",
- "type": "behavioral",
- },
- {
- "key": "$pageview",
- "event_type": "events",
- "operator": "gte",
- "operator_value": 2,
- "time_interval": "week",
- "time_value": 3,
- "total_periods": 3,
- "min_periods": 2,
- "value": "performed_event_regularly",
- "type": "behavioral",
- },
- ],
- }
- }
- )
- query_class = CohortQuery(filter=filter, team=self.team)
- q, params = query_class.get_query()
- assert not query_class._restrict_event_query_by_time
- res, q, params = execute(filter, self.team)
-
def test_negation_raises(self):
_create_person(
team_id=self.team.pk,
@@ -1612,7 +1432,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- with pytest.raises(ValueError):
+ with pytest.raises(ValidationError):
CohortQuery(filter=filter, team=self.team)
def test_negation_with_simplify_filters(self):
@@ -1685,7 +1505,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
team=self.team,
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert sorted([p3.uuid]) == sorted([r[0] for r in res])
def test_negation_dynamic_time_bound_with_performed_event(self):
@@ -1789,7 +1609,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert sorted([p3.uuid, p4.uuid]) == sorted([r[0] for r in res])
@@ -1929,7 +1749,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert sorted([p3.uuid, p4.uuid, p5.uuid, p6.uuid]) == sorted([r[0] for r in res])
def test_cohort_filter(self):
@@ -1956,7 +1776,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
@@ -2102,14 +1922,12 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
cohort.calculate_people_ch(pending_version=0)
with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- q, params = CohortQuery(filter=filter, team=self.team).get_query()
# Precalculated cohorts should not be used as is
# since we want cohort calculation with cohort properties to not be out of sync
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
- @snapshot_clickhouse_queries
def test_precalculated_cohort_filter_with_extra_filters(self):
p1 = _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "test"})
p2 = _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"name": "test2"})
@@ -2142,13 +1960,10 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
cohort.calculate_people_ch(pending_version=0)
with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- # TODO: update
- q, params = CohortQuery(filter=filter, team=self.team).get_query()
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert sorted([p1.uuid, p2.uuid]) == sorted([r[0] for r in res])
- @snapshot_clickhouse_queries
def test_cohort_filter_with_extra(self):
p1 = _create_person(
team_id=self.team.pk,
@@ -2197,7 +2012,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
cohort.calculate_people_ch(pending_version=0)
sync_execute("OPTIMIZE TABLE cohortpeople FINAL")
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert sorted([p2.uuid]) == sorted([r[0] for r in res])
filter = Filter(
@@ -2223,10 +2038,9 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
cohort.calculate_people_ch(pending_version=0)
sync_execute("OPTIMIZE TABLE cohortpeople FINAL")
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert sorted([p1.uuid, p2.uuid]) == sorted([r[0] for r in res])
- @snapshot_clickhouse_queries
def test_cohort_filter_with_another_cohort_with_event_sequence(self):
# passes filters for cohortCeption, but not main cohort
_create_person(
@@ -2312,11 +2126,10 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
)
cohort.calculate_people_ch(pending_version=0)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p2.uuid] == [r[0] for r in res]
- @snapshot_clickhouse_queries
def test_static_cohort_filter(self):
p1 = _create_person(
team_id=self.team.pk,
@@ -2336,11 +2149,10 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
- @snapshot_clickhouse_queries
def test_static_cohort_filter_with_extra(self):
p1 = _create_person(
team_id=self.team.pk,
@@ -2383,7 +2195,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p2.uuid] == [r[0] for r in res]
@@ -2407,11 +2219,10 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
team=self.team,
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert sorted([p1.uuid, p2.uuid]) == sorted([r[0] for r in res])
- @snapshot_clickhouse_queries
def test_performed_event_sequence(self):
p1 = _create_person(
team_id=self.team.pk,
@@ -2458,7 +2269,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
@@ -2527,7 +2338,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
@@ -2594,7 +2405,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert sorted([p1.uuid, p2.uuid]) == sorted([r[0] for r in res])
@@ -2670,11 +2481,10 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
- @snapshot_clickhouse_queries
def test_performed_event_sequence_with_person_properties(self):
with freeze_time(datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)):
p1 = _create_person(
@@ -2778,7 +2588,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
@@ -2864,11 +2674,10 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert [p1.uuid] == [r[0] for r in res]
- @snapshot_clickhouse_queries
def test_performed_event_sequence_and_clause_with_additional_event(self):
with freeze_time(datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)):
p1 = _create_person(
@@ -2939,11 +2748,10 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
}
}
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert {p1.uuid, p2.uuid} == {r[0] for r in res}
- @snapshot_clickhouse_queries
def test_unwrapping_static_cohort_filter_hidden_in_layers_of_cohorts(self):
_create_person(
team_id=self.team.pk,
@@ -3040,7 +2848,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
)
other_cohort.calculate_people_ch(pending_version=0)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert sorted([p2.uuid, p3.uuid]) == sorted([r[0] for r in res])
@@ -3159,7 +2967,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
cohort1.calculate_people_ch(pending_version=0)
cohort2.calculate_people_ch(pending_version=0)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert sorted([p2.uuid]) == sorted([r[0] for r in res])
@@ -3310,7 +3118,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
team=self.team,
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert sorted([p4.uuid]) == sorted([r[0] for r in res])
@@ -3431,7 +3239,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
)
# Execute the filter
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
# Only person 1 should match
assert len(res) == 1
@@ -3495,7 +3303,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
)
# Execute the filter
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
# Person 1 and 2 should match because their emails are in the list
assert len(res) == 2
@@ -3506,207 +3314,6 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
class TestCohortNegationValidation(BaseTest):
- def test_basic_valid_negation_tree(self):
- property_group = PropertyGroup(
- type=PropertyOperatorType.AND,
- values=[
- Property(key="name", value="test", type="person"),
- Property(key="email", value="xxx", type="person", negation=True),
- ],
- )
-
- has_pending_neg, has_reg = check_negation_clause(property_group)
- assert has_pending_neg is False
- assert has_reg is True
-
- def test_valid_negation_tree_with_extra_layers(self):
- property_group = PropertyGroup(
- type=PropertyOperatorType.OR,
- values=[
- PropertyGroup(
- type=PropertyOperatorType.AND,
- values=[Property(key="name", value="test", type="person")],
- ),
- PropertyGroup(
- type=PropertyOperatorType.AND,
- values=[
- PropertyGroup(
- type=PropertyOperatorType.OR,
- values=[
- Property(
- key="email",
- value="xxx",
- type="person",
- negation=True,
- )
- ],
- ),
- PropertyGroup(
- type=PropertyOperatorType.OR,
- values=[Property(key="email", value="xxx", type="person")],
- ),
- ],
- ),
- ],
- )
-
- has_pending_neg, has_reg = check_negation_clause(property_group)
- assert has_pending_neg is False
- assert has_reg is True
-
- def test_invalid_negation_tree_with_extra_layers(self):
- property_group = PropertyGroup(
- type=PropertyOperatorType.OR,
- values=[
- PropertyGroup(
- type=PropertyOperatorType.AND,
- values=[Property(key="name", value="test", type="person")],
- ),
- PropertyGroup(
- type=PropertyOperatorType.AND,
- values=[
- PropertyGroup(
- type=PropertyOperatorType.OR,
- values=[
- Property(
- key="email",
- value="xxx",
- type="person",
- negation=True,
- )
- ],
- ),
- PropertyGroup(
- type=PropertyOperatorType.OR,
- values=[
- Property(
- key="email",
- value="xxx",
- type="person",
- negation=True,
- )
- ],
- ),
- ],
- ),
- ],
- )
-
- has_pending_neg, has_reg = check_negation_clause(property_group)
- assert has_pending_neg is True
- assert has_reg is True
-
- def test_valid_negation_tree_with_extra_layers_recombining_at_top(self):
- property_group = PropertyGroup(
- type=PropertyOperatorType.AND, # top level AND protects the 2 negations from being invalid
- values=[
- PropertyGroup(
- type=PropertyOperatorType.OR,
- values=[Property(key="name", value="test", type="person")],
- ),
- PropertyGroup(
- type=PropertyOperatorType.AND,
- values=[
- PropertyGroup(
- type=PropertyOperatorType.OR,
- values=[
- Property(
- key="email",
- value="xxx",
- type="person",
- negation=True,
- )
- ],
- ),
- PropertyGroup(
- type=PropertyOperatorType.OR,
- values=[
- Property(
- key="email",
- value="xxx",
- type="person",
- negation=True,
- )
- ],
- ),
- ],
- ),
- ],
- )
-
- has_pending_neg, has_reg = check_negation_clause(property_group)
- assert has_pending_neg is False
- assert has_reg is True
-
- def test_invalid_negation_tree_no_positive_filter(self):
- property_group = PropertyGroup(
- type=PropertyOperatorType.AND,
- values=[
- PropertyGroup(
- type=PropertyOperatorType.OR,
- values=[Property(key="name", value="test", type="person", negation=True)],
- ),
- PropertyGroup(
- type=PropertyOperatorType.AND,
- values=[
- PropertyGroup(
- type=PropertyOperatorType.OR,
- values=[
- Property(
- key="email",
- value="xxx",
- type="person",
- negation=True,
- )
- ],
- ),
- PropertyGroup(
- type=PropertyOperatorType.OR,
- values=[
- Property(
- key="email",
- value="xxx",
- type="person",
- negation=True,
- )
- ],
- ),
- ],
- ),
- ],
- )
-
- has_pending_neg, has_reg = check_negation_clause(property_group)
- assert has_pending_neg is True
- assert has_reg is False
-
- def test_empty_property_group(self):
- property_group = PropertyGroup(type=PropertyOperatorType.AND, values=[])
-
- has_pending_neg, has_reg = check_negation_clause(property_group)
- assert has_pending_neg is False
- assert has_reg is False
-
- def test_basic_invalid_negation_tree(self):
- property_group = PropertyGroup(
- type=PropertyOperatorType.AND,
- values=[Property(key="email", value="xxx", type="person", negation=True)],
- )
-
- has_pending_neg, has_reg = check_negation_clause(property_group)
- assert has_pending_neg is True
- assert has_reg is False
-
- def test_basic_valid_negation_tree_with_no_negations(self):
- property_group = PropertyGroup(
- type=PropertyOperatorType.AND,
- values=[Property(key="name", value="test", type="person")],
- )
-
- has_pending_neg, has_reg = check_negation_clause(property_group)
- assert has_pending_neg is False
- assert has_reg is True
-
def test_type_misalignment(self):
PropertyDefinition.objects.create(
team=self.team,
@@ -3756,7 +3363,7 @@ class TestCohortNegationValidation(BaseTest):
team=self.team,
)
- res, q, params = execute(filter, self.team)
+ res = execute(filter, self.team)
assert 1 == len(res)
def test_project_properties(self):
@@ -3838,7 +3445,8 @@ class TestCohortNegationValidation(BaseTest):
assert cohort_query1.clickhouse_query
assert cohort_query2.clickhouse_query
- assert (
- cohort_query1.clickhouse_query.replace(f"team_id, {self.team.pk}", f"team_id, {str(other_team.pk)}")
- == cohort_query2.clickhouse_query
- )
+ # The same cohort definition under two teams of the same project stays team-scoped:
+ # each query references its own team and the two are not identical.
+ assert str(self.team.pk) in cohort_query1.clickhouse_query
+ assert str(other_team.pk) in cohort_query2.clickhouse_query
+ assert cohort_query1.clickhouse_query != cohort_query2.clickhouse_query
diff --git a/ee/clickhouse/queries/test/test_util.py b/ee/clickhouse/queries/test/test_util.py
index 68554010a1a4..1c55379ed398 100644
--- a/ee/clickhouse/queries/test/test_util.py
+++ b/ee/clickhouse/queries/test/test_util.py
@@ -4,8 +4,6 @@ from zoneinfo import ZoneInfo
from freezegun.api import freeze_time
from posthog.test.base import _create_event
-from posthog.hogql.hogql import HogQLContext
-
from posthog.clickhouse.client import sync_execute
from posthog.models.cohort import Cohort
from posthog.queries.breakdown_props import _parse_breakdown_cohorts
@@ -62,6 +60,6 @@ def test_get_earliest_timestamp_with_no_events(db, team):
def test_parse_breakdown_cohort_query(db, team):
action = Action.objects.create(team=team, name="$pageview", steps_json=[{"event": "$pageview"}])
cohort1 = Cohort.objects.create(team=team, groups=[{"action_id": action.pk, "days": 3}], name="cohort1")
- queries, params = _parse_breakdown_cohorts([cohort1], HogQLContext(team_id=team.pk))
+ queries, params = _parse_breakdown_cohorts([cohort1])
assert len(queries) == 1
sync_execute(queries[0], params)
diff --git a/posthog/hogql_queries/hogql_cohort_query.py b/posthog/hogql_queries/hogql_cohort_query.py
index d857265c26c2..a87938c48afe 100644
--- a/posthog/hogql_queries/hogql_cohort_query.py
+++ b/posthog/hogql_queries/hogql_cohort_query.py
@@ -2,7 +2,7 @@ from collections import defaultdict, namedtuple
from copy import deepcopy
from datetime import datetime
from numbers import Number
-from typing import Literal, Optional, Union, cast
+from typing import Any, Literal, Optional, Union, cast
import posthoganalytics
from rest_framework.exceptions import ValidationError
@@ -48,24 +48,150 @@ from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner
from posthog.hogql_queries.events_query_runner import EventsQueryRunner
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models import Cohort, Filter, Property, Team
-from posthog.models.property import PropertyGroup
-from posthog.queries.cohort_query import CohortQuery
-from posthog.queries.foss_cohort_query import (
- INTERVAL_TO_SECONDS,
- FOSSCohortQuery,
- parse_and_validate_positive_integer,
- validate_interval,
-)
+from posthog.models.property import OperatorInterval, PropertyGroup
from posthog.types import AnyPropertyFilter
+INTERVAL_TO_SECONDS = {
+ "minute": 60,
+ "hour": 3600,
+ "day": 86400,
+ "week": 604800,
+ "month": 2592000,
+ "year": 31536000,
+}
+
+
+def validate_interval(interval: Optional[OperatorInterval]) -> OperatorInterval:
+ if interval is None or interval not in INTERVAL_TO_SECONDS.keys():
+ raise ValueError(f"Invalid interval: {interval}")
+ else:
+ return interval
+
+
+def parse_and_validate_positive_integer(value: Optional[Union[str, int]], value_name: str) -> int:
+ if value is None:
+ raise ValueError(f"{value_name} cannot be None")
+ try:
+ parsed_value = int(value)
+ except (ValueError, TypeError):
+ raise ValueError(f"{value_name} must be an integer, got {value}")
+ if parsed_value <= 0:
+ raise ValueError(f"{value_name} must be greater than 0, got {value}")
+ return parsed_value
+
+
+def unwrap_cohort(filter: Filter, team_id: int, team: Optional[Team] = None, cohort: Optional[Cohort] = None) -> Filter:
+ """Flatten cohort-typed properties into nested static/dynamic-cohort PropertyGroups.
+
+ Each ``cohort``/``precalculated-cohort`` property is replaced by an AND group holding a
+ single ``static-cohort``/``dynamic-cohort`` property, while sibling properties are wrapped
+ into AND groups too, propagating negation per De Morgan's law.
+ """
+
+ def _unwrap(property_group: PropertyGroup, negate_group: bool = False) -> PropertyGroup:
+ nonlocal team
+ if len(property_group.values):
+ if isinstance(property_group.values[0], PropertyGroup):
+ # dealing with a list of property groups, so unwrap each one
+ # Propogate the negation to the children and handle as necessary with respect to deMorgan's law
+ if not negate_group:
+ return PropertyGroup(
+ type=property_group.type,
+ values=[_unwrap(v) for v in cast(list[PropertyGroup], property_group.values)],
+ )
+ else:
+ return PropertyGroup(
+ type=(
+ PropertyOperatorType.AND
+ if property_group.type == PropertyOperatorType.OR
+ else PropertyOperatorType.OR
+ ),
+ values=[_unwrap(v, True) for v in cast(list[PropertyGroup], property_group.values)],
+ )
+
+ elif isinstance(property_group.values[0], Property):
+ # dealing with a list of properties
+ # if any single one is a cohort property, unwrap it into a property group
+ # which implies converting everything else in the list into a property group too
+
+ new_property_group_list: list[PropertyGroup] = []
+ for prop in property_group.values:
+ prop = cast(Property, prop)
+ current_negation = prop.negation or False
+ negation_value = not current_negation if negate_group else current_negation
+ if prop.type in ["cohort", "precalculated-cohort"]:
+ try:
+ # Use passed cohort object if it matches the requested cohort ID
+ if cohort is not None and str(cohort.pk) == str(prop.value):
+ prop_cohort = cohort
+ else:
+ # Use passed team object if available, otherwise fetch from database
+ if team is None:
+ team = Team.objects.get(pk=team_id)
+ prop_cohort = Cohort.objects.get(
+ pk=cast(str | int, prop.value), team__project_id=team.project_id
+ )
+ new_property_group_list.append(
+ PropertyGroup(
+ type=PropertyOperatorType.AND,
+ values=[
+ Property(
+ type="static-cohort" if prop_cohort.is_static else "dynamic-cohort",
+ key="id",
+ value=prop_cohort.pk,
+ negation=negation_value,
+ )
+ ],
+ )
+ )
+ except Cohort.DoesNotExist:
+ new_property_group_list.append(
+ PropertyGroup(
+ type=PropertyOperatorType.AND,
+ values=[
+ Property(
+ key="fake_key_01r2ho",
+ value="0",
+ type="person",
+ )
+ ],
+ )
+ )
+ else:
+ prop.negation = negation_value
+ new_property_group_list.append(PropertyGroup(type=PropertyOperatorType.AND, values=[prop]))
+ if not negate_group:
+ return PropertyGroup(type=property_group.type, values=new_property_group_list)
+ else:
+ return PropertyGroup(
+ type=(
+ PropertyOperatorType.AND
+ if property_group.type == PropertyOperatorType.OR
+ else PropertyOperatorType.OR
+ ),
+ values=new_property_group_list,
+ )
+
+ return property_group
+
+ new_props = _unwrap(filter.property_groups)
+ return filter.shallow_clone({"properties": new_props.to_dict()})
+
+
+class TestWrapperCohortQuery:
+ """Runs a filter through HogQLCohortQuery for the cohort-query test suite.
+
+ ``hogql_result`` holds the executed result the tests assert membership against;
+ ``clickhouse_query`` / ``get_query`` expose the generated SQL.
+ """
-class TestWrapperCohortQuery(CohortQuery):
def __init__(self, filter: Filter, team: Team):
- cohort_query = CohortQuery(filter=filter, team=team)
- executor = HogQLCohortQuery(cohort_query=cohort_query).get_query_executor()
+ executor = HogQLCohortQuery(filter=filter, team=team).get_query_executor()
self.hogql_result = executor.execute()
self.clickhouse_query = executor.clickhouse_sql
- super().__init__(filter=filter, team=team)
+
+ def get_query(self) -> tuple[str, dict[str, Any]]:
+ return self.clickhouse_query or "", {}
def convert_property(prop: Property) -> PersonPropertyFilter:
@@ -97,14 +223,14 @@ def convert(prop: PropertyGroup) -> PropertyGroupFilterValue:
class HogQLCohortQuery:
def __init__(
self,
- cohort_query: Optional[CohortQuery] = None,
+ filter: Optional[Filter] = None,
cohort: Optional[Cohort] = None,
team: Optional[Team] = None,
):
if cohort is not None:
self.hogql_context = HogQLContext(team_id=cohort.team.pk, enable_select_queries=True)
self.team = team or cohort.team
- filter = FOSSCohortQuery.unwrap_cohort(
+ unwrapped = unwrap_cohort(
Filter(
data={"properties": cohort.properties},
team=cohort.team,
@@ -114,13 +240,15 @@ class HogQLCohortQuery:
self.team,
cohort,
)
- self.property_groups = filter.property_groups
- elif cohort_query is not None:
- self.hogql_context = HogQLContext(team_id=cohort_query._team_id, enable_select_queries=True)
- self.property_groups = cohort_query._filter.property_groups
- self.team = team or cohort_query._team
+ self.property_groups = unwrapped.property_groups
+ elif filter is not None:
+ if team is None:
+ raise ValueError("HogQLCohortQuery requires a team when constructed from a filter")
+ self.hogql_context = HogQLContext(team_id=team.pk, enable_select_queries=True)
+ self.team = team
+ self.property_groups = unwrap_cohort(filter, team.pk, team).property_groups
else:
- raise
+ raise ValueError("HogQLCohortQuery requires either a cohort or a filter")
def get_query_executor(self) -> HogQLQueryExecutor:
return HogQLQueryExecutor(
@@ -401,25 +529,33 @@ class HogQLCohortQuery:
return query_runner.to_query()
def get_static_cohort_condition(self, prop: Property) -> ast.SelectQuery:
- cohort = Cohort.objects.get(pk=cast(int, prop.value), team__project_id=self.team.project_id)
+ # Convert the cohort id to an int (not the no-op typing.cast) and bind it as a parameter.
+ # prop.value is normally a cohort pk, but an internal cohort property smuggled through the
+ # unvalidated legacy `groups` field could carry an arbitrary string; binding it (rather than
+ # interpolating into parse_select) keeps it out of the query structure.
+ if isinstance(prop.value, list):
+ raise ValueError(f"cohort id must be an integer, got {prop.value}")
+ cohort = Cohort.objects.get(
+ pk=parse_and_validate_positive_integer(prop.value, "cohort id"), team__project_id=self.team.project_id
+ )
return cast(
ast.SelectQuery,
parse_select(
- f"SELECT person_id as id FROM static_cohort_people WHERE cohort_id = {cohort.pk} AND team_id = {self.team.pk}",
+ "SELECT person_id as id FROM static_cohort_people WHERE cohort_id = {cohort_id} AND team_id = {team_id}",
+ {"cohort_id": ast.Constant(value=cohort.pk), "team_id": ast.Constant(value=self.team.pk)},
),
)
def get_dynamic_cohort_condition(self, prop: Property) -> ast.SelectQuery:
- cohort_id = cast(int, prop.value)
-
+ # See get_static_cohort_condition: convert + bind so a non-int value can't alter the query.
+ if isinstance(prop.value, list):
+ raise ValueError(f"cohort id must be an integer, got {prop.value}")
+ cohort_id = parse_and_validate_positive_integer(prop.value, "cohort id")
return cast(
ast.SelectQuery,
parse_select(
- f"""
- SELECT person_id as id FROM cohort_people
- WHERE cohort_id = {cohort_id}
- AND team_id = {self.team.pk}
- """,
+ "SELECT person_id as id FROM cohort_people WHERE cohort_id = {cohort_id} AND team_id = {team_id}",
+ {"cohort_id": ast.Constant(value=cohort_id), "team_id": ast.Constant(value=self.team.pk)},
),
)
@@ -628,11 +764,11 @@ class HogQLRealtimeCohortQuery(HogQLCohortQuery):
def __init__(
self,
- cohort_query: Optional[CohortQuery] = None,
+ filter: Optional[Filter] = None,
cohort: Optional[Cohort] = None,
team: Optional[Team] = None,
):
- super().__init__(cohort_query=cohort_query, cohort=cohort, team=team)
+ super().__init__(filter=filter, cohort=cohort, team=team)
self.cohort = cohort
# Preprocess to merge properties with same key and operator
self.property_groups = self._preprocess_property_groups(self.property_groups) # type: ignore[assignment]
@@ -694,7 +830,7 @@ class HogQLRealtimeCohortQuery(HogQLCohortQuery):
"""
Unwrap PropertyGroups that contain only a single child.
- FOSSCohortQuery.unwrap_cohort creates nested PropertyGroups like:
+ unwrap_cohort creates nested PropertyGroups like:
PropertyGroup(AND) -> PropertyGroup(AND) -> Property
This unwraps them to just: Property
@@ -1035,7 +1171,9 @@ class HogQLRealtimeCohortQuery(HogQLCohortQuery):
Query cohort_membership table for realtime cohort membership.
Filters most recent status='entered' to find current members.
"""
- cohort_id = cast(int, prop.value)
+ if isinstance(prop.value, list):
+ raise ValueError(f"cohort id must be an integer, got {prop.value}")
+ cohort_id = parse_and_validate_positive_integer(prop.value, "cohort id")
return cast(
ast.SelectQuery,
diff --git a/posthog/hogql_queries/test/test_hogql_cohort_query.py b/posthog/hogql_queries/test/test_hogql_cohort_query.py
index 942cb4a81828..85c97b1bbd2f 100644
--- a/posthog/hogql_queries/test/test_hogql_cohort_query.py
+++ b/posthog/hogql_queries/test/test_hogql_cohort_query.py
@@ -8,6 +8,18 @@ from posthog.models import Cohort
class TestHogQLCohortQuery(ClickhouseTestMixin, APIBaseTest):
"""Tests for HogQLCohortQuery, particularly the optimization for multiple person property filters."""
+ def test_dynamic_cohort_id_is_not_injectable(self) -> None:
+ # A static/dynamic-cohort property whose value is an arbitrary string (e.g. smuggled through
+ # the unvalidated legacy `groups` field) must be rejected, not interpolated into the query.
+ for cohort_type in ("dynamic-cohort", "static-cohort"):
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name=f"malicious-{cohort_type}",
+ groups=[{"properties": [{"key": "id", "type": cohort_type, "value": "0 OR 1=1"}]}],
+ )
+ with self.assertRaises(ValueError):
+ HogQLCohortQuery(cohort=cohort).get_query()
+
@patch("posthoganalytics.feature_enabled", return_value=True)
def test_multiple_person_properties_optimization(self, mock_feature_enabled: MagicMock) -> None:
"""
diff --git a/posthog/models/cohort/util.py b/posthog/models/cohort/util.py
index 41e72eb4829c..7ad58adab6bc 100644
--- a/posthog/models/cohort/util.py
+++ b/posthog/models/cohort/util.py
@@ -15,12 +15,13 @@ from dateutil import parser
from pydantic import ValidationError as PydanticValidationError
from rest_framework.exceptions import ValidationError
-from posthog.schema import ProductKey
+from posthog.schema import HogQLQueryModifiers, PersonsOnEventsMode, ProductKey
from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
from posthog.hogql.hogql import HogQLContext
from posthog.hogql.modifiers import create_default_modifiers_for_team
+from posthog.hogql.parser import parse_select
from posthog.hogql.printer import prepare_and_print_ast
from posthog.hogql.resolver_utils import extract_select_queries
@@ -40,7 +41,6 @@ from posthog.models.cohort.calculation_history import CohortCalculationHistory
from posthog.models.cohort.cohort import Cohort, CohortOrEmpty
from posthog.models.cohort.dependencies import get_cohort_dependents
from posthog.models.cohort.sql import (
- CALCULATE_COHORT_PEOPLE_SQL,
GET_COHORT_SIZE_SQL,
GET_COHORTS_BY_PERSON_UUID,
GET_PERSON_ID_BY_PRECALCULATED_COHORT_ID,
@@ -54,7 +54,6 @@ from posthog.models.person.sql import (
PERSON_STATIC_COHORT_TABLE,
)
from posthog.models.property import Property, PropertyGroup
-from posthog.queries.person_distinct_id_query import get_team_distinct_ids_query
from products.actions.backend.models.action import Action
from products.actions.backend.models.util import format_action_filter
@@ -277,7 +276,7 @@ def get_clickhouse_query_stats(tag_matcher: str, cohort_id: int, start_time: dat
return None
-def format_person_query(cohort: Cohort, index: int, hogql_context: HogQLContext) -> tuple[str, dict[str, Any]]:
+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="")
@@ -285,22 +284,9 @@ def format_person_query(cohort: Cohort, index: int, hogql_context: HogQLContext)
# No person can match an empty cohort
return "SELECT generateUUIDv4() as id WHERE 0 = 19", {}
- from posthog.queries.cohort_query import CohortQuery
-
- query_builder = CohortQuery(
- Filter(
- data={"properties": cohort.properties},
- team=cohort.team,
- hogql_context=hogql_context,
- ),
- cohort.team,
- cohort_pk=cohort.pk,
- persons_on_events_mode=cohort.team.person_on_events_mode,
- )
-
- query, params = query_builder.get_query()
-
- return query, params
+ # Compile the cohort criteria via HogQLCohortQuery and embed the result as a person-id subquery.
+ cohort_query, cohort_context = hogql_cohort_subquery_sql(cohort, team=cohort.team)
+ return _prefix_cohort_hogql_params(cohort_query, cohort_context.values, cohort=cohort, index=index)
def _sanitize_query_for_cohort(query_dict: dict) -> dict:
@@ -551,31 +537,77 @@ def is_precalculated_query(cohort: Cohort) -> bool:
return False
-def format_filter_query(
- cohort: Cohort,
- index: int,
- hogql_context: HogQLContext,
- id_column: str = "distinct_id",
- custom_match_field="person_id",
+def _trim_trailing_settings(sql: str) -> str:
+ # ClickHouse rejects a top-level SETTINGS clause when the SELECT is embedded as a subquery, so trim it.
+ 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]]:
- person_query, params = format_cohort_subquery(cohort, index, hogql_context, custom_match_field=custom_match_field)
+ # 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
- person_id_query = CALCULATE_COHORT_PEOPLE_SQL.format(
- query=person_query,
- id_column=id_column,
- GET_TEAM_PERSON_DISTINCT_IDS=get_team_distinct_ids_query(cohort.team_id),
+ 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},
)
- return person_id_query, params
+ sql, context = HogQLQueryExecutor(
+ query_type="CohortFilterDistinctIds",
+ query=query,
+ modifiers=HogQLQueryModifiers(personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED),
+ team=team,
+ limit_context=LimitContext.COHORT_CALCULATION,
+ settings=HogQLGlobalSettings(),
+ ).generate_clickhouse_sql()
+ sql = _trim_trailing_settings(sql)
+ return _prefix_cohort_hogql_params(sql, context.values, cohort=cohort, index=index)
-def format_cohort_subquery(
- cohort: Cohort, index: int, hogql_context: HogQLContext, custom_match_field="person_id"
-) -> tuple[str, dict[str, Any]]:
+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)
+ # The leading `SELECT distinct_id` is load-bearing: breakdown_props rewrites it via string replace.
+ 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, hogql_context)
+ query, params = format_person_query(cohort, index)
person_query = f"{custom_match_field} IN ({query})"
return person_query, params
@@ -700,8 +732,7 @@ def hogql_cohort_subquery_sql(cohort: Cohort, *, team: Team) -> tuple[str, HogQL
sql, hogql_context = HogQLCohortQuery(cohort=cohort, team=team).get_query_executor().generate_clickhouse_sql()
- # Clickhouse rejects a top-level SETTINGS clause when the SELECT is used as a subquery, so we trim it.
- return sql[: sql.rfind("SETTINGS")], hogql_context
+ return _trim_trailing_settings(sql), hogql_context
def _recalculate_cohortpeople_for_team_hogql(
diff --git a/posthog/models/property/util.py b/posthog/models/property/util.py
index 9cd14bf77984..89c6f875ac77 100644
--- a/posthog/models/property/util.py
+++ b/posthog/models/property/util.py
@@ -182,20 +182,14 @@ def parse_prop_clauses(
) # 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,
- cast(HogQLContext, hogql_context),
- custom_match_field=person_id_joined_alias,
- )
+ 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,
- cast(HogQLContext, hogql_context),
- custom_match_field=f"{person_id_joined_alias}",
+ custom_match_field=person_id_joined_alias,
)
params = {**params, **cohort_filter_params}
final.append(f"{property_operator} {person_id_query}")
diff --git a/posthog/queries/breakdown_props.py b/posthog/queries/breakdown_props.py
index cc0a7b68b9e8..05be7e31fabe 100644
--- a/posthog/queries/breakdown_props.py
+++ b/posthog/queries/breakdown_props.py
@@ -360,7 +360,7 @@ def format_breakdown_cohort_join_query(team: Team, filter: Filter, **kwargs) ->
if isinstance(breakdown, list)
else Cohort.objects.filter(team__project_id=team.project_id, pk=breakdown)
)
- cohort_queries, params = _parse_breakdown_cohorts(list(cohorts), filter.hogql_context)
+ cohort_queries, params = _parse_breakdown_cohorts(list(cohorts))
ids = [cohort.pk for cohort in cohorts]
if isinstance(breakdown, list) and "all" in breakdown:
all_query, all_params = _format_all_query(team, filter, entity=entity)
@@ -370,12 +370,12 @@ def format_breakdown_cohort_join_query(team: Team, filter: Filter, **kwargs) ->
return " UNION ALL ".join(cohort_queries), ids, params
-def _parse_breakdown_cohorts(cohorts: list[Cohort], hogql_context: HogQLContext) -> tuple[list[str], dict]:
+def _parse_breakdown_cohorts(cohorts: list[Cohort]) -> tuple[list[str], dict]:
queries = []
params: dict[str, Any] = {}
for idx, cohort in enumerate(cohorts):
- person_id_query, cohort_filter_params = format_filter_query(cohort, idx, hogql_context)
+ person_id_query, cohort_filter_params = format_filter_query(cohort, idx)
params = {**params, **cohort_filter_params}
cohort_query = person_id_query.replace(
"SELECT distinct_id", f"SELECT distinct_id, {cohort.pk} as value", 1
diff --git a/posthog/queries/cohort_query.py b/posthog/queries/cohort_query.py
deleted file mode 100644
index d839f89622cb..000000000000
--- a/posthog/queries/cohort_query.py
+++ /dev/null
@@ -1,6 +0,0 @@
-from posthog.settings import EE_AVAILABLE
-
-if EE_AVAILABLE:
- from ee.clickhouse.queries.enterprise_cohort_query import EnterpriseCohortQuery as CohortQuery
-else:
- from posthog.queries.foss_cohort_query import FOSSCohortQuery as CohortQuery # type: ignore # noqa: F401
diff --git a/posthog/queries/foss_cohort_query.py b/posthog/queries/foss_cohort_query.py
deleted file mode 100644
index c6c812b6035e..000000000000
--- a/posthog/queries/foss_cohort_query.py
+++ /dev/null
@@ -1,692 +0,0 @@
-from datetime import datetime
-from typing import Any, Optional, Union, cast
-from zoneinfo import ZoneInfo
-
-from posthog.schema import PersonsOnEventsMode
-
-from posthog.clickhouse.materialized_columns import ColumnName
-from posthog.constants import PropertyOperatorType
-from posthog.models import Filter, Team
-from posthog.models.cohort import Cohort
-from posthog.models.cohort.util import format_static_cohort_query, get_count_operator, get_entity_query
-from posthog.models.filters.mixins.utils import cached_property
-from posthog.models.property import BehavioralPropertyType, OperatorInterval, Property, PropertyGroup, PropertyName
-from posthog.models.property.util import parse_prop_grouped_clauses, prop_filter_json_extract
-from posthog.queries.event_query import EventQuery
-from posthog.queries.util import PersonPropertiesMode
-from posthog.utils import relative_date_parse
-
-from products.actions.backend.models.action import Action
-
-Relative_Date = tuple[int, OperatorInterval]
-Event = tuple[str, Union[str, int]]
-
-
-INTERVAL_TO_SECONDS = {
- "minute": 60,
- "hour": 3600,
- "day": 86400,
- "week": 604800,
- "month": 2592000,
- "year": 31536000,
-}
-
-
-def relative_date_to_seconds(date: tuple[Optional[int], Union[OperatorInterval, None]]):
- if date[0] is None or date[1] is None:
- raise ValueError("Time value and time interval must be specified")
-
- return date[0] * INTERVAL_TO_SECONDS[date[1]]
-
-
-def validate_interval(interval: Optional[OperatorInterval]) -> OperatorInterval:
- if interval is None or interval not in INTERVAL_TO_SECONDS.keys():
- raise ValueError(f"Invalid interval: {interval}")
- else:
- return interval
-
-
-def parse_and_validate_positive_integer(value: Optional[int], value_name: str) -> int:
- if value is None:
- raise ValueError(f"{value_name} cannot be None")
- try:
- parsed_value = int(value)
- except ValueError:
- raise ValueError(f"{value_name} must be an integer, got {value}")
- if parsed_value <= 0:
- raise ValueError(f"{value_name} must be greater than 0, got {value}")
- return parsed_value
-
-
-def validate_entity(possible_event: tuple[Optional[str], Optional[Union[int, str]]]) -> Event:
- event_type = possible_event[0]
- event_val = possible_event[1]
- if event_type is None or event_val is None:
- raise ValueError("Entity name and entity id must be specified")
- return (event_type, event_val)
-
-
-def validate_seq_date_more_recent_than_date(seq_date: Relative_Date, date: Relative_Date):
- if relative_date_is_greater(seq_date, date):
- raise ValueError("seq_date must be more recent than date")
-
-
-def relative_date_is_greater(date_1: Relative_Date, date_2: Relative_Date) -> bool:
- return relative_date_to_seconds(date_1) > relative_date_to_seconds(date_2)
-
-
-def convert_to_entity_params(events: list[Event], team_id: int) -> tuple[list, list]:
- res_events = []
- res_actions = []
-
- for idx, event in enumerate(events):
- event_type = event[0]
- event_val = event[1]
-
- if event_type == "events":
- res_events.append({"id": event_val, "name": event_val, "order": idx, "type": event_type})
- elif event_type == "actions":
- action = Action.objects.get(id=event_val, team_id=team_id)
- res_actions.append({"id": event_val, "name": action.name, "order": idx, "type": event_type})
-
- return res_events, res_actions
-
-
-def get_relative_date_arg(relative_date: Relative_Date) -> str:
- return f"-{relative_date[0]}{relative_date[1][0].lower()}"
-
-
-def full_outer_join_query(q: str, alias: str, left_operand: str, right_operand: str) -> str:
- return join_query(q, "FULL OUTER JOIN", alias, left_operand, right_operand)
-
-
-def inner_join_query(q: str, alias: str, left_operand: str, right_operand: str) -> str:
- return join_query(q, "INNER JOIN", alias, left_operand, right_operand)
-
-
-def join_query(q: str, join: str, alias: str, left_operand: str, right_operand: str) -> str:
- return f"{join} ({q}) {alias} ON {left_operand} = {right_operand}"
-
-
-def if_condition(condition: str, true_res: str, false_res: str) -> str:
- return f"if({condition}, {true_res}, {false_res})"
-
-
-class FOSSCohortQuery(EventQuery):
- BEHAVIOR_QUERY_ALIAS = "behavior_query"
- FUNNEL_QUERY_ALIAS = "funnel_query"
- SEQUENCE_FIELD_ALIAS = "steps"
- _fields: list[str]
- _events: list[str]
- _earliest_time_for_event_query: Optional[Relative_Date]
- _restrict_event_query_by_time: bool
-
- def __init__(
- self,
- filter: Filter,
- team: Team,
- *,
- cohort_pk: Optional[int] = None,
- round_interval=False,
- should_join_distinct_ids=False,
- should_join_persons=False,
- # Extra events/person table columns to fetch since parent query needs them
- extra_fields: Optional[list[ColumnName]] = None,
- extra_event_properties: Optional[list[PropertyName]] = None,
- extra_person_fields: Optional[list[ColumnName]] = None,
- override_aggregate_users_by_distinct_id: Optional[bool] = None,
- **kwargs,
- ) -> None:
- if extra_person_fields is None:
- extra_person_fields = []
- if extra_event_properties is None:
- extra_event_properties = []
- if extra_fields is None:
- extra_fields = []
- self._fields = []
- self._events = []
- self._earliest_time_for_event_query = None
- self._restrict_event_query_by_time = True
- self._cohort_pk = cohort_pk
-
- super().__init__(
- filter=FOSSCohortQuery.unwrap_cohort(filter, team.pk, team),
- team=team,
- round_interval=round_interval,
- should_join_distinct_ids=should_join_distinct_ids,
- should_join_persons=should_join_persons,
- extra_fields=extra_fields,
- extra_event_properties=extra_event_properties,
- extra_person_fields=extra_person_fields,
- override_aggregate_users_by_distinct_id=override_aggregate_users_by_distinct_id,
- person_on_events_mode=team.person_on_events_mode,
- **kwargs,
- )
-
- self._validate_negations()
-
- property_groups = self._column_optimizer.property_optimizer.parse_property_groups(self._filter.property_groups)
- self._inner_property_groups = property_groups.inner
- self._outer_property_groups = property_groups.outer
-
- @staticmethod
- def unwrap_cohort(
- filter: Filter, team_id: int, team: Optional[Team] = None, cohort: Optional[Cohort] = None
- ) -> Filter:
- def _unwrap(property_group: PropertyGroup, negate_group: bool = False) -> PropertyGroup:
- nonlocal team
- if len(property_group.values):
- if isinstance(property_group.values[0], PropertyGroup):
- # dealing with a list of property groups, so unwrap each one
- # Propogate the negation to the children and handle as necessary with respect to deMorgan's law
- if not negate_group:
- return PropertyGroup(
- type=property_group.type,
- values=[_unwrap(v) for v in cast(list[PropertyGroup], property_group.values)],
- )
- else:
- return PropertyGroup(
- type=(
- PropertyOperatorType.AND
- if property_group.type == PropertyOperatorType.OR
- else PropertyOperatorType.OR
- ),
- values=[_unwrap(v, True) for v in cast(list[PropertyGroup], property_group.values)],
- )
-
- elif isinstance(property_group.values[0], Property):
- # dealing with a list of properties
- # if any single one is a cohort property, unwrap it into a property group
- # which implies converting everything else in the list into a property group too
-
- new_property_group_list: list[PropertyGroup] = []
- for prop in property_group.values:
- prop = cast(Property, prop)
- current_negation = prop.negation or False
- negation_value = not current_negation if negate_group else current_negation
- if prop.type in ["cohort", "precalculated-cohort"]:
- try:
- # Use passed cohort object if it matches the requested cohort ID
- if cohort is not None and str(cohort.pk) == str(prop.value):
- prop_cohort = cohort
- else:
- # Use passed team object if available, otherwise fetch from database
- if team is None:
- team = Team.objects.get(pk=team_id)
- prop_cohort = Cohort.objects.get(
- pk=cast(str | int, prop.value), team__project_id=team.project_id
- )
- new_property_group_list.append(
- PropertyGroup(
- type=PropertyOperatorType.AND,
- values=[
- Property(
- type="static-cohort" if prop_cohort.is_static else "dynamic-cohort",
- key="id",
- value=prop_cohort.pk,
- negation=negation_value,
- )
- ],
- )
- )
- except Cohort.DoesNotExist:
- new_property_group_list.append(
- PropertyGroup(
- type=PropertyOperatorType.AND,
- values=[
- Property(
- key="fake_key_01r2ho",
- value="0",
- type="person",
- )
- ],
- )
- )
- else:
- prop.negation = negation_value
- new_property_group_list.append(PropertyGroup(type=PropertyOperatorType.AND, values=[prop]))
- if not negate_group:
- return PropertyGroup(type=property_group.type, values=new_property_group_list)
- else:
- return PropertyGroup(
- type=(
- PropertyOperatorType.AND
- if property_group.type == PropertyOperatorType.OR
- else PropertyOperatorType.OR
- ),
- values=new_property_group_list,
- )
-
- return property_group
-
- new_props = _unwrap(filter.property_groups)
- return filter.shallow_clone({"properties": new_props.to_dict()})
-
- # Implemented in /ee
- def get_query(self) -> tuple[str, dict[str, Any]]:
- if not self._outer_property_groups:
- # everything is pushed down, no behavioral stuff to do
- # thus, use personQuery directly
- return self._person_query.get_query(prepend=self._cohort_pk)
-
- # TODO: clean up this kludge. Right now, get_conditions has to run first so that _fields is populated for _get_behavioral_subquery()
- conditions, condition_params = self._get_conditions()
- self.params.update(condition_params)
-
- subq = []
-
- (
- behavior_subquery,
- behavior_subquery_params,
- behavior_query_alias,
- ) = self._get_behavior_subquery()
- subq.append((behavior_subquery, behavior_query_alias))
- self.params.update(behavior_subquery_params)
-
- person_query, person_params, person_query_alias = self._get_persons_query(prepend=str(self._cohort_pk))
- subq.append((person_query, person_query_alias))
- self.params.update(person_params)
-
- # Since we can FULL OUTER JOIN, we may end up with pairs of uuids where one side is blank. Always try to choose the non blank ID
- q, fields = self._build_sources(subq)
-
- final_query = f"""
- SELECT {fields} AS id FROM
- {q}
- WHERE 1 = 1
- {conditions}
- """
-
- return final_query, self.params
-
- def _build_sources(self, subq: list[tuple[str, str]]) -> tuple[str, str]:
- q = ""
- filtered_queries = [(q, alias) for (q, alias) in subq if q and len(q)]
-
- prev_alias: Optional[str] = None
- fields = ""
- for idx, (subq_query, subq_alias) in enumerate(filtered_queries):
- if idx == 0:
- q += f"({subq_query}) {subq_alias}"
- fields = f"{subq_alias}.person_id"
- elif prev_alias: # can't join without a previous alias
- if subq_alias == self.PERSON_TABLE_ALIAS and self.should_pushdown_persons:
- if self._person_on_events_mode == PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS:
- # when using person-on-events, instead of inner join, we filter inside
- # the event query itself
- continue
-
- q = f"{q} {inner_join_query(subq_query, subq_alias, f'{subq_alias}.person_id', f'{prev_alias}.person_id')}"
- fields = f"{subq_alias}.person_id"
- else:
- q = f"{q} {full_outer_join_query(subq_query, subq_alias, f'{subq_alias}.person_id', f'{prev_alias}.person_id')}"
- fields = if_condition(
- f"{prev_alias}.person_id = '00000000-0000-0000-0000-000000000000'",
- f"{subq_alias}.person_id",
- f"{fields}",
- )
-
- prev_alias = subq_alias
-
- return q, fields
-
- def _get_behavior_subquery(self) -> tuple[str, dict[str, Any], str]:
- #
- # Get the subquery for the cohort query.
- #
- event_param_name = f"{self._cohort_pk}_event_ids"
-
- person_prop_query = ""
- person_prop_params: dict = {}
-
- query, params = "", {}
- if self._should_join_behavioral_query:
- _fields = []
- if not self._should_join_distinct_ids:
- _fields.append(f"{self.EVENT_TABLE_ALIAS}.person_id AS person_id")
- elif self._person_on_events_mode == PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS:
- _fields.append(
- f"if(not(empty({self.PERSON_ID_OVERRIDES_TABLE_ALIAS}.distinct_id)), {self.PERSON_ID_OVERRIDES_TABLE_ALIAS}.person_id, {self.EVENT_TABLE_ALIAS}.person_id) AS person_id"
- )
- else:
- _fields.append(
- f"if(not(empty({self.DISTINCT_ID_TABLE_ALIAS}.distinct_id)), {self.DISTINCT_ID_TABLE_ALIAS}.person_id, {self.EVENT_TABLE_ALIAS}.person_id) AS person_id"
- )
- _fields.extend(self._fields)
-
- if self.should_pushdown_persons and self._person_on_events_mode != PersonsOnEventsMode.DISABLED:
- person_prop_query, person_prop_params = self._get_prop_groups(
- self._inner_property_groups,
- person_properties_mode=PersonPropertiesMode.DIRECT_ON_EVENTS,
- person_id_joined_alias=self._person_id_alias,
- )
-
- date_condition, date_params = self._get_date_condition()
- if len(self._events) > 0:
- event_condition = f"AND event IN %({event_param_name})s"
- else:
- event_condition = ""
-
- query = f"""
- SELECT {", ".join(_fields)} FROM events {self.EVENT_TABLE_ALIAS}
- {self._get_person_ids_query()}
- WHERE team_id = %(team_id)s
- {event_condition}
- {date_condition}
- {person_prop_query}
- GROUP BY person_id
- """
-
- query, params = (
- query,
- {
- "team_id": self._team_id,
- event_param_name: self._events,
- **date_params,
- **person_prop_params,
- },
- )
-
- return query, params, self.BEHAVIOR_QUERY_ALIAS
-
- def _get_persons_query(self, prepend: str = "") -> tuple[str, dict[str, Any], str]:
- query, params = "", {}
- if self._should_join_persons:
- person_query, person_params = self._person_query.get_query(prepend=prepend)
- person_query = f"SELECT *, id AS person_id FROM ({person_query})"
-
- query, params = person_query, person_params
-
- return query, params, self.PERSON_TABLE_ALIAS
-
- @cached_property
- def should_pushdown_persons(self) -> bool:
- return (
- "person" not in [prop.type for prop in getattr(self._outer_property_groups, "flat", [])]
- and "static-cohort" not in [prop.type for prop in getattr(self._outer_property_groups, "flat", [])]
- and "dynamic-cohort" not in [prop.type for prop in getattr(self._outer_property_groups, "flat", [])]
- )
-
- def _get_date_condition(self) -> tuple[str, dict[str, Any]]:
- date_query = ""
- date_params: dict[str, Any] = {}
- earliest_time_param = f"earliest_time_{self._cohort_pk}"
-
- if self._earliest_time_for_event_query and self._restrict_event_query_by_time:
- date_params = {earliest_time_param: self._earliest_time_for_event_query[0]}
- date_query = f"AND timestamp <= now() AND timestamp >= now() - INTERVAL %({earliest_time_param})s {self._earliest_time_for_event_query[1]}"
-
- return date_query, date_params
-
- def _check_earliest_date(self, relative_date: Relative_Date) -> None:
- if self._earliest_time_for_event_query is None:
- self._earliest_time_for_event_query = relative_date
- elif relative_date_is_greater(relative_date, self._earliest_time_for_event_query):
- self._earliest_time_for_event_query = relative_date
-
- def _get_conditions(self) -> tuple[str, dict[str, Any]]:
- def build_conditions(prop: Optional[Union[PropertyGroup, Property]], prepend="level", num=0):
- if not prop:
- return "", {}
-
- if isinstance(prop, PropertyGroup):
- params = {}
- conditions = []
- for idx, p in enumerate(prop.values):
- q, q_params = build_conditions(p, f"{prepend}_level_{num}", idx) # type: ignore
- if q != "":
- conditions.append(q)
- params.update(q_params)
-
- return f"({f' {prop.type} '.join(conditions)})", params
- else:
- return self._get_condition_for_property(prop, prepend, num)
-
- conditions, params = build_conditions(self._outer_property_groups, prepend=f"{self._cohort_pk}_level", num=0)
- return f"AND ({conditions})" if conditions else "", params
-
- # Implemented in /ee
- def _get_condition_for_property(self, prop: Property, prepend: str, idx: int) -> tuple[str, dict[str, Any]]:
- res: str = ""
- params: dict[str, Any] = {}
-
- if prop.type == "behavioral":
- if prop.value == "performed_event":
- res, params = self.get_performed_event_condition(prop, prepend, idx)
- elif prop.value == "performed_event_multiple":
- res, params = self.get_performed_event_multiple(prop, prepend, idx)
- elif prop.type == "person":
- res, params = self.get_person_condition(prop, prepend, idx)
- elif prop.type == "static-cohort": # static cohorts are handled by flattening during initialization
- res, params = self.get_static_cohort_condition(prop, prepend, idx)
- elif prop.type == "dynamic-cohort":
- res, params = self.get_dynamic_cohort_condition(prop, prepend, idx)
- else:
- raise ValueError(f"Invalid property type for Cohort queries: {prop.type}")
-
- return res, params
-
- def get_person_condition(self, prop: Property, prepend: str, idx: int) -> tuple[str, dict[str, Any]]:
- if self._outer_property_groups and len(self._outer_property_groups.flat):
- return prop_filter_json_extract(
- prop,
- idx,
- prepend,
- prop_var="person_props",
- allow_denormalized_props=True,
- property_operator="",
- )
- else:
- return "", {}
-
- def get_static_cohort_condition(self, prop: Property, prepend: str, idx: int) -> tuple[str, dict[str, Any]]:
- # If we reach this stage, it means there are no cyclic dependencies
- # They should've been caught by API update validation
- # and if not there, `simplifyFilter` would've failed
- cohort = Cohort.objects.get(pk=cast(int, prop.value), team_id=self._team_id)
- query, params = format_static_cohort_query(cohort, idx, prepend)
- return f"id {'NOT' if prop.negation else ''} IN ({query})", params
-
- def get_dynamic_cohort_condition(self, prop: Property, prepend: str, idx: int) -> tuple[str, dict[str, Any]]:
- cohort_id = cast(int, prop.value)
-
- param_key_cohort = f"{prepend}_dynamic_cohort_{idx}"
- param_key_team = f"{prepend}_dynamic_cohort_team_{idx}"
-
- query = f"""
- SELECT person_id FROM cohortpeople
- WHERE cohort_id = %({param_key_cohort})s
- AND team_id = %({param_key_team})s
- """
-
- return f"id {'NOT' if prop.negation else ''} IN ({query})", {
- param_key_cohort: cohort_id,
- param_key_team: self._team_id,
- }
-
- def _get_entity_event_filters(self, prop: Property, prepend: str, idx: int) -> tuple[str, dict[str, Any]]:
- params: dict[str, Any] = {}
-
- if prop.event_filters:
- prop_query, prop_params = parse_prop_grouped_clauses(
- team_id=self._team_id,
- property_group=Filter(data={"properties": prop.event_filters}).property_groups,
- prepend=f"{prepend}_{idx}_event_filters",
- # should be no person properties in these filters, but if there are, use
- # the inefficient person subquery default mode
- person_properties_mode=PersonPropertiesMode.USING_SUBQUERY,
- hogql_context=self._filter.hogql_context,
- )
- params.update(prop_params)
- return prop_query, params
- else:
- return "AND 1=1", {}
-
- def _get_relative_interval_from_explicit_date(self, datetime: datetime, timezone: ZoneInfo) -> Relative_Date:
- # get days difference between now and given datetime for global datetime filters
- delta = datetime.now().astimezone(timezone) - datetime
- # one extra day for any partial days
- return (delta.days + 1, "day")
-
- def _get_entity_datetime_filters(self, prop: Property, prepend: str, idx: int) -> tuple[str, dict[str, Any]]:
- if prop.explicit_datetime:
- # Explicit datetime filter, can be a relative or absolute date, follows same convention
- # as all analytics datetime filters
- date_param = f"{prepend}_explicit_date_{idx}"
- target_datetime = relative_date_parse(prop.explicit_datetime, self._team.timezone_info)
-
- # Do this to create global filters for the entire query
- relative_date = self._get_relative_interval_from_explicit_date(target_datetime, self._team.timezone_info)
- self._check_earliest_date(relative_date)
-
- params: dict[str, Any] = {date_param: target_datetime}
- clause = f"timestamp > %({date_param})s"
-
- if prop.explicit_datetime_to:
- date_to_param = f"{prepend}_explicit_date_to_{idx}"
- target_datetime_to = relative_date_parse(prop.explicit_datetime_to, self._team.timezone_info)
- # Upper bound is inclusive of the full to-date, matching the HogQL engine which
- # compares a day-precision `date` column with `<= toDate(...)`. Normalising to
- # end-of-day here keeps both engines producing identical cohort membership.
- target_datetime_to = target_datetime_to.replace(hour=23, minute=59, second=59, microsecond=999999)
- params[date_to_param] = target_datetime_to
- clause = f"{clause} AND timestamp <= %({date_to_param})s"
-
- return clause, params
- else:
- date_value = parse_and_validate_positive_integer(prop.time_value, "time_value")
- date_interval = validate_interval(prop.time_interval)
- date_param = f"{prepend}_date_{idx}"
-
- self._check_earliest_date((date_value, date_interval))
-
- return f"timestamp > now() - INTERVAL %({date_param})s {date_interval}", {f"{date_param}": date_value}
-
- def get_performed_event_condition(self, prop: Property, prepend: str, idx: int) -> tuple[str, dict[str, Any]]:
- event = (prop.event_type, prop.key)
- column_name = f"performed_event_condition_{prepend}_{idx}"
-
- entity_query, entity_params = self._get_entity(event, prepend, idx)
- entity_filters, entity_filters_params = self._get_entity_event_filters(prop, prepend, idx)
- date_filter, date_params = self._get_entity_datetime_filters(prop, prepend, idx)
-
- field = f"countIf({date_filter} AND timestamp < now() AND {entity_query} {entity_filters}) > 0 AS {column_name}"
- self._fields.append(field)
-
- # Negation is handled in the where clause to ensure the right result if a full join occurs where the joined person did not perform the event
- # For OR conditions, we need to handle NULL values that occur when a person doesn't appear in the behavioral subquery
- # NULL should be treated as false for behavioral conditions
- return f"{'NOT' if prop.negation else ''} coalesce({column_name}, false)", {
- **date_params,
- **entity_params,
- **entity_filters_params,
- }
-
- def get_performed_event_multiple(self, prop: Property, prepend: str, idx: int) -> tuple[str, dict[str, Any]]:
- event = (prop.event_type, prop.key)
- column_name = f"performed_event_multiple_condition_{prepend}_{idx}"
-
- entity_query, entity_params = self._get_entity(event, prepend, idx)
- entity_filters, entity_filters_params = self._get_entity_event_filters(prop, prepend, idx)
- date_filter, date_params = self._get_entity_datetime_filters(prop, prepend, idx)
-
- count = parse_and_validate_positive_integer(prop.operator_value, "operator_value")
- operator_value_param = f"{prepend}_operator_value_{idx}"
-
- field = f"countIf({date_filter} AND timestamp < now() AND {entity_query} {entity_filters}) {get_count_operator(prop.operator)} %({operator_value_param})s AS {column_name}"
- self._fields.append(field)
-
- # Negation is handled in the where clause to ensure the right result if a full join occurs where the joined person did not perform the event
- # For OR conditions, we need to handle NULL values that occur when a person doesn't appear in the behavioral subquery
- # NULL should be treated as false for behavioral conditions
- return (
- f"{'NOT' if prop.negation else ''} coalesce({column_name}, false)",
- {
- f"{operator_value_param}": count,
- **date_params,
- **entity_params,
- **entity_filters_params,
- },
- )
-
- def _determine_should_join_distinct_ids(self) -> None:
- self._should_join_distinct_ids = (
- self._person_on_events_mode != PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS
- )
-
- def _determine_should_join_persons(self) -> None:
- # :TRICKY: This doesn't apply to joining inside events query, but to the
- # overall query, while `should_join_distinct_ids` applies only to
- # event subqueries
- self._should_join_persons = (
- self._column_optimizer.is_using_person_properties
- or len(self._column_optimizer.used_properties_with_type("static-cohort")) > 0
- or len(self._column_optimizer.used_properties_with_type("dynamic-cohort")) > 0
- )
-
- @cached_property
- def _should_join_behavioral_query(self) -> bool:
- for prop in self._filter.property_groups.flat:
- if prop.value in [
- BehavioralPropertyType.PERFORMED_EVENT,
- BehavioralPropertyType.PERFORMED_EVENT_FIRST_TIME,
- BehavioralPropertyType.PERFORMED_EVENT_MULTIPLE,
- BehavioralPropertyType.PERFORMED_EVENT_REGULARLY,
- BehavioralPropertyType.RESTARTED_PERFORMING_EVENT,
- BehavioralPropertyType.STOPPED_PERFORMING_EVENT,
- ]:
- return True
- return False
-
- # Check if negations are always paired with a positive filter
- # raise a value error warning that this is an invalid cohort
- # implemented in /ee
- def _validate_negations(self) -> None:
- pass
-
- def _get_entity(
- self,
- event: tuple[Optional[str], Optional[Union[int, str]]],
- prepend: str,
- idx: int,
- ) -> tuple[str, dict[str, Any]]:
- res: str = ""
- params: dict[str, Any] = {}
-
- if event[0] is None or event[1] is None:
- raise ValueError("Event type and key must be specified")
-
- if event[0] == "actions":
- self._add_action(int(event[1]))
- res, params = get_entity_query(
- None,
- int(event[1]),
- self._team_id,
- f"{prepend}_entity_{idx}",
- self._filter.hogql_context,
- person_properties_mode=PersonPropertiesMode.DIRECT_ON_EVENTS
- if self._person_on_events_mode != PersonsOnEventsMode.DISABLED
- else None,
- )
- elif event[0] == "events":
- self._add_event(str(event[1]))
- res, params = get_entity_query(
- str(event[1]),
- None,
- self._team_id,
- f"{prepend}_entity_{idx}",
- self._filter.hogql_context,
- )
- else:
- raise ValueError(f"Event type must be 'events' or 'actions'")
-
- return res, params
-
- def _add_action(self, action_id: int) -> None:
- action = Action.objects.get(id=action_id, team_id=self._team_id)
- for step in action.steps:
- if step.event:
- self._events.append(step.event)
-
- def _add_event(self, event_id: str) -> None:
- self._events.append(event_id)
diff --git a/posthog/queries/funnels/test/__snapshots__/test_funnel.ambr b/posthog/queries/funnels/test/__snapshots__/test_funnel.ambr
index 01fbc42d5187..e8d4c607ee3d 100644
--- a/posthog/queries/funnels/test/__snapshots__/test_funnel.ambr
+++ b/posthog/queries/funnels/test/__snapshots__/test_funnel.ambr
@@ -327,18 +327,20 @@
if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
if(event = 'user signed up'
- AND (person_id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%.com%')))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%.com%')) SETTINGS optimize_aggregation_in_order = 1)), 1, 0) as step_0,
+ AND (person_id IN (
+ (SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email, 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(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', '')), '%.com%'), 0)))))
+ GROUP BY person.id
+ HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
+ WHERE ifNull(ilike(toString(persons.properties___email), '%.com%'), 0)
+ ORDER BY persons.id ASC
+ LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1, join_algorithm='auto'))), 1, 0) as step_0,
if(step_0 = 1, timestamp, null) as latest_0,
if(event = 'paid', 1, 0) as step_1,
if(step_1 = 1, timestamp, null) as latest_1
diff --git a/posthog/queries/test/__snapshots__/test_trends.ambr b/posthog/queries/test/__snapshots__/test_trends.ambr
index c5f475701a39..71809e24bd0e 100644
--- a/posthog/queries/test/__snapshots__/test_trends.ambr
+++ b/posthog/queries/test/__snapshots__/test_trends.ambr
@@ -635,18 +635,23 @@
WHERE team_id = 99999
AND ((event = '$pageview'
AND (has(['p1', 'p2', 'p3'], replaceRegexpAll(JSONExtractRaw(person_props, 'name'), '^"|"$', ''))
- AND pdi.person_id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((has(['p1', 'p2'], replaceRegexpAll(JSONExtractRaw(properties, 'name'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((has(['p1', 'p2'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'name'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1))))
+ AND pdi.person_id IN (
+ (SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
+ 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), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'name'), ''), 'null'), '^"|"$', ''), tuple('p1', 'p2'))))))
+ GROUP BY person.id
+ HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
+ WHERE in(persons.properties___name,
+ tuple('p1', 'p2'))
+ ORDER BY persons.id ASC
+ LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto')))))
AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
GROUP BY value
@@ -720,18 +725,23 @@
AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
AND ((event = '$pageview'
AND (has(['p1', 'p2', 'p3'], replaceRegexpAll(JSONExtractRaw(person_props, 'name'), '^"|"$', ''))
- AND pdi.person_id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((has(['p1', 'p2'], replaceRegexpAll(JSONExtractRaw(properties, 'name'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((has(['p1', 'p2'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'name'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1))))
+ AND pdi.person_id IN (
+ (SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
+ 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), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'name'), ''), 'null'), '^"|"$', ''), tuple('p1', 'p2'))))))
+ GROUP BY person.id
+ HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
+ WHERE in(persons.properties___name,
+ tuple('p1', 'p2'))
+ ORDER BY persons.id ASC
+ LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto')))))
GROUP BY timestamp, person_id,
breakdown_value) e
WHERE e.timestamp <= d.timestamp
@@ -1676,18 +1686,22 @@
HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
WHERE team_id = 99999
AND ((event = 'sign up'
- AND (pdi.person_id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((has(['some_val'], replaceRegexpAll(JSONExtractRaw(properties, '$some_prop'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((has(['some_val'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$some_prop'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1))))
+ AND (pdi.person_id IN (
+ (SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, '$some_prop'), ''), 'null'), '^"|"$', '')), person.version), 1) AS `properties___$some_prop`,
+ 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, '$some_prop'), ''), 'null'), '^"|"$', ''), 'some_val'), 0)))))
+ GROUP BY person.id
+ HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
+ WHERE ifNull(equals(persons.`properties___$some_prop`, 'some_val'), 0)
+ ORDER BY persons.id ASC
+ LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto')))))
AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC')
AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
GROUP BY value
@@ -1738,18 +1752,22 @@
AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
AND ((event = 'sign up'
- AND (pdi.person_id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((has(['some_val'], replaceRegexpAll(JSONExtractRaw(properties, '$some_prop'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((has(['some_val'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$some_prop'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1))))
+ AND (pdi.person_id IN (
+ (SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, '$some_prop'), ''), 'null'), '^"|"$', '')), person.version), 1) AS `properties___$some_prop`,
+ 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, '$some_prop'), ''), 'null'), '^"|"$', ''), 'some_val'), 0)))))
+ GROUP BY person.id
+ HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons
+ WHERE ifNull(equals(persons.`properties___$some_prop`, 'some_val'), 0)
+ ORDER BY persons.id ASC
+ LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto')))))
GROUP BY day_start,
breakdown_value))
GROUP BY day_start,
diff --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.ambr
index 078cfca837b0..2d3f6395f2e0 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
@@ -6351,24 +6351,30 @@
AND (pdi.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 person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((has(['yes'], replaceRegexpAll(JSONExtractRaw(properties, '$is_internal'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((has(['yes'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$is_internal'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1)))
+ (SELECT person_distinct_ids.distinct_id AS distinct_id
+ FROM
+ (SELECT tupleElement(argMax(tuple(person_distinct_id2.person_id), person_distinct_id2.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id2.is_deleted), person_distinct_id2.version), 1), 0), 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(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) 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)))
'''
# ---
# name: TestSessionRecordingsListFromQuery_0.test_filter_users_from_excluded_cohort.2
@@ -6655,24 +6661,30 @@
AND (pdi.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 person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((has(['yes'], replaceRegexpAll(JSONExtractRaw(properties, '$is_internal'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((has(['yes'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$is_internal'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1)))
+ (SELECT person_distinct_ids.distinct_id AS distinct_id
+ FROM
+ (SELECT tupleElement(argMax(tuple(person_distinct_id2.person_id), person_distinct_id2.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id2.is_deleted), person_distinct_id2.version), 1), 0), 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(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) 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)))
'''
# ---
# name: TestSessionRecordingsListFromQuery_0.test_filter_users_from_excluded_cohort_no_events.2
@@ -14053,24 +14065,30 @@
AND (pdi.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 person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((has(['yes'], replaceRegexpAll(JSONExtractRaw(properties, '$is_internal'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((has(['yes'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$is_internal'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1)))
+ (SELECT person_distinct_ids.distinct_id AS distinct_id
+ FROM
+ (SELECT tupleElement(argMax(tuple(person_distinct_id2.person_id), person_distinct_id2.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id2.is_deleted), person_distinct_id2.version), 1), 0), 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(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) 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)))
'''
# ---
# name: TestSessionRecordingsListFromQuery_1.test_filter_users_from_excluded_cohort.2
@@ -14357,24 +14375,30 @@
AND (pdi.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 person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((has(['yes'], replaceRegexpAll(JSONExtractRaw(properties, '$is_internal'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((has(['yes'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$is_internal'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1)))
+ (SELECT person_distinct_ids.distinct_id AS distinct_id
+ FROM
+ (SELECT tupleElement(argMax(tuple(person_distinct_id2.person_id), person_distinct_id2.version), 1) 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id2.is_deleted), person_distinct_id2.version), 1), 0), 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(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) 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)))
'''
# ---
# name: TestSessionRecordingsListFromQuery_1.test_filter_users_from_excluded_cohort_no_events.2