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.

fix(sessions): serve session property values via HogQL, not raw SQL (#91455)

Sandy Spicer5a1e8f415741
diff --git a/posthog/api/event.py b/posthog/api/event.py
index 5657fcaf2997..bc5ade188f66 100644
--- a/posthog/api/event.py
+++ b/posthog/api/event.py
@@ -35,6 +35,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.auth import PersonalAPIKeyAuthentication
from posthog.clickhouse.query_tagging import Feature, tag_queries
+from posthog.errors import ExposedCHQueryError
from posthog.event_usage import get_request_analytics_properties
from posthog.exceptions_capture import capture_exception
from posthog.models import Element, Person, PropertyDefinition, User
@@ -476,7 +477,12 @@ class EventViewSet(
execution_mode = execution_mode_from_refresh(refresh)
if execution_mode == ExecutionMode.CACHE_ONLY_NEVER_CALCULATE and not refresh:
execution_mode = ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS
- result = runner.run(execution_mode, analytics_props=get_request_analytics_properties(self.request))
+ # Convert here rather than in the runner, so QueryRunner.run() sees the original
+ # ClickHouse error and can classify it and record it in the failure cache. Matches persons/values.
+ try:
+ result = runner.run(execution_mode, analytics_props=get_request_analytics_properties(self.request))
+ except ExposedCHQueryError as e:
+ raise serializers.ValidationError(str(e), e.code_name)
assert isinstance(result, (PropertyValuesQueryResponse, CachedPropertyValuesQueryResponse))
is_refreshing = (
isinstance(result, CachedPropertyValuesQueryResponse)
diff --git a/posthog/api/session.py b/posthog/api/session.py
index 15fa42eb5326..ac8236552541 100644
--- a/posthog/api/session.py
+++ b/posthog/api/session.py
@@ -23,6 +23,7 @@ from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.api.property_value_metrics import PROPERTY_VALUES_DURATION
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
+from posthog.errors import ExposedCHQueryError
from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle
from posthog.utils import convert_property_value, flatten
@@ -58,15 +59,19 @@ class SessionViewSet(
modifiers = create_default_modifiers_for_team(team)
version = modifiers.sessionTableVersion
- if version == SessionTableVersion.V3:
- span.set_attribute("session_table_version", "v3")
- result = get_lazy_session_table_values_v3(key, search_term=search_term, team=team)
- elif version == SessionTableVersion.V2 or version == SessionTableVersion.AUTO:
- span.set_attribute("session_table_version", "v2")
- result = get_lazy_session_table_values_v2(key, search_term=search_term, team=team)
- else:
- span.set_attribute("session_table_version", "v1")
- result = get_lazy_session_table_values_v1(key, search_term=search_term, team=team)
+ # A user-safe ClickHouse error (such as a timeout) is the caller's 400, not a 500.
+ try:
+ if version == SessionTableVersion.V3:
+ span.set_attribute("session_table_version", "v3")
+ result = get_lazy_session_table_values_v3(key, search_term=search_term, team=team)
+ elif version == SessionTableVersion.V2 or version == SessionTableVersion.AUTO:
+ span.set_attribute("session_table_version", "v2")
+ result = get_lazy_session_table_values_v2(key, search_term=search_term, team=team)
+ else:
+ span.set_attribute("session_table_version", "v1")
+ result = get_lazy_session_table_values_v1(key, search_term=search_term, team=team)
+ except ExposedCHQueryError as e:
+ raise ValidationError(str(e), e.code_name)
span.set_attribute("result_count", len(result))
diff --git a/posthog/api/test/test_session.py b/posthog/api/test/test_session.py
index cc2c7cfeb48a..4ea2a044ee52 100644
--- a/posthog/api/test/test_session.py
+++ b/posthog/api/test/test_session.py
@@ -1,10 +1,12 @@
import uuid
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
from parameterized import parameterized
from rest_framework import status
+from posthog.errors import ExposedCHQueryError
from posthog.models.event.util import create_event
from posthog.models.raw_sessions.sessions_v3 import SESSION_V3_LOWER_TIER_AD_IDS
from posthog.models.utils import uuid7
@@ -216,6 +218,16 @@ class TestSessionsAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
assert len(response.json()["results"]) == 0
+ def test_values_returns_400_on_user_safe_clickhouse_error(self):
+ _set_session_table_version(self.team, "v2")
+ with patch(
+ "posthog.hogql.query.sync_execute",
+ side_effect=ExposedCHQueryError("Estimated query execution time is too long", code_name="timeout"),
+ ):
+ response = self.client.get(f"/api/projects/{self.team.pk}/sessions/values/?key=$entry_utm_source")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ assert "Estimated query execution time" in response.json()["detail"]
+
@parameterized.expand([("v2",), ("v3",)])
def test_numerical_session_properties(self, version):
_set_session_table_version(self.team, version)
diff --git a/posthog/hogql/ACCESS_CONTROL.md b/posthog/hogql/ACCESS_CONTROL.md
index c43b51db25cc..703fdc42c4b8 100644
--- a/posthog/hogql/ACCESS_CONTROL.md
+++ b/posthog/hogql/ACCESS_CONTROL.md
@@ -57,6 +57,7 @@ The MCP `execute-sql` tool goes through the same path (`posthog/api/query.py` ru
**Fail closed:** if you forget to pass the user, all access-controlled system tables are removed (`_compute_system_table_access_decision` in `posthog/hogql/database/database.py` returns every scoped table as denied for `user=None`), and all warehouse tables/views are denied (`_is_warehouse_table_denied` / `_is_warehouse_view_denied` fail closed when `user_access_control is None`).
This is deliberate: if someone forgets to pass the user, the query fails outright and makes the mistake obvious, instead of silently falling back to a permissive "default access" that would leak data.
In practice the user is available anywhere system tables are queried; for user-initiated background work, see [contexts without a request user](#contexts-without-a-request-user).
+`Database.create_for_posthog_tables`, the cheaper build for Python-built queries over built-in tables, has no user at all and removes every scoped and entitlement-gated system table up front without the access-control lookups, so it fails closed the same way.
## 1. System tables
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 60cc097d5bae..e47b3db2d412 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -1397,6 +1397,46 @@ class Database(BaseModel):
sources, timings=timings, build_postgres_foreign_keys=build_postgres_foreign_keys
)
+ @staticmethod
+ def create_for_posthog_tables(
+ team: Team, *, modifiers: HogQLQueryModifiers | None = None, timings: HogQLTimings | None = None
+ ) -> Database:
+ """PostHog's built-in tables only, wired for the team's modifiers, with no Postgres I/O.
+
+ For internal queries that touch only built-in tables. It has no warehouse tables, views, or
+ joins, no group-type tables, and no per-user access control, so it must never serve
+ user-written HogQL. Every access-controlled or entitlement-gated system table is removed up
+ front, so a query that names one fails with TableAccessDeniedError instead of reading rows
+ unchecked. create_for runs a dozen Postgres queries and feature-flag checks that such a
+ query never uses; on teams with many warehouse tables that costs more than the query."""
+ if timings is None:
+ timings = HogQLTimings()
+ with timings.measure("modifiers"):
+ modifiers = create_default_modifiers_for_team(team, modifiers)
+ sources = HogQLDatabaseSources(
+ team=team,
+ user=None,
+ connection_id=None,
+ modifiers=modifiers,
+ is_managed_viewset_enabled=False,
+ is_hogql_warehouse_access_control_enabled=False,
+ is_data_quality_enabled=False,
+ is_billing_usage_records_enabled=False,
+ bypass_warehouse_access_control=False,
+ direct_connection_metadata=None,
+ user_access_control=None,
+ denied_system_table_names=set(_scoped_system_tables()) | set(_system_table_required_features()),
+ group_types=[],
+ saved_queries=[],
+ endpoint_saved_queries=[],
+ revenue_views=[],
+ warehouse_tables=[],
+ data_warehouse_joins=[],
+ data_warehouse_expressions=[],
+ event_modifier_saved_queries={},
+ )
+ return Database._build_from_sources(sources, timings=timings)
+
@staticmethod
def _fetch_sources(
team_id: int | None = None,
diff --git a/posthog/hogql/database/schema/sessions_v1.py b/posthog/hogql/database/schema/sessions_v1.py
index a7745759ad5d..4b15927c80c3 100644
--- a/posthog/hogql/database/schema/sessions_v1.py
+++ b/posthog/hogql/database/schema/sessions_v1.py
@@ -1,5 +1,6 @@
import re
-from typing import TYPE_CHECKING, Optional, cast
+import copy
+from typing import TYPE_CHECKING, Any, Optional, cast
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
@@ -20,9 +21,10 @@ from posthog.hogql.database.models import (
from posthog.hogql.database.schema.channel_type import DEFAULT_CHANNEL_TYPES, ChannelTypeExprs, create_channel_type_expr
from posthog.hogql.database.schema.util.where_clause_extractor import SessionMinTimestampWhereClauseExtractorV1
from posthog.hogql.errors import ResolutionError
+from posthog.hogql.modifiers import create_default_modifiers_for_team
+from posthog.hogql.parser import parse_expr, parse_select
-from posthog.queries.insight import insight_sync_execute
-from posthog.schema_enums import BounceRatePageViewMode
+from posthog.schema_enums import BounceRatePageViewMode, SessionTableVersion
if TYPE_CHECKING:
from posthog.models.team import Team
@@ -504,38 +506,110 @@ def get_lazy_session_table_properties_v1(search: Optional[str]):
# NOTE: Keep the AD IDs in sync with `products.web_analytics.backend.hogql_queries.session_attribution_explorer_query_runner.py`
-SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR_MAP = {
- "$entry_referring_domain": "finalizeAggregation(initial_referring_domain)",
- "$entry_utm_source": "finalizeAggregation(initial_utm_source)",
- "$entry_utm_campaign": "finalizeAggregation(initial_utm_campaign)",
- "$entry_utm_medium": "finalizeAggregation(initial_utm_medium)",
- "$entry_utm_term": "finalizeAggregation(initial_utm_term)",
- "$entry_utm_content": "finalizeAggregation(initial_utm_content)",
- "$entry_gclid": "finalizeAggregation(initial_gclid)",
- "$entry_gad_source": "finalizeAggregation(initial_gad_source)",
- "$entry_gclsrc": "finalizeAggregation(initial_gclsrc)",
- "$entry_dclid": "finalizeAggregation(initial_dclid)",
- "$entry_gbraid": "finalizeAggregation(initial_gbraid)",
- "$entry_wbraid": "finalizeAggregation(initial_wbraid)",
- "$entry_fbclid": "finalizeAggregation(initial_fbclid)",
- "$entry_msclkid": "finalizeAggregation(initial_msclkid)",
- "$entry_twclid": "finalizeAggregation(initial_twclid)",
- "$entry_li_fat_id": "finalizeAggregation(initial_li_fat_id)",
- "$entry_mc_cid": "finalizeAggregation(initial_mc_cid)",
- "$entry_igshid": "finalizeAggregation(initial_igshid)",
- "$entry_ttclid": "finalizeAggregation(initial_ttclid)",
- "$entry_current_url": "finalizeAggregation(entry_url)",
- "$exit_current_url": "finalizeAggregation(exit_url)",
+def finalize_aggregation(column: str) -> ast.Expr:
+ return ast.Call(name="_finalizeAggregation", args=[ast.Field(chain=[column])])
+
+
+SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR: dict[str, ast.Expr] = {
+ "$entry_referring_domain": finalize_aggregation("initial_referring_domain"),
+ "$entry_utm_source": finalize_aggregation("initial_utm_source"),
+ "$entry_utm_campaign": finalize_aggregation("initial_utm_campaign"),
+ "$entry_utm_medium": finalize_aggregation("initial_utm_medium"),
+ "$entry_utm_term": finalize_aggregation("initial_utm_term"),
+ "$entry_utm_content": finalize_aggregation("initial_utm_content"),
+ "$entry_gclid": finalize_aggregation("initial_gclid"),
+ "$entry_gad_source": finalize_aggregation("initial_gad_source"),
+ "$entry_gclsrc": finalize_aggregation("initial_gclsrc"),
+ "$entry_dclid": finalize_aggregation("initial_dclid"),
+ "$entry_gbraid": finalize_aggregation("initial_gbraid"),
+ "$entry_wbraid": finalize_aggregation("initial_wbraid"),
+ "$entry_fbclid": finalize_aggregation("initial_fbclid"),
+ "$entry_msclkid": finalize_aggregation("initial_msclkid"),
+ "$entry_twclid": finalize_aggregation("initial_twclid"),
+ "$entry_li_fat_id": finalize_aggregation("initial_li_fat_id"),
+ "$entry_mc_cid": finalize_aggregation("initial_mc_cid"),
+ "$entry_igshid": finalize_aggregation("initial_igshid"),
+ "$entry_ttclid": finalize_aggregation("initial_ttclid"),
+ "$entry_current_url": finalize_aggregation("entry_url"),
+ "$exit_current_url": finalize_aggregation("exit_url"),
}
-def get_lazy_session_table_values_v1(key: str, search_term: Optional[str], team: "Team"):
- # lazy import keeps the sessions SQL module (Django ORM) off this module's import path
- from posthog.models.sessions.sql import ( # noqa: PLC0415
- SELECT_SESSION_PROP_STRING_VALUES_SQL,
- SELECT_SESSION_PROP_STRING_VALUES_SQL_WITH_FILTER,
+def select_session_property_values(
+ team: "Team",
+ *,
+ session_table_version: SessionTableVersion,
+ table: str,
+ value_expr: ast.Expr,
+ order_by: str,
+ search_term: Optional[str],
+ recent_sessions_only: Optional[ast.Expr] = None,
+) -> list[tuple[Any, ...]]:
+ """The 20 most common values of one raw sessions column among the newest 100k stored rows.
+
+ The raw table holds aggregate states, and finalizeAggregation reads each stored row as-is.
+ The `sessions` lazy table would instead merge every row of the team before the sample,
+ which is far too slow for autocomplete. Unmerged rows can count a session more than once;
+ that does not matter for a popularity ranking."""
+ # Deferred: posthog.hogql.query imports the database, which imports this module.
+ from posthog.hogql.context import HogQLContext # noqa: PLC0415
+ from posthog.hogql.database.database import Database # noqa: PLC0415
+ from posthog.hogql.query import execute_hogql_query # noqa: PLC0415
+
+ def value() -> ast.Expr:
+ # replace_placeholders writes the template position onto the spliced node, and the map
+ # entries are shared, so every placement gets its own copy.
+ return copy.deepcopy(value_expr)
+
+ if search_term:
+ query_type = "get_session_property_values_with_value"
+ value_filters = [
+ parse_expr("{value} ILIKE {pattern}", {"value": value(), "pattern": ast.Constant(value=f"%{search_term}%")})
+ ]
+ else:
+ query_type = "get_session_property_values"
+ value_filters = [
+ parse_expr("{value} IS NOT NULL", {"value": value()}),
+ parse_expr("{value} != ''", {"value": value()}),
+ ]
+ where = ast.And(exprs=[*([recent_sessions_only] if recent_sessions_only is not None else []), *value_filters])
+ query = parse_select(
+ """
+ SELECT value, count(value)
+ FROM (
+ SELECT {value} AS value
+ FROM {table}
+ WHERE {where}
+ ORDER BY {order_by} DESC
+ LIMIT 100000
+ )
+ GROUP BY value
+ ORDER BY count(value) DESC
+ LIMIT 20
+ """,
+ placeholders={
+ "value": value(),
+ "table": ast.Field(chain=[table]),
+ "where": where,
+ "order_by": ast.Field(chain=[order_by]),
+ },
)
+ # Each version reads its own raw table, so pin the version instead of trusting the team default.
+ modifiers = create_default_modifiers_for_team(team).model_copy(
+ update={"sessionTableVersion": session_table_version}
+ )
+ # The query touches only the raw sessions table, so skip the per-team warehouse schema build.
+ database = Database.create_for_posthog_tables(team, modifiers=modifiers)
+ return execute_hogql_query(
+ query,
+ team=team,
+ query_type=query_type,
+ modifiers=modifiers,
+ context=HogQLContext(team_id=team.pk, database=database),
+ ).results
+
+def get_lazy_session_table_values_v1(key: str, search_term: Optional[str], team: "Team"):
# the sessions table does not have a properties json object like the events and person tables
if key == "$channel_type":
@@ -546,23 +620,18 @@ def get_lazy_session_table_values_v1(key: str, search_term: Optional[str], team:
return []
if isinstance(field_definition, StringDatabaseField):
- expr = SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR_MAP.get(key)
+ value_expr = SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR.get(key)
- if not expr:
+ if value_expr is None:
return []
- if search_term:
- return insight_sync_execute(
- SELECT_SESSION_PROP_STRING_VALUES_SQL_WITH_FILTER.format(property_expr=expr),
- {"team_id": team.pk, "key": key, "value": "%{}%".format(search_term)},
- query_type="get_session_property_values_with_value",
- team_id=team.pk,
- )
- return insight_sync_execute(
- SELECT_SESSION_PROP_STRING_VALUES_SQL.format(property_expr=expr),
- {"team_id": team.pk, "key": key},
- query_type="get_session_property_values",
- team_id=team.pk,
+ return select_session_property_values(
+ team,
+ session_table_version=SessionTableVersion.V1,
+ table="raw_sessions",
+ value_expr=value_expr,
+ order_by="session_id",
+ search_term=search_term,
)
if isinstance(field_definition, BooleanDatabaseField):
# ideally we'd be able to just send [[True], [False]]
diff --git a/posthog/hogql/database/schema/sessions_v2.py b/posthog/hogql/database/schema/sessions_v2.py
index f78e21f168a6..8f528e87e9af 100644
--- a/posthog/hogql/database/schema/sessions_v2.py
+++ b/posthog/hogql/database/schema/sessions_v2.py
@@ -18,7 +18,12 @@ from posthog.hogql.database.models import (
Table,
)
from posthog.hogql.database.schema.channel_type import DEFAULT_CHANNEL_TYPES, ChannelTypeExprs, create_channel_type_expr
-from posthog.hogql.database.schema.sessions_v1 import DEFAULT_BOUNCE_RATE_DURATION_SECONDS, null_if_empty
+from posthog.hogql.database.schema.sessions_v1 import (
+ DEFAULT_BOUNCE_RATE_DURATION_SECONDS,
+ finalize_aggregation,
+ null_if_empty,
+ select_session_property_values,
+)
from posthog.hogql.database.schema.util.where_clause_extractor import (
SessionMinTimestampWhereClauseExtractorV2,
build_session_id_literal_pushdown_predicate,
@@ -27,10 +32,10 @@ from posthog.hogql.database.schema.util.where_clause_extractor import (
)
from posthog.hogql.errors import ResolutionError
from posthog.hogql.modifiers import create_default_modifiers_for_team
+from posthog.hogql.parser import parse_expr
from posthog.hogql.visitor import clone_expr
-from posthog.queries.insight import insight_sync_execute
-from posthog.schema_enums import BounceRatePageViewMode, SessionsV2JoinMode
+from posthog.schema_enums import BounceRatePageViewMode, SessionsV2JoinMode, SessionTableVersion
if TYPE_CHECKING:
from posthog.schema import CustomChannelRule
@@ -777,44 +782,38 @@ def get_lazy_session_table_properties_v2(search: Optional[str]):
# NOTE: Keep the AD IDs in sync with `products.web_analytics.backend.hogql_queries.session_attribution_explorer_query_runner.py`
-SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR_MAP = {
- "$entry_referring_domain": "finalizeAggregation(initial_referring_domain)",
- "$entry_utm_source": "finalizeAggregation(initial_utm_source)",
- "$entry_utm_campaign": "finalizeAggregation(initial_utm_campaign)",
- "$entry_utm_medium": "finalizeAggregation(initial_utm_medium)",
- "$entry_utm_term": "finalizeAggregation(initial_utm_term)",
- "$entry_utm_content": "finalizeAggregation(initial_utm_content)",
- "$entry_gclid": "finalizeAggregation(initial_gclid)",
- "$entry_gad_source": "finalizeAggregation(initial_gad_source)",
- "$entry_gclsrc": "finalizeAggregation(initial_gclsrc)",
- "$entry_dclid": "finalizeAggregation(initial_dclid)",
- "$entry_gbraid": "finalizeAggregation(initial_gbraid)",
- "$entry_wbraid": "finalizeAggregation(initial_wbraid)",
- "$entry_fbclid": "finalizeAggregation(initial_fbclid)",
- "$entry_msclkid": "finalizeAggregation(initial_msclkid)",
- "$entry_twclid": "finalizeAggregation(initial_twclid)",
- "$entry_li_fat_id": "finalizeAggregation(initial_li_fat_id)",
- "$entry_mc_cid": "finalizeAggregation(initial_mc_cid)",
- "$entry_igshid": "finalizeAggregation(initial_igshid)",
- "$entry_ttclid": "finalizeAggregation(initial_ttclid)",
- "$entry__kx": "finalizeAggregation(initial__kx)",
- "$entry_irclid": "finalizeAggregation(initial_irclid)",
- "$entry_pathname": "path(finalizeAggregation(entry_url))",
- "$entry_current_url": "finalizeAggregation(entry_url)",
- "$end_current_url": "finalizeAggregation(end_url)",
- "$end_pathname": "path(finalizeAggregation(end_url))",
- "$last_external_click_url": "finalizeAggregation(last_external_click_url)",
- "$vitals_lcp": "finalizeAggregation(vitals_lcp)",
+SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR: dict[str, ast.Expr] = {
+ "$entry_referring_domain": finalize_aggregation("initial_referring_domain"),
+ "$entry_utm_source": finalize_aggregation("initial_utm_source"),
+ "$entry_utm_campaign": finalize_aggregation("initial_utm_campaign"),
+ "$entry_utm_medium": finalize_aggregation("initial_utm_medium"),
+ "$entry_utm_term": finalize_aggregation("initial_utm_term"),
+ "$entry_utm_content": finalize_aggregation("initial_utm_content"),
+ "$entry_gclid": finalize_aggregation("initial_gclid"),
+ "$entry_gad_source": finalize_aggregation("initial_gad_source"),
+ "$entry_gclsrc": finalize_aggregation("initial_gclsrc"),
+ "$entry_dclid": finalize_aggregation("initial_dclid"),
+ "$entry_gbraid": finalize_aggregation("initial_gbraid"),
+ "$entry_wbraid": finalize_aggregation("initial_wbraid"),
+ "$entry_fbclid": finalize_aggregation("initial_fbclid"),
+ "$entry_msclkid": finalize_aggregation("initial_msclkid"),
+ "$entry_twclid": finalize_aggregation("initial_twclid"),
+ "$entry_li_fat_id": finalize_aggregation("initial_li_fat_id"),
+ "$entry_mc_cid": finalize_aggregation("initial_mc_cid"),
+ "$entry_igshid": finalize_aggregation("initial_igshid"),
+ "$entry_ttclid": finalize_aggregation("initial_ttclid"),
+ "$entry__kx": finalize_aggregation("initial__kx"),
+ "$entry_irclid": finalize_aggregation("initial_irclid"),
+ "$entry_pathname": ast.Call(name="path", args=[finalize_aggregation("entry_url")]),
+ "$entry_current_url": finalize_aggregation("entry_url"),
+ "$end_current_url": finalize_aggregation("end_url"),
+ "$end_pathname": ast.Call(name="path", args=[finalize_aggregation("end_url")]),
+ "$last_external_click_url": finalize_aggregation("last_external_click_url"),
+ "$vitals_lcp": finalize_aggregation("vitals_lcp"),
}
def get_lazy_session_table_values_v2(key: str, search_term: Optional[str], team: "Team"):
- # lazy import keeps the raw-sessions SQL module (Django ORM) off this module's import path
- from posthog.models.raw_sessions.sessions_v2 import ( # noqa: PLC0415
- RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL,
- RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL_WITH_FILTER,
- )
-
# the sessions table does not have a properties json object like the events and person tables
if key == "$channel_type":
@@ -835,23 +834,21 @@ def get_lazy_session_table_values_v2(key: str, search_term: Optional[str], team:
return []
if isinstance(field_definition, StringDatabaseField):
- expr = SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR_MAP.get(key)
+ value_expr = SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR.get(key)
- if not expr:
+ if value_expr is None:
return []
- if search_term:
- return insight_sync_execute(
- RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL_WITH_FILTER.format(property_expr=expr),
- {"team_id": team.pk, "key": key, "value": "%{}%".format(search_term)},
- query_type="get_session_property_values_with_value",
- team_id=team.pk,
- )
- return insight_sync_execute(
- RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL.format(property_expr=expr),
- {"team_id": team.pk, "key": key},
- query_type="get_session_property_values",
- team_id=team.pk,
+ return select_session_property_values(
+ team,
+ session_table_version=SessionTableVersion.V2,
+ table="raw_sessions",
+ value_expr=value_expr,
+ order_by="session_id_v7",
+ search_term=search_term,
+ recent_sessions_only=parse_expr(
+ "fromUnixTimestamp(intDiv(_toUInt64(bitShiftRight(session_id_v7, 80)), 1000)) >= now() - INTERVAL 30 DAY"
+ ),
)
if isinstance(field_definition, BooleanDatabaseField):
# ideally we'd be able to just send [[True], [False]]
diff --git a/posthog/hogql/database/schema/sessions_v3.py b/posthog/hogql/database/schema/sessions_v3.py
index be08cc297c6b..0262f3abc834 100644
--- a/posthog/hogql/database/schema/sessions_v3.py
+++ b/posthog/hogql/database/schema/sessions_v3.py
@@ -19,13 +19,18 @@ from posthog.hogql.database.models import (
UUIDDatabaseField,
)
from posthog.hogql.database.schema.channel_type import DEFAULT_CHANNEL_TYPES, ChannelTypeExprs, create_channel_type_expr
-from posthog.hogql.database.schema.sessions_v1 import DEFAULT_BOUNCE_RATE_DURATION_SECONDS
+from posthog.hogql.database.schema.sessions_v1 import (
+ DEFAULT_BOUNCE_RATE_DURATION_SECONDS,
+ finalize_aggregation,
+ select_session_property_values,
+)
from posthog.hogql.database.schema.util.where_clause_extractor import SessionMinTimestampWhereClauseExtractorV3
from posthog.hogql.errors import ResolutionError
from posthog.hogql.modifiers import create_default_modifiers_for_team
+from posthog.hogql.parser import parse_expr
-from posthog.queries.insight import insight_sync_execute
from posthog.raw_sessions_v3_ad_ids import SESSION_V3_LOWER_TIER_AD_IDS
+from posthog.schema_enums import SessionTableVersion
if TYPE_CHECKING:
from posthog.schema import CustomChannelRule
@@ -576,38 +581,33 @@ def get_lazy_session_table_properties_v3(search: Optional[str]):
# NOTE: Keep the AD IDs in sync with `products.web_analytics.backend.hogql_queries.session_attribution_explorer_query_runner.py`
-SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR_MAP = {
- "$entry_referring_domain": "finalizeAggregation(entry_referring_domain)",
- "$entry_utm_source": "finalizeAggregation(entry_utm_source)",
- "$entry_utm_campaign": "finalizeAggregation(entry_utm_campaign)",
- "$entry_utm_medium": "finalizeAggregation(entry_utm_medium)",
- "$entry_utm_term": "finalizeAggregation(entry_utm_term)",
- "$entry_utm_content": "finalizeAggregation(entry_utm_content)",
- "$entry_gclid": "finalizeAggregation(entry_gclid)",
- "$entry_gad_source": "finalizeAggregation(entry_gad_source)",
- "$entry_fbclid": "finalizeAggregation(entry_fbclid)",
- "$entry_current_url": "finalizeAggregation(entry_url)",
- "$entry_pathname": "path(finalizeAggregation(entry_url))",
- "$entry_hostname": "domain(finalizeAggregation(entry_url))",
- "$end_current_url": "finalizeAggregation(end_url)",
- "$end_pathname": "path(finalizeAggregation(end_url))",
- "$end_hostname": "domain(finalizeAggregation(end_url))",
- "$last_external_click_url": "finalizeAggregation(last_external_click_url)",
+SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR: dict[str, ast.Expr] = {
+ "$entry_referring_domain": finalize_aggregation("entry_referring_domain"),
+ "$entry_utm_source": finalize_aggregation("entry_utm_source"),
+ "$entry_utm_campaign": finalize_aggregation("entry_utm_campaign"),
+ "$entry_utm_medium": finalize_aggregation("entry_utm_medium"),
+ "$entry_utm_term": finalize_aggregation("entry_utm_term"),
+ "$entry_utm_content": finalize_aggregation("entry_utm_content"),
+ "$entry_gclid": finalize_aggregation("entry_gclid"),
+ "$entry_gad_source": finalize_aggregation("entry_gad_source"),
+ "$entry_fbclid": finalize_aggregation("entry_fbclid"),
+ "$entry_current_url": finalize_aggregation("entry_url"),
+ "$entry_pathname": ast.Call(name="path", args=[finalize_aggregation("entry_url")]),
+ "$entry_hostname": ast.Call(name="domain", args=[finalize_aggregation("entry_url")]),
+ "$end_current_url": finalize_aggregation("end_url"),
+ "$end_pathname": ast.Call(name="path", args=[finalize_aggregation("end_url")]),
+ "$end_hostname": ast.Call(name="domain", args=[finalize_aggregation("end_url")]),
+ "$last_external_click_url": finalize_aggregation("last_external_click_url"),
}
for session_ad_id in SESSION_V3_LOWER_TIER_AD_IDS:
- SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR_MAP["$entry_" + session_ad_id] = (
- f"arrayElement(finalizeAggregation(entry_ad_ids_map), '{session_ad_id}')"
+ SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR["$entry_" + session_ad_id] = ast.Call(
+ name="arrayElement",
+ args=[finalize_aggregation("entry_ad_ids_map"), ast.Constant(value=session_ad_id)],
)
def get_lazy_session_table_values_v3(key: str, search_term: Optional[str], team: "Team"):
- # lazy import keeps the raw-sessions SQL module (Django ORM) off this module's import path
- from posthog.models.raw_sessions.sessions_v3 import ( # noqa: PLC0415
- RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL_V3,
- RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL_WITH_FILTER_V3,
- )
-
# the sessions table does not have a properties json object like the events and person tables
if key == "$channel_type":
@@ -628,23 +628,19 @@ def get_lazy_session_table_values_v3(key: str, search_term: Optional[str], team:
return []
if isinstance(field_definition, StringDatabaseField):
- expr = SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR_MAP.get(key)
+ value_expr = SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR.get(key)
- if not expr:
+ if value_expr is None:
return []
- if search_term:
- return insight_sync_execute(
- RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL_WITH_FILTER_V3.format(property_expr=expr),
- {"team_id": team.pk, "key": key, "value": "%{}%".format(search_term)},
- query_type="get_session_property_values_with_value",
- team_id=team.pk,
- )
- return insight_sync_execute(
- RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL_V3.format(property_expr=expr),
- {"team_id": team.pk, "key": key},
- query_type="get_session_property_values",
- team_id=team.pk,
+ return select_session_property_values(
+ team,
+ session_table_version=SessionTableVersion.V3,
+ table="raw_sessions_v3",
+ value_expr=value_expr,
+ order_by="session_id_v7",
+ search_term=search_term,
+ recent_sessions_only=parse_expr("session_timestamp >= now() - INTERVAL 30 DAY"),
)
if isinstance(field_definition, BooleanDatabaseField):
# ideally we'd be able to just send [[True], [False]]
diff --git a/posthog/hogql/database/schema/test/test_sessions_v1.py b/posthog/hogql/database/schema/test/test_sessions_v1.py
index 04139d748533..d8777c68b2e1 100644
--- a/posthog/hogql/database/schema/test/test_sessions_v1.py
+++ b/posthog/hogql/database/schema/test/test_sessions_v1.py
@@ -1,5 +1,6 @@
import pytest
from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, ClickhouseTestMixin, _create_event
+from unittest.mock import patch
from django.db.utils import IntegrityError
@@ -8,6 +9,7 @@ from parameterized import parameterized
from posthog.schema import BounceRatePageViewMode, HogQLQueryModifiers, SessionTableVersion
from posthog.hogql import ast
+from posthog.hogql.database.database import Database
from posthog.hogql.database.schema.sessions_v1 import (
get_lazy_session_table_properties_v1,
get_lazy_session_table_values_v1,
@@ -360,6 +362,25 @@ class TestGetLazySessionProperties(ClickhouseTestMixin, APIBaseTest):
for prop in results:
get_lazy_session_table_values_v1(key=prop["id"], team=self.team, search_term=None)
+ @parameterized.expand([(None,), ("tub",)])
+ def test_values_query_samples_raw_rows(self, search_term):
+ with (
+ patch.object(Database, "_fetch_sources", side_effect=AssertionError("full database build")),
+ self.capture_select_queries() as queries,
+ ):
+ get_lazy_session_table_values_v1(key="$entry_utm_source", team=self.team, search_term=search_term)
+
+ assert len(queries) == 1
+ sql = " ".join(queries[0].split())
+ assert "FROM sessions" in sql
+ assert "finalizeAggregation(sessions.initial_utm_source)" in sql
+ assert "ORDER BY sessions.session_id DESC" in sql
+ assert "LIMIT 100000" in sql
+ # The `sessions` lazy table would merge every row of the team first.
+ assert "argMinMerge" not in sql
+ assert sql.count("GROUP BY") == 1
+ assert ("ilike(" in sql) == (search_term is not None)
+
def test_custom_channel_types(self):
results = get_lazy_session_table_values_v1(key="$channel_type", team=self.team, search_term=None)
# the custom channel types should be first, there's should be no duplicates, and any custom rules for existing
diff --git a/posthog/hogql/database/schema/test/test_sessions_v2.py b/posthog/hogql/database/schema/test/test_sessions_v2.py
index cc8405f264c6..82d0188a6b7a 100644
--- a/posthog/hogql/database/schema/test/test_sessions_v2.py
+++ b/posthog/hogql/database/schema/test/test_sessions_v2.py
@@ -4,6 +4,7 @@ from typing import cast
import pytest
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
+from unittest.mock import patch
from parameterized import parameterized
@@ -878,6 +879,25 @@ class TestGetLazySessionProperties(ClickhouseTestMixin, APIBaseTest):
for prop in results:
get_lazy_session_table_values_v2(key=prop["id"], team=self.team, search_term=None)
+ @parameterized.expand([(None,), ("tub",)])
+ def test_values_query_samples_raw_rows(self, search_term):
+ with (
+ patch.object(Database, "_fetch_sources", side_effect=AssertionError("full database build")),
+ self.capture_select_queries() as queries,
+ ):
+ get_lazy_session_table_values_v2(key="$entry_utm_source", team=self.team, search_term=search_term)
+
+ assert len(queries) == 1
+ sql = " ".join(queries[0].split())
+ assert "FROM raw_sessions" in sql
+ assert "finalizeAggregation(raw_sessions.initial_utm_source)" in sql
+ assert "ORDER BY raw_sessions.session_id_v7 DESC" in sql
+ assert "LIMIT 100000" in sql
+ # The `sessions` lazy table would merge every row of the team first.
+ assert "argMinMerge" not in sql
+ assert sql.count("GROUP BY") == 1
+ assert ("ilike(" in sql) == (search_term is not None)
+
def test_custom_channel_types(self):
self.team.modifiers = {
"customChannelTypeRules": [
diff --git a/posthog/hogql/database/schema/test/test_sessions_v3.py b/posthog/hogql/database/schema/test/test_sessions_v3.py
index 008541154f41..80bbe2538448 100644
--- a/posthog/hogql/database/schema/test/test_sessions_v3.py
+++ b/posthog/hogql/database/schema/test/test_sessions_v3.py
@@ -9,10 +9,14 @@ from posthog.test.base import (
_create_person,
snapshot_clickhouse_queries,
)
+from unittest.mock import patch
+
+from parameterized import parameterized
from posthog.schema import FilterLogicalOperator, HogQLQueryModifiers, SessionTableVersion
from posthog.hogql import ast
+from posthog.hogql.database.database import Database
from posthog.hogql.database.schema.sessions_v3 import (
get_lazy_session_table_properties_v3,
get_lazy_session_table_values_v3,
@@ -793,6 +797,25 @@ class TestGetLazySessionProperties(ClickhouseTestMixin, APIBaseTest):
for prop in results:
get_lazy_session_table_values_v3(key=prop["id"], team=self.team, search_term=None)
+ @parameterized.expand([(None,), ("tub",)])
+ def test_values_query_samples_raw_rows(self, search_term):
+ with (
+ patch.object(Database, "_fetch_sources", side_effect=AssertionError("full database build")),
+ self.capture_select_queries() as queries,
+ ):
+ get_lazy_session_table_values_v3(key="$entry_utm_source", team=self.team, search_term=search_term)
+
+ assert len(queries) == 1
+ sql = " ".join(queries[0].split())
+ assert "FROM raw_sessions_v3" in sql
+ assert "finalizeAggregation(raw_sessions_v3.entry_utm_source)" in sql
+ assert "ORDER BY raw_sessions_v3.session_id_v7 DESC" in sql
+ assert "LIMIT 100000" in sql
+ # The `sessions` lazy table would merge every row of the team first.
+ assert "argMinMerge" not in sql
+ assert sql.count("GROUP BY") == 1
+ assert ("ilike(" in sql) == (search_term is not None)
+
def test_custom_channel_types(self):
self.team.modifiers = {
"customChannelTypeRules": [
diff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.py
index 4dd55d405e97..b485fa5f756d 100644
--- a/posthog/hogql/database/test/test_database.py
+++ b/posthog/hogql/database/test/test_database.py
@@ -57,7 +57,8 @@ from posthog.hogql.database.models import (
)
from posthog.hogql.database.postgres_table import PostgresTable
from posthog.hogql.database.s3_table import DataWarehouseTable as HogQLDataWarehouseTable
-from posthog.hogql.errors import ExposedHogQLError, QueryError
+from posthog.hogql.database.schema.sessions_v2 import RawSessionsTableV2
+from posthog.hogql.errors import ExposedHogQLError, QueryError, TableAccessDeniedError
from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.printer import prepare_and_print_ast
@@ -69,6 +70,7 @@ from posthog.models.group_type_mapping import invalidate_group_types_cache
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.scoping import team_scope
from posthog.models.team.team import Team
+from posthog.schema_enums import SessionTableVersion
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
@@ -4181,3 +4183,27 @@ class TestDatabase(BaseTest, QueryMatchingTest):
database = Database.create_for(team=self.team, user=self.user)
assert ("system.activity_logs" in database.get_system_table_names()) is expected_visible
+
+
+class TestCreateForPosthogTables(BaseTest):
+ def test_builds_without_postgres_and_applies_modifiers(self):
+ modifiers = HogQLQueryModifiers(sessionTableVersion=SessionTableVersion.V2)
+ with (
+ patch.object(Database, "_fetch_sources", side_effect=AssertionError("full database build")),
+ # One cached instance-setting read is fine; the full build issues a dozen queries.
+ self.assertNumQueries(FuzzyInt(0, 1)),
+ ):
+ database = Database.create_for_posthog_tables(self.team, modifiers=modifiers)
+
+ assert isinstance(database.get_table("raw_sessions"), RawSessionsTableV2)
+ assert "events" in database.get_posthog_table_names()
+ assert database.get_warehouse_table_names() == []
+
+ def test_removes_gated_system_tables(self):
+ database = Database.create_for_posthog_tables(self.team)
+
+ system_table_names = database.get_system_table_names()
+ assert "system.feature_flags" not in system_table_names
+ assert "system.activity_logs" not in system_table_names
+ with pytest.raises(TableAccessDeniedError):
+ database.get_table("system.activity_logs")
diff --git a/posthog/hogql/functions/mapping.py b/posthog/hogql/functions/mapping.py
index c4b4c1940f89..382afa31595e 100644
--- a/posthog/hogql/functions/mapping.py
+++ b/posthog/hogql/functions/mapping.py
@@ -259,6 +259,10 @@ HOGQL_CLICKHOUSE_FUNCTIONS: dict[str, HogQLFunctionMeta] = {
],
signatures=[((StringType(),), StringType())],
),
+ # Reads an aggregate function state as a plain value. The underscore keeps it out of autocomplete and
+ # marks it private: Python-built queries over the raw sessions tables use it, and it can change or go
+ # away without notice.
+ "_finalizeAggregation": HogQLFunctionMeta("finalizeAggregation", 1, 1),
}
diff --git a/posthog/models/raw_sessions/sessions_v2.py b/posthog/models/raw_sessions/sessions_v2.py
index 5537b2adc77f..f5858c25596b 100644
--- a/posthog/models/raw_sessions/sessions_v2.py
+++ b/posthog/models/raw_sessions/sessions_v2.py
@@ -577,46 +577,3 @@ FROM {TABLE_BASE_NAME}
GROUP BY session_id_v7, team_id
"""
)
-
-RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL = """
-SELECT
- value,
- count(value)
-FROM (
- SELECT
- {property_expr} as value
- FROM
- raw_sessions
- WHERE
- team_id = %(team_id)s AND
- fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(session_id_v7, 80)), 1000)) >= now() - INTERVAL 30 DAY AND
- {property_expr} IS NOT NULL AND
- {property_expr} != ''
- ORDER BY session_id_v7 DESC
- LIMIT 100000
-)
-GROUP BY value
-ORDER BY count(value) DESC
-LIMIT 20
-"""
-
-RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL_WITH_FILTER = """
-SELECT
- value,
- count(value)
-FROM (
- SELECT
- {property_expr} as value
- FROM
- raw_sessions
- WHERE
- team_id = %(team_id)s AND
- fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(session_id_v7, 80)), 1000)) >= now() - INTERVAL 30 DAY AND
- {property_expr} ILIKE %(value)s
- ORDER BY session_id_v7 DESC
- LIMIT 100000
-)
-GROUP BY value
-ORDER BY count(value) DESC
-LIMIT 20
-"""
diff --git a/posthog/models/raw_sessions/sessions_v3.py b/posthog/models/raw_sessions/sessions_v3.py
index 6fdab7782910..036efd0d5f2f 100644
--- a/posthog/models/raw_sessions/sessions_v3.py
+++ b/posthog/models/raw_sessions/sessions_v3.py
@@ -754,49 +754,6 @@ GROUP BY session_id_v7, session_timestamp, team_id
"""
)
-RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL_V3 = """
-SELECT
- value,
- count(value)
-FROM (
- SELECT
- {property_expr} as value
- FROM
- raw_sessions_v3
- WHERE
- team_id = %(team_id)s AND
- session_timestamp >= now() - INTERVAL 30 DAY AND
- {property_expr} IS NOT NULL AND
- {property_expr} != ''
- ORDER BY session_id_v7 DESC
- LIMIT 100000
-)
-GROUP BY value
-ORDER BY count(value) DESC
-LIMIT 20
-"""
-
-RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL_WITH_FILTER_V3 = """
-SELECT
- value,
- count(value)
-FROM (
- SELECT
- {property_expr} as value
- FROM
- raw_sessions_v3
- WHERE
- team_id = %(team_id)s AND
- session_timestamp >= now() - INTERVAL 30 DAY AND
- {property_expr} ILIKE %(value)s
- ORDER BY session_id_v7 DESC
- LIMIT 100000
-)
-GROUP BY value
-ORDER BY count(value) DESC
-LIMIT 20
-"""
-
def GET_NUM_RAW_SESSIONS_ACTIVE_PARTS(
partitions: list[str],
diff --git a/posthog/models/sessions/sql.py b/posthog/models/sessions/sql.py
index 56d23f258fa5..ce57c27bc724 100644
--- a/posthog/models/sessions/sql.py
+++ b/posthog/models/sessions/sql.py
@@ -314,44 +314,3 @@ FROM sessions
GROUP BY session_id, team_id
"""
)
-
-SELECT_SESSION_PROP_STRING_VALUES_SQL = """
-SELECT
- value,
- count(value)
-FROM (
- SELECT
- {property_expr} as value
- FROM
- sessions
- WHERE
- team_id = %(team_id)s AND
- {property_expr} IS NOT NULL AND
- {property_expr} != ''
- ORDER BY session_id DESC
- LIMIT 100000
-)
-GROUP BY value
-ORDER BY count(value) DESC
-LIMIT 20
-"""
-
-SELECT_SESSION_PROP_STRING_VALUES_SQL_WITH_FILTER = """
-SELECT
- value,
- count(value)
-FROM (
- SELECT
- {property_expr} as value
- FROM
- sessions
- WHERE
- team_id = %(team_id)s AND
- {property_expr} ILIKE %(value)s
- ORDER BY session_id DESC
- LIMIT 100000
-)
-GROUP BY value
-ORDER BY count(value) DESC
-LIMIT 20
-"""
diff --git a/posthog/queries/insight.py b/posthog/queries/insight.py
deleted file mode 100644
index 9c77059c9db4..000000000000
--- a/posthog/queries/insight.py
+++ /dev/null
@@ -1,39 +0,0 @@
-from typing import TYPE_CHECKING, Optional
-
-from rest_framework.exceptions import ValidationError
-
-from posthog.clickhouse.client import sync_execute
-from posthog.clickhouse.query_tagging import tag_queries
-from posthog.errors import ExposedCHQueryError
-
-if TYPE_CHECKING:
- from posthog.types import FilterType
-
-
-# Wrapper around sync_execute, adding query tags for insights performance
-def insight_sync_execute(
- query,
- args=None,
- *,
- team_id: int,
- query_type: str,
- filter: Optional["FilterType"] = None,
- **kwargs,
-):
- tag_queries(team_id=team_id)
- _tag_query(query, query_type, filter)
- try:
- return sync_execute(query, args=args, team_id=team_id, **kwargs)
- except ExposedCHQueryError as e:
- raise ValidationError(str(e), e.code_name)
-
-
-def _tag_query(query, query_type, filter: Optional["FilterType"]):
- tag_queries(
- query_type=query_type,
- has_joins="JOIN" in query,
- has_json_operations="JSONExtract" in query or "JSONHas" in query,
- )
-
- if filter is not None:
- tag_queries(filter=filter.to_dict(), **filter.query_tags())
diff --git a/posthog/queries/property_values.py b/posthog/queries/property_values.py
index 7d1d4a5b29ab..a47d701bcc9b 100644
--- a/posthog/queries/property_values.py
+++ b/posthog/queries/property_values.py
@@ -2,8 +2,9 @@ from typing import Optional
from opentelemetry import trace
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.query_tagging import tag_queries
from posthog.models.team import Team
-from posthog.queries.insight import insight_sync_execute
tracer = trace.get_tracer(__name__)
@@ -34,10 +35,10 @@ def get_event_property_values_from_aggregated_table(key: str, team: Team, value:
value_filter = "AND lower(property_value) LIKE %(value)s"
params["value"] = f"%{escaped.lower()}%"
- result = insight_sync_execute(
+ tag_queries(team_id=team.pk, query_type="get_event_property_values_from_aggregated_table")
+ result = sync_execute(
SELECT_EVENT_PROPERTY_VALUES_FROM_AGGREGATED_TABLE_SQL.format(value_filter=value_filter),
params,
- query_type="get_event_property_values_from_aggregated_table",
team_id=team.pk,
)
span.set_attribute("result_count", len(result))
diff --git a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr
index 1a845d4f727f..a0c9a8e1e264 100644
--- a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr
+++ b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr
@@ -64,7 +64,7 @@
HogQL defines what functions are available with most (but not all) having a 1:1 mapping to ClickHouse functions.
These are the non-aggregated HogQL functions:
```
- ['plus', 'minus', 'multiply', 'divide', 'intDiv', 'intDivOrZero', 'modulo', 'moduloOrZero', 'positiveModulo', 'negate', 'abs', 'gcd', 'lcm', 'max2', 'min2', 'multiplyDecimal', 'divideDecimal', 'empty', 'notEmpty', 'length', 'reverse', 'array', 'range', 'arrayConcat', 'arrayElement', 'has', 'hasAll', 'hasAny', 'hasSubstr', 'indexOf', 'arrayCount', 'countEqual', 'arrayEnumerate', 'arrayEnumerateUniq', 'arrayPopBack', 'arrayPopFront', 'arrayPushBack', 'arrayPushFront', 'arrayResize', 'arraySlice', 'arraySort', 'arrayReverseSort', 'arrayUniq', 'arrayJoin', 'arrayDifference', 'arrayDistinct', 'arrayEnumerateDense', 'arrayIntersect', 'arrayReduce', 'arrayReverse', 'arrayFilter', 'arrayFlatten', 'arrayCompact', 'arrayZip', 'arrayAUC', 'arrayMap', 'arrayFill', 'arrayFold', 'arrayWithConstant', 'arraySplit', 'arrayReverseFill', 'arrayReverseSplit', 'arrayRotateLeft', 'arrayRotateRight', 'arrayExists', 'arrayAll', 'arrayFirst', 'arrayLast', 'arrayFirstIndex', 'arrayLastIndex', 'arrayMin', 'arrayMax', 'arraySum', 'arrayAvg', 'arrayCumSum', 'arrayCumSumNonNegative', 'arrayProduct', 'arrayStringConcat', 'generateSeries', 'hex', 'unhex', 'reinterpretAsUInt8', 'reinterpretAsUInt16', 'reinterpretAsUInt32', 'reinterpretAsUInt64', 'reinterpretAsUInt128', 'reinterpretAsUInt256', 'reinterpretAsInt8', 'reinterpretAsInt16', 'reinterpretAsInt32', 'reinterpretAsInt64', 'reinterpretAsInt128', 'reinterpretAsInt256', 'reinterpretAsFloat32', 'reinterpretAsFloat64', 'reinterpretAsUUID', 'accurateCast', 'accurateCastOrNull', 'toInt', 'toIntOrZero', 'toIntOrDefault', '_toInt8', '_toInt16', '_toInt32', '_toInt64', '_toUInt8', '_toUInt64', '_toUInt128', 'toFloat', 'toFloatOrNull', 'toFloat64OrNull', 'toFloatOrZero', 'toFloatOrDefault', 'toDecimal', '_toDate', 'toUUID', 'toUUIDOrDefault', 'toString', 'toNullableString', 'toBool', 'toJSONString', 'parseDateTime', 'parseDateTimeBestEffort', 'dynamicType', 'toTypeName', 'defaultValueOfTypeName', 'cityHash64', 'UUIDv7ToDateTime', 'toDate', 'to_date', 'toDateTime', 'toDateTime64', 'toDateTimeUS', 'isnull', 'isNotNull', 'coalesce', 'ifnull', 'nullif', 'assumeNotNull', 'toNullable', 'timeZoneOf', 'timeZoneOffset', 'toYear', 'toQuarter', 'toMonth', 'toDayOfYear', 'toDayOfMonth', 'toDayOfWeek', 'toHour', 'toMinute', 'toSecond', 'toUnixTimestamp', 'toUnixTimestamp64Milli', 'fromUnixTimestamp64Milli', 'toStartOfInterval', 'toStartOfYear', 'toStartOfISOYear', 'toStartOfQuarter', 'toStartOfMonth', 'toLastDayOfMonth', 'toMonday', 'toStartOfWeek', 'toStartOfDay', 'toLastDayOfWeek', 'toStartOfHour', 'toStartOfMinute', 'toStartOfSecond', 'toStartOfFiveMinutes', 'toStartOfTenMinutes', 'toStartOfFifteenMinutes', 'toTime', 'toISOYear', 'toISOWeek', 'toWeek', 'toYearWeek', 'age', 'dateAdd', 'dateSub', 'date_bin', 'date_add', 'date_subtract', 'date_diff', 'dateDiff', 'timeStampAdd', 'timeStampSub', 'nowInBlock', 'rowNumberInBlock', 'rowNumberInAllBlocks', 'timeSlot', 'toYYYYMM', 'toYYYYMMDD', 'toYYYYMMDDhhmmss', 'addYears', 'addMonths', 'addWeeks', 'addDays', 'addHours', 'addMinutes', 'addSeconds', 'addQuarters', 'subtractYears', 'subtractMonths', 'subtractWeeks', 'subtractDays', 'subtractHours', 'subtractMinutes', 'subtractSeconds', 'subtractQuarters', 'timeSlots', 'formatDateTime', 'dateName', 'monthName', 'fromUnixTimestamp', 'toModifiedJulianDay', 'fromModifiedJulianDay', 'toIntervalSecond', 'toIntervalMinute', 'toIntervalHour', 'toIntervalDay', 'toIntervalWeek', 'toIntervalMonth', 'toIntervalQuarter', 'toIntervalYear', 'now', 'yesterday', 'current_timestamp', 'today', 'current_date', 'date_part', 'date_trunc', 'dateTrunc', 'to_timestamp', 'to_char', 'make_timestamp', 'make_date', 'make_interval', 'make_timestamptz', 'timezone', 'toTimeZone', 'greatCircleDistance', 'geoDistance', 'greatCircleAngle', 'pointInEllipses', 'pointInPolygon', 'geohashEncode', 'geohashDecode', 'geohashesInBox', 'h3IsValid', 'h3GetResolution', 'h3GetBaseCell', 'h3EdgeAngle', 'h3EdgeLengthM', 'h3EdgeLengthKm', 'geoToH3', 'h3ToGeo', 'h3ToGeoBoundary', 'h3kRing', 'h3HexAreaM2', 'h3HexAreaKm2', 'h3IndexesAreNeighbors', 'h3ToChildren', 'h3ToParent', 'h3ToString', 'stringToH3', 'h3IsResClassIII', 'h3IsPentagon', 'h3GetFaces', 'h3CellAreaM2', 'h3CellAreaRads2', 'h3ToCenterChild', 'h3ExactEdgeLengthM', 'h3ExactEdgeLengthKm', 'h3ExactEdgeLengthRads', 'h3NumHexagons', 'h3PointDistM', 'h3PointDistKm', 'h3PointDistRads', 'h3GetRes0Indexes', 'h3GetPentagonIndexes', 'h3Line', 'h3Distance', 'h3HexRing', 'h3GetUnidirectionalEdge', 'h3UnidirectionalEdgeIsValid', 'h3GetOriginIndexFromUnidirectionalEdge', 'h3GetDestinationIndexFromUnidirectionalEdge', 'h3GetIndexesFromUnidirectionalEdge', 'h3GetUnidirectionalEdgesFromHexagon', 'h3GetUnidirectionalEdgeBoundary', 'isValidJSON', 'JSONHas', 'JSONLength', 'JSONArrayLength', 'JSONType', 'JSONExtract', 'JSONExtractUInt', 'JSONExtractInt', 'JSONExtractFloat', 'JSONExtractBool', 'JSONExtractString', 'JSONExtractKeys', 'JSONExtractRaw', 'JSONExtractArrayRaw', 'JSONExtractKeysAndValues', 'JSONExtractKeysAndValuesRaw', 'JSON_VALUE', 'e', 'pi', 'exp', 'log', 'ln', 'exp2', 'log2', 'exp10', 'log10', 'sqrt', 'cbrt', 'erf', 'erfc', 'lgamma', 'tgamma', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'pow', 'power', 'intExp2', 'intExp10', 'cosh', 'acosh', 'sinh', 'asinh', 'atanh', 'atan2', 'hypot', 'log1p', 'sign', 'degrees', 'radians', 'factorial', 'width_bucket', 'floor', 'ceil', 'trunc', 'round', 'roundBankers', 'roundToExp2', 'roundDuration', 'roundAge', 'roundDown', 'rand', 'left', 'right', 'lengthUTF8', 'leftPad', 'rightPad', 'leftPadUTF8', 'rightPadUTF8', 'lower', 'upper', 'lowerUTF8', 'upperUTF8', 'isValidUTF8', 'toValidUTF8', 'format', 'reverseUTF8', 'concat', 'substring', 'substringUTF8', 'appendTrailingCharIfAbsent', 'convertCharset', 'base58Encode', 'base58Decode', 'tryBase58Decode', 'base64Encode', 'base64Decode', 'tryBase64Decode', 'endsWith', 'startsWith', 'encodeXMLComponent', 'decodeXMLComponent', 'extractTextFromHTML', 'ascii', 'concatWithSeparator', 'position', 'positionCaseInsensitive', 'positionUTF8', 'positionCaseInsensitiveUTF8', 'multiSearchAllPositions', 'multiSearchAllPositionsUTF8', 'multiSearchFirstPosition', 'multiSearchFirstIndex', 'multiSearchAny', 'multiSearchAllPositionsCaseInsensitive', 'multiSearchAllPositionsCaseInsensitiveUTF8', 'multiSearchAnyUTF8', 'multiSearchAnyCaseInsensitive', 'multiSearchAnyCaseInsensitiveUTF8', 'multiSearchFirstIndexUTF8', 'multiSearchFirstIndexCaseInsensitive', 'multiSearchFirstIndexCaseInsensitiveUTF8', 'multiSearchFirstPositionUTF8', 'multiSearchFirstPositionCaseInsensitive', 'multiSearchFirstPositionCaseInsensitiveUTF8', 'match', 'multiMatchAny', 'multiMatchAnyIndex', 'multiMatchAllIndices', 'multiFuzzyMatchAny', 'multiFuzzyMatchAnyIndex', 'multiFuzzyMatchAllIndices', 'extract', 'extractAll', 'extractAllGroupsHorizontal', 'extractAllGroupsVertical', 'extractGroups', 'like', 'ilike', 'notLike', 'notILike', 'locate', 'ngramDistance', 'ngramDistanceCaseInsensitive', 'ngramDistanceUTF8', 'ngramDistanceCaseInsensitiveUTF8', 'ngramSearch', 'ngramSearchCaseInsensitive', 'ngramSearchUTF8', 'ngramSearchCaseInsensitiveUTF8', 'countSubstrings', 'countSubstringsCaseInsensitive', 'countSubstringsCaseInsensitiveUTF8', 'countMatches', 'countMatchesCaseInsensitive', 'hasSubsequence', 'hasSubsequenceCaseInsensitive', 'hasSubsequenceUTF8', 'hasSubsequenceCaseInsensitiveUTF8', 'hasToken', 'hasTokenCaseInsensitive', 'hasTokenOrNull', 'hasTokenCaseInsensitiveOrNull', 'hasAllTokens', 'hasAnyTokens', 'regexpExtract', 'replace', 'replaceAll', 'replaceOne', 'replaceRegexpAll', 'replaceRegexpOne', 'regexpQuoteMeta', 'translate', 'translateUTF8', 'splitByChar', 'splitByString', 'splitByRegexp', 'splitByWhitespace', 'splitByNonAlpha', 'alphaTokens', 'extractAllGroups', 'ngrams', 'tokens', 'repeat', 'initcap', 'lpad', 'rpad', 'split_part', 'ltrim', 'trimLeft', 'rtrim', 'trimRight', 'btrim', 'trim', 'equals', 'notEquals', 'less', 'greater', 'lessOrEquals', 'greaterOrEquals', 'in', 'notIn', 'and', 'or', 'xor', 'not', '_caseWithExpression', 'if', 'multiIf', 'throwIf', 'map', 'mapFromArrays', 'mapAdd', 'mapSubtract', 'mapPopulateSeries', 'mapContains', 'mapKeys', 'mapValues', 'mapContainsKeyLike', 'mapExtractKeyLike', 'mapApply', 'mapFilter', 'mapUpdate', 'bitAnd', 'bitOr', 'bitXor', 'bitNot', 'bitShiftLeft', 'bitShiftRight', 'bitRotateLeft', 'bitRotateRight', 'bitSlice', 'bitTest', 'bitTestAll', 'bitTestAny', 'bitCount', 'bitHammingDistance', 'bitmapBuild', 'bitmapToArray', 'bitmapSubsetInRange', 'bitmapSubsetLimit', 'subBitmap', 'bitmapContains', 'bitmapHasAny', 'bitmapHasAll', 'bitmapCardinality', 'bitmapMin', 'bitmapMax', 'bitmapTransform', 'bitmapAnd', 'bitmapOr', 'bitmapXor', 'bitmapAndnot', 'bitmapAndCardinality', 'bitmapOrCardinality', 'bitmapXorCardinality', 'bitmapAndnotCardinality', 'protocol', 'domain', 'domainWithoutWWW', 'topLevelDomain', 'firstSignificantSubdomain', 'cutToFirstSignificantSubdomain', 'cutToFirstSignificantSubdomainWithWWW', 'port', 'path', 'pathFull', 'queryString', 'fragment', 'queryStringAndFragment', 'extractURLParameter', 'extractURLParameters', 'extractURLParameterNames', 'URLHierarchy', 'URLPathHierarchy', 'encodeURLComponent', 'decodeURLComponent', 'encodeURLFormComponent', 'decodeURLFormComponent', 'netloc', 'cutWWW', 'cutQueryString', 'cutFragment', 'cutQueryStringAndFragment', 'cutURLParameter', 'IPv4NumToString', 'IPv4StringToNum', 'IPv4StringToNumOrDefault', 'IPv4StringToNumOrNull', 'IPv6NumToString', 'IPv6StringToNum', 'IPv6StringToNumOrDefault', 'IPv6StringToNumOrNull', 'IPv4ToIPv6', 'toIPv4', 'toIPv4OrDefault', 'toIPv4OrNull', 'toIPv4OrZero', 'toIPv6', 'toIPv6OrDefault', 'toIPv6OrNull', 'toIPv6OrZero', 'isIPv4String', 'isIPv6String', 'isIPAddressInRange', 'IPv4CIDRToRange', 'IPv6CIDRToRange', 'cutIPv6', 'tuple', 'tupleElement', 'untuple', 'tupleHammingDistance', 'tupleToNameValuePairs', 'tuplePlus', 'tupleMinus', 'tupleMultiply', 'tupleDivide', 'tupleNegate', 'tupleMultiplyByNumber', 'tupleDivideByNumber', 'dotProduct', 'isFinite', 'isInfinite', 'ifNotFinite', 'isNaN', 'bar', 'transform', 'formatReadableDecimalSize', 'formatReadableSize', 'formatReadableQuantity', 'formatReadableTimeDelta', 'least', 'greatest', 'indexHint', 'extractIPv4Substrings', 'tumble', 'hop', 'tumbleStart', 'tumbleEnd', 'hopStart', 'hopEnd', 'L1Norm', 'L2Norm', 'LinfNorm', 'LpNorm', 'L1Distance', 'L2Distance', 'LinfDistance', 'LpDistance', 'L1Normalize', 'L2Normalize', 'LinfNormalize', 'LpNormalize', 'cosineDistance', 'rank', 'dense_rank', 'row_number', 'first_value', 'last_value', 'nth_value', 'lagInFrame', 'leadInFrame', 'lag', 'lead', 'languageCodeToName', 'aggregate_funnel', 'aggregate_funnel_array', 'aggregate_funnel_cohort', 'aggregate_funnel_trends', 'aggregate_funnel_array_trends', 'aggregate_funnel_cohort_trends', 'aggregate_funnel_json', 'aggregate_funnel_array_json', 'aggregate_funnel_cohort_json', 'aggregate_funnel_trends_json', 'aggregate_funnel_array_trends_json', 'aggregate_funnel_cohort_trends_json', 'aggregate_funnel_test', 'aggregate_funnel_array_trends_test']
+ ['plus', 'minus', 'multiply', 'divide', 'intDiv', 'intDivOrZero', 'modulo', 'moduloOrZero', 'positiveModulo', 'negate', 'abs', 'gcd', 'lcm', 'max2', 'min2', 'multiplyDecimal', 'divideDecimal', 'empty', 'notEmpty', 'length', 'reverse', 'array', 'range', 'arrayConcat', 'arrayElement', 'has', 'hasAll', 'hasAny', 'hasSubstr', 'indexOf', 'arrayCount', 'countEqual', 'arrayEnumerate', 'arrayEnumerateUniq', 'arrayPopBack', 'arrayPopFront', 'arrayPushBack', 'arrayPushFront', 'arrayResize', 'arraySlice', 'arraySort', 'arrayReverseSort', 'arrayUniq', 'arrayJoin', 'arrayDifference', 'arrayDistinct', 'arrayEnumerateDense', 'arrayIntersect', 'arrayReduce', 'arrayReverse', 'arrayFilter', 'arrayFlatten', 'arrayCompact', 'arrayZip', 'arrayAUC', 'arrayMap', 'arrayFill', 'arrayFold', 'arrayWithConstant', 'arraySplit', 'arrayReverseFill', 'arrayReverseSplit', 'arrayRotateLeft', 'arrayRotateRight', 'arrayExists', 'arrayAll', 'arrayFirst', 'arrayLast', 'arrayFirstIndex', 'arrayLastIndex', 'arrayMin', 'arrayMax', 'arraySum', 'arrayAvg', 'arrayCumSum', 'arrayCumSumNonNegative', 'arrayProduct', 'arrayStringConcat', 'generateSeries', 'hex', 'unhex', 'reinterpretAsUInt8', 'reinterpretAsUInt16', 'reinterpretAsUInt32', 'reinterpretAsUInt64', 'reinterpretAsUInt128', 'reinterpretAsUInt256', 'reinterpretAsInt8', 'reinterpretAsInt16', 'reinterpretAsInt32', 'reinterpretAsInt64', 'reinterpretAsInt128', 'reinterpretAsInt256', 'reinterpretAsFloat32', 'reinterpretAsFloat64', 'reinterpretAsUUID', 'accurateCast', 'accurateCastOrNull', 'toInt', 'toIntOrZero', 'toIntOrDefault', '_toInt8', '_toInt16', '_toInt32', '_toInt64', '_toUInt8', '_toUInt64', '_toUInt128', 'toFloat', 'toFloatOrNull', 'toFloat64OrNull', 'toFloatOrZero', 'toFloatOrDefault', 'toDecimal', '_toDate', 'toUUID', 'toUUIDOrDefault', 'toString', 'toNullableString', 'toBool', 'toJSONString', 'parseDateTime', 'parseDateTimeBestEffort', 'dynamicType', 'toTypeName', 'defaultValueOfTypeName', 'cityHash64', 'UUIDv7ToDateTime', 'toDate', 'to_date', 'toDateTime', 'toDateTime64', 'toDateTimeUS', 'isnull', 'isNotNull', 'coalesce', 'ifnull', 'nullif', 'assumeNotNull', 'toNullable', 'timeZoneOf', 'timeZoneOffset', 'toYear', 'toQuarter', 'toMonth', 'toDayOfYear', 'toDayOfMonth', 'toDayOfWeek', 'toHour', 'toMinute', 'toSecond', 'toUnixTimestamp', 'toUnixTimestamp64Milli', 'fromUnixTimestamp64Milli', 'toStartOfInterval', 'toStartOfYear', 'toStartOfISOYear', 'toStartOfQuarter', 'toStartOfMonth', 'toLastDayOfMonth', 'toMonday', 'toStartOfWeek', 'toStartOfDay', 'toLastDayOfWeek', 'toStartOfHour', 'toStartOfMinute', 'toStartOfSecond', 'toStartOfFiveMinutes', 'toStartOfTenMinutes', 'toStartOfFifteenMinutes', 'toTime', 'toISOYear', 'toISOWeek', 'toWeek', 'toYearWeek', 'age', 'dateAdd', 'dateSub', 'date_bin', 'date_add', 'date_subtract', 'date_diff', 'dateDiff', 'timeStampAdd', 'timeStampSub', 'nowInBlock', 'rowNumberInBlock', 'rowNumberInAllBlocks', 'timeSlot', 'toYYYYMM', 'toYYYYMMDD', 'toYYYYMMDDhhmmss', 'addYears', 'addMonths', 'addWeeks', 'addDays', 'addHours', 'addMinutes', 'addSeconds', 'addQuarters', 'subtractYears', 'subtractMonths', 'subtractWeeks', 'subtractDays', 'subtractHours', 'subtractMinutes', 'subtractSeconds', 'subtractQuarters', 'timeSlots', 'formatDateTime', 'dateName', 'monthName', 'fromUnixTimestamp', 'toModifiedJulianDay', 'fromModifiedJulianDay', 'toIntervalSecond', 'toIntervalMinute', 'toIntervalHour', 'toIntervalDay', 'toIntervalWeek', 'toIntervalMonth', 'toIntervalQuarter', 'toIntervalYear', 'now', 'yesterday', 'current_timestamp', 'today', 'current_date', 'date_part', 'date_trunc', 'dateTrunc', 'to_timestamp', 'to_char', 'make_timestamp', 'make_date', 'make_interval', 'make_timestamptz', 'timezone', 'toTimeZone', 'greatCircleDistance', 'geoDistance', 'greatCircleAngle', 'pointInEllipses', 'pointInPolygon', 'geohashEncode', 'geohashDecode', 'geohashesInBox', 'h3IsValid', 'h3GetResolution', 'h3GetBaseCell', 'h3EdgeAngle', 'h3EdgeLengthM', 'h3EdgeLengthKm', 'geoToH3', 'h3ToGeo', 'h3ToGeoBoundary', 'h3kRing', 'h3HexAreaM2', 'h3HexAreaKm2', 'h3IndexesAreNeighbors', 'h3ToChildren', 'h3ToParent', 'h3ToString', 'stringToH3', 'h3IsResClassIII', 'h3IsPentagon', 'h3GetFaces', 'h3CellAreaM2', 'h3CellAreaRads2', 'h3ToCenterChild', 'h3ExactEdgeLengthM', 'h3ExactEdgeLengthKm', 'h3ExactEdgeLengthRads', 'h3NumHexagons', 'h3PointDistM', 'h3PointDistKm', 'h3PointDistRads', 'h3GetRes0Indexes', 'h3GetPentagonIndexes', 'h3Line', 'h3Distance', 'h3HexRing', 'h3GetUnidirectionalEdge', 'h3UnidirectionalEdgeIsValid', 'h3GetOriginIndexFromUnidirectionalEdge', 'h3GetDestinationIndexFromUnidirectionalEdge', 'h3GetIndexesFromUnidirectionalEdge', 'h3GetUnidirectionalEdgesFromHexagon', 'h3GetUnidirectionalEdgeBoundary', 'isValidJSON', 'JSONHas', 'JSONLength', 'JSONArrayLength', 'JSONType', 'JSONExtract', 'JSONExtractUInt', 'JSONExtractInt', 'JSONExtractFloat', 'JSONExtractBool', 'JSONExtractString', 'JSONExtractKeys', 'JSONExtractRaw', 'JSONExtractArrayRaw', 'JSONExtractKeysAndValues', 'JSONExtractKeysAndValuesRaw', 'JSON_VALUE', 'e', 'pi', 'exp', 'log', 'ln', 'exp2', 'log2', 'exp10', 'log10', 'sqrt', 'cbrt', 'erf', 'erfc', 'lgamma', 'tgamma', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'pow', 'power', 'intExp2', 'intExp10', 'cosh', 'acosh', 'sinh', 'asinh', 'atanh', 'atan2', 'hypot', 'log1p', 'sign', 'degrees', 'radians', 'factorial', 'width_bucket', 'floor', 'ceil', 'trunc', 'round', 'roundBankers', 'roundToExp2', 'roundDuration', 'roundAge', 'roundDown', 'rand', 'left', 'right', 'lengthUTF8', 'leftPad', 'rightPad', 'leftPadUTF8', 'rightPadUTF8', 'lower', 'upper', 'lowerUTF8', 'upperUTF8', 'isValidUTF8', 'toValidUTF8', 'format', 'reverseUTF8', 'concat', 'substring', 'substringUTF8', 'appendTrailingCharIfAbsent', 'convertCharset', 'base58Encode', 'base58Decode', 'tryBase58Decode', 'base64Encode', 'base64Decode', 'tryBase64Decode', 'endsWith', 'startsWith', 'encodeXMLComponent', 'decodeXMLComponent', 'extractTextFromHTML', 'ascii', 'concatWithSeparator', 'position', 'positionCaseInsensitive', 'positionUTF8', 'positionCaseInsensitiveUTF8', 'multiSearchAllPositions', 'multiSearchAllPositionsUTF8', 'multiSearchFirstPosition', 'multiSearchFirstIndex', 'multiSearchAny', 'multiSearchAllPositionsCaseInsensitive', 'multiSearchAllPositionsCaseInsensitiveUTF8', 'multiSearchAnyUTF8', 'multiSearchAnyCaseInsensitive', 'multiSearchAnyCaseInsensitiveUTF8', 'multiSearchFirstIndexUTF8', 'multiSearchFirstIndexCaseInsensitive', 'multiSearchFirstIndexCaseInsensitiveUTF8', 'multiSearchFirstPositionUTF8', 'multiSearchFirstPositionCaseInsensitive', 'multiSearchFirstPositionCaseInsensitiveUTF8', 'match', 'multiMatchAny', 'multiMatchAnyIndex', 'multiMatchAllIndices', 'multiFuzzyMatchAny', 'multiFuzzyMatchAnyIndex', 'multiFuzzyMatchAllIndices', 'extract', 'extractAll', 'extractAllGroupsHorizontal', 'extractAllGroupsVertical', 'extractGroups', 'like', 'ilike', 'notLike', 'notILike', 'locate', 'ngramDistance', 'ngramDistanceCaseInsensitive', 'ngramDistanceUTF8', 'ngramDistanceCaseInsensitiveUTF8', 'ngramSearch', 'ngramSearchCaseInsensitive', 'ngramSearchUTF8', 'ngramSearchCaseInsensitiveUTF8', 'countSubstrings', 'countSubstringsCaseInsensitive', 'countSubstringsCaseInsensitiveUTF8', 'countMatches', 'countMatchesCaseInsensitive', 'hasSubsequence', 'hasSubsequenceCaseInsensitive', 'hasSubsequenceUTF8', 'hasSubsequenceCaseInsensitiveUTF8', 'hasToken', 'hasTokenCaseInsensitive', 'hasTokenOrNull', 'hasTokenCaseInsensitiveOrNull', 'hasAllTokens', 'hasAnyTokens', 'regexpExtract', 'replace', 'replaceAll', 'replaceOne', 'replaceRegexpAll', 'replaceRegexpOne', 'regexpQuoteMeta', 'translate', 'translateUTF8', 'splitByChar', 'splitByString', 'splitByRegexp', 'splitByWhitespace', 'splitByNonAlpha', 'alphaTokens', 'extractAllGroups', 'ngrams', 'tokens', 'repeat', 'initcap', 'lpad', 'rpad', 'split_part', 'ltrim', 'trimLeft', 'rtrim', 'trimRight', 'btrim', 'trim', 'equals', 'notEquals', 'less', 'greater', 'lessOrEquals', 'greaterOrEquals', 'in', 'notIn', 'and', 'or', 'xor', 'not', '_caseWithExpression', 'if', 'multiIf', 'throwIf', 'map', 'mapFromArrays', 'mapAdd', 'mapSubtract', 'mapPopulateSeries', 'mapContains', 'mapKeys', 'mapValues', 'mapContainsKeyLike', 'mapExtractKeyLike', 'mapApply', 'mapFilter', 'mapUpdate', 'bitAnd', 'bitOr', 'bitXor', 'bitNot', 'bitShiftLeft', 'bitShiftRight', 'bitRotateLeft', 'bitRotateRight', 'bitSlice', 'bitTest', 'bitTestAll', 'bitTestAny', 'bitCount', 'bitHammingDistance', 'bitmapBuild', 'bitmapToArray', 'bitmapSubsetInRange', 'bitmapSubsetLimit', 'subBitmap', 'bitmapContains', 'bitmapHasAny', 'bitmapHasAll', 'bitmapCardinality', 'bitmapMin', 'bitmapMax', 'bitmapTransform', 'bitmapAnd', 'bitmapOr', 'bitmapXor', 'bitmapAndnot', 'bitmapAndCardinality', 'bitmapOrCardinality', 'bitmapXorCardinality', 'bitmapAndnotCardinality', 'protocol', 'domain', 'domainWithoutWWW', 'topLevelDomain', 'firstSignificantSubdomain', 'cutToFirstSignificantSubdomain', 'cutToFirstSignificantSubdomainWithWWW', 'port', 'path', 'pathFull', 'queryString', 'fragment', 'queryStringAndFragment', 'extractURLParameter', 'extractURLParameters', 'extractURLParameterNames', 'URLHierarchy', 'URLPathHierarchy', 'encodeURLComponent', 'decodeURLComponent', 'encodeURLFormComponent', 'decodeURLFormComponent', 'netloc', 'cutWWW', 'cutQueryString', 'cutFragment', 'cutQueryStringAndFragment', 'cutURLParameter', 'IPv4NumToString', 'IPv4StringToNum', 'IPv4StringToNumOrDefault', 'IPv4StringToNumOrNull', 'IPv6NumToString', 'IPv6StringToNum', 'IPv6StringToNumOrDefault', 'IPv6StringToNumOrNull', 'IPv4ToIPv6', 'toIPv4', 'toIPv4OrDefault', 'toIPv4OrNull', 'toIPv4OrZero', 'toIPv6', 'toIPv6OrDefault', 'toIPv6OrNull', 'toIPv6OrZero', 'isIPv4String', 'isIPv6String', 'isIPAddressInRange', 'IPv4CIDRToRange', 'IPv6CIDRToRange', 'cutIPv6', 'tuple', 'tupleElement', 'untuple', 'tupleHammingDistance', 'tupleToNameValuePairs', 'tuplePlus', 'tupleMinus', 'tupleMultiply', 'tupleDivide', 'tupleNegate', 'tupleMultiplyByNumber', 'tupleDivideByNumber', 'dotProduct', 'isFinite', 'isInfinite', 'ifNotFinite', 'isNaN', 'bar', 'transform', 'formatReadableDecimalSize', 'formatReadableSize', 'formatReadableQuantity', 'formatReadableTimeDelta', 'least', 'greatest', 'indexHint', 'extractIPv4Substrings', 'tumble', 'hop', 'tumbleStart', 'tumbleEnd', 'hopStart', 'hopEnd', 'L1Norm', 'L2Norm', 'LinfNorm', 'LpNorm', 'L1Distance', 'L2Distance', 'LinfDistance', 'LpDistance', 'L1Normalize', 'L2Normalize', 'LinfNormalize', 'LpNormalize', 'cosineDistance', 'rank', 'dense_rank', 'row_number', 'first_value', 'last_value', 'nth_value', 'lagInFrame', 'leadInFrame', 'lag', 'lead', 'languageCodeToName', '_finalizeAggregation', 'aggregate_funnel', 'aggregate_funnel_array', 'aggregate_funnel_cohort', 'aggregate_funnel_trends', 'aggregate_funnel_array_trends', 'aggregate_funnel_cohort_trends', 'aggregate_funnel_json', 'aggregate_funnel_array_json', 'aggregate_funnel_cohort_json', 'aggregate_funnel_trends_json', 'aggregate_funnel_array_trends_json', 'aggregate_funnel_cohort_trends_json', 'aggregate_funnel_test', 'aggregate_funnel_array_trends_test']
```
These are the aggregated HogQL functions:
diff --git a/products/logs/backend/group_by_query_runner.py b/products/logs/backend/group_by_query_runner.py
index 47e69285eba9..23e5cdf8503b 100644
--- a/products/logs/backend/group_by_query_runner.py
+++ b/products/logs/backend/group_by_query_runner.py
@@ -286,7 +286,7 @@ class LogsGroupByQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryR
def _calculate(self) -> LogsQueryResponse:
# The group-by templates only reference posthog-native tables (logs, log_attributes)
- # and the grouping key is a bound constant, so hand the executor a plain posthog-only
+ # and the grouping key is a bound constant, so hand the executor a posthog-tables-only
# Database up front. Without it, the `{filters}` placeholder LogsFilterBuilder.where()
# always emits makes the executor run the full per-query database build — warehouse
# tables, saved queries, endpoints: several Postgres round trips this query never uses.
@@ -294,7 +294,7 @@ class LogsGroupByQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryR
team_id=self.team.pk,
team=self.team,
enable_select_queries=True,
- database=Database(timezone=self.team.timezone, week_start_day=self.team.week_start_day),
+ database=Database.create_for_posthog_tables(self.team, modifiers=self.modifiers),
)
response = execute_hogql_query(
query_type="LogsQuery",