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(hogql): extract variable resolution from visit_placeholder (#95827)

posthog[bot]66071add85b4
diff --git a/posthog/api/services/query.py b/posthog/api/services/query.py
index 1c2ebe02fc48..8d4651c2ba29 100644
--- a/posthog/api/services/query.py
+++ b/posthog/api/services/query.py
@@ -34,7 +34,13 @@ from posthog.cloud_utils import is_cloud
from posthog.event_usage import AnalyticsProps
from posthog.exceptions import DatabaseSchemaUnavailable
from posthog.exceptions_capture import capture_exception
-from posthog.hogql_queries.query_runner import CacheMissResponse, ExecutionMode, QueryResponse, get_query_runner_or_none
+from posthog.hogql_queries.query_runner import (
+ CacheMissResponse,
+ ExecutionMode,
+ QueryResponse,
+ QueryRunner,
+ get_query_runner_or_none,
+)
from posthog.models import Team, User
from posthog.schema_migrations.upgrade import upgrade
@@ -296,8 +302,6 @@ def process_query_model(
analytics_props: Optional[AnalyticsProps] = None,
allow_raw_results: bool = False,
) -> dict | BaseModel | RawCachedQueryResponse:
- result: dict | BaseModel | RawCachedQueryResponse
-
if isinstance(query, HogQLAutocomplete):
with EDITOR_ASSIST_DURATION_SECONDS.labels(kind="autocomplete").time():
_, database = resolve_database_for_connection(
@@ -322,67 +326,103 @@ def process_query_model(
query_runner = get_query_runner_or_none(
query, team, limit_context=limit_context, user=user, user_access_control=user_access_control
)
- if query_runner is None: # This query doesn't run via query runner
- if hasattr(query, "source") and isinstance(query.source, BaseModel):
- result = process_query_model(
- team,
- query.source,
- dashboard_filters=dashboard_filters,
- variables_override=variables_override,
- limit_context=limit_context,
- execution_mode=execution_mode,
- user=user,
- user_access_control=user_access_control,
- query_id=query_id,
- insight_id=insight_id,
- dashboard_id=dashboard_id,
- is_query_service=is_query_service,
- cache_age_seconds=cache_age_seconds,
- analytics_props=analytics_props,
- allow_raw_results=allow_raw_results,
- )
- elif execution_mode == ExecutionMode.CACHE_ONLY_NEVER_CALCULATE:
- # Caching is handled by query runners, so in this case we can only return a cache miss
- result = CacheMissResponse(cache_key=None)
- elif isinstance(query, HogQuery):
- if is_cloud() and (user is None or not user.is_staff):
- return {"results": "Hog queries currently require staff user privileges."}
-
- try:
- hog_result = execute_hog(query.code or "", team=team)
- bytecode = hog_result.bytecodes.get("root", None)
- result = HogQueryResponse(
- results=hog_result.result,
- bytecode=bytecode,
- coloredBytecode=color_bytecode(bytecode) if bytecode else None,
- stdout="\n".join(hog_result.stdout),
- )
- except Exception as e:
- result = HogQueryResponse(results=f"ERROR: {str(e)}")
- else:
- raise ValidationError(f"Unsupported query kind: {query.__class__.__name__}")
- else: # Query runner available - it will handle execution as well as caching
- if dashboard_filters:
- query_runner.apply_dashboard_filters(dashboard_filters)
- if variables_override:
- query_runner.apply_variable_overrides(variables_override)
- if pagination_cursor:
- query_runner.apply_pagination_cursor(pagination_cursor)
- query_runner.is_query_service = is_query_service
- if allow_raw_results:
- query_runner.serve_raw_cached_results = True
-
- result = query_runner.run(
+ if query_runner is not None: # Query runner available - it will handle execution as well as caching
+ return _run_query_runner(
+ query_runner,
+ dashboard_filters=dashboard_filters,
+ variables_override=variables_override,
execution_mode=execution_mode,
user=user,
query_id=query_id,
insight_id=insight_id,
dashboard_id=dashboard_id,
+ is_query_service=is_query_service,
cache_age_seconds=cache_age_seconds,
+ pagination_cursor=pagination_cursor,
analytics_props=analytics_props,
+ allow_raw_results=allow_raw_results,
)
- raw_results = query_runner.raw_cached_results_bytes
- if raw_results is not None and isinstance(result, BaseModel):
- return RawCachedQueryResponse(response=result, raw_results=raw_results)
+ # This query doesn't run via query runner
+ if hasattr(query, "source") and isinstance(query.source, BaseModel):
+ return process_query_model(
+ team,
+ query.source,
+ dashboard_filters=dashboard_filters,
+ variables_override=variables_override,
+ limit_context=limit_context,
+ execution_mode=execution_mode,
+ user=user,
+ user_access_control=user_access_control,
+ query_id=query_id,
+ insight_id=insight_id,
+ dashboard_id=dashboard_id,
+ is_query_service=is_query_service,
+ cache_age_seconds=cache_age_seconds,
+ analytics_props=analytics_props,
+ allow_raw_results=allow_raw_results,
+ )
+ if execution_mode == ExecutionMode.CACHE_ONLY_NEVER_CALCULATE:
+ # Caching is handled by query runners, so in this case we can only return a cache miss
+ return CacheMissResponse(cache_key=None)
+ if isinstance(query, HogQuery):
+ return _run_hog_query(query, team, user)
+ raise ValidationError(f"Unsupported query kind: {query.__class__.__name__}")
+
+
+def _run_hog_query(query: HogQuery, team: Team, user: Optional[User]) -> dict | HogQueryResponse:
+ if is_cloud() and (user is None or not user.is_staff):
+ return {"results": "Hog queries currently require staff user privileges."}
+
+ try:
+ hog_result = execute_hog(query.code or "", team=team)
+ bytecode = hog_result.bytecodes.get("root", None)
+ return HogQueryResponse(
+ results=hog_result.result,
+ bytecode=bytecode,
+ coloredBytecode=color_bytecode(bytecode) if bytecode else None,
+ stdout="\n".join(hog_result.stdout),
+ )
+ except Exception as e:
+ return HogQueryResponse(results=f"ERROR: {str(e)}")
+
+
+def _run_query_runner(
+ query_runner: QueryRunner,
+ *,
+ dashboard_filters: Optional[DashboardFilter],
+ variables_override: Optional[list[HogQLVariable]],
+ execution_mode: ExecutionMode,
+ user: Optional[User],
+ query_id: Optional[str],
+ insight_id: Optional[int],
+ dashboard_id: Optional[int],
+ is_query_service: bool,
+ cache_age_seconds: Optional[int],
+ pagination_cursor: Optional[str],
+ analytics_props: Optional[AnalyticsProps],
+ allow_raw_results: bool,
+) -> dict | BaseModel | RawCachedQueryResponse:
+ if dashboard_filters:
+ query_runner.apply_dashboard_filters(dashboard_filters)
+ if variables_override:
+ query_runner.apply_variable_overrides(variables_override)
+ if pagination_cursor:
+ query_runner.apply_pagination_cursor(pagination_cursor)
+ query_runner.is_query_service = is_query_service
+ if allow_raw_results:
+ query_runner.serve_raw_cached_results = True
+
+ result = query_runner.run(
+ execution_mode=execution_mode,
+ user=user,
+ query_id=query_id,
+ insight_id=insight_id,
+ dashboard_id=dashboard_id,
+ cache_age_seconds=cache_age_seconds,
+ analytics_props=analytics_props,
+ )
+ raw_results = query_runner.raw_cached_results_bytes
+ if raw_results is not None and isinstance(result, BaseModel):
+ return RawCachedQueryResponse(response=result, raw_results=raw_results)
return result
diff --git a/posthog/hogql/variables.py b/posthog/hogql/variables.py
index fb3f53020114..db3a21e9c508 100644
--- a/posthog/hogql/variables.py
+++ b/posthog/hogql/variables.py
@@ -1,6 +1,6 @@
import re
from difflib import get_close_matches
-from typing import TypeVar
+from typing import Any, TypeVar
from posthog.schema import HogQLVariable
@@ -33,54 +33,53 @@ class ReplaceVariables(CloningVisitor):
self.team = team
def visit_placeholder(self, node):
- if node.chain and node.chain[0] == "variables":
- variable_code_name = node.chain[1]
- if not self.variables:
- raise self._missing_variable_error(variable_code_name)
-
- matching_variables = [variable for variable in self.variables if variable.code_name == variable_code_name]
- if not matching_variables:
- raise self._missing_variable_error(variable_code_name)
-
- matching_variable = matching_variables[0]
-
- matching_insight_variable = [
- variable for variable in self.insight_variables if variable.code_name == variable_code_name
- ]
- if not matching_insight_variable:
- raise QueryError(f"Variable {variable_code_name} does not exist")
-
- variable_definition = matching_insight_variable[0]
- if matching_variable.isNull:
- if variable_definition.type == InsightVariableType.LIST and variable_definition.is_multi:
- return ast.Array(exprs=[])
- return ast.Constant(value=None)
-
- value = (
- matching_variable.value
- if matching_variable.value is not None
- else matching_insight_variable[0].default_value
- )
-
- if variable_definition.type == InsightVariableType.LIST:
- if variable_definition.is_multi:
- # Saved insights keep the scalar value from before a variable was
- # toggled to multi — wrap it so {variables.x} is always an array.
- items = value if isinstance(value, list) else ([] if value is None else [value])
- return ast.Array(exprs=[ast.Constant(value=item) for item in items])
- if not variable_definition.is_multi and isinstance(value, list):
- value = value[0] if value else None
-
- if (
- variable_definition.type == InsightVariableType.DATE
- and isinstance(value, str)
- and is_relative_date_value(value)
- ):
- value = relative_date_parse(value, self.team.timezone_info)
-
- return ast.Constant(value=value)
-
- return super().visit_placeholder(node)
+ if not (node.chain and node.chain[0] == "variables"):
+ return super().visit_placeholder(node)
+ return self._resolve_variable(node.chain[1])
+
+ def _resolve_variable(self, variable_code_name: str) -> ast.Expr:
+ if not self.variables:
+ raise self._missing_variable_error(variable_code_name)
+
+ matching_variables = [variable for variable in self.variables if variable.code_name == variable_code_name]
+ if not matching_variables:
+ raise self._missing_variable_error(variable_code_name)
+
+ matching_variable = matching_variables[0]
+
+ matching_insight_variable = [
+ variable for variable in self.insight_variables if variable.code_name == variable_code_name
+ ]
+ if not matching_insight_variable:
+ raise QueryError(f"Variable {variable_code_name} does not exist")
+
+ variable_definition = matching_insight_variable[0]
+ if matching_variable.isNull:
+ if variable_definition.type == InsightVariableType.LIST and variable_definition.is_multi:
+ return ast.Array(exprs=[])
+ return ast.Constant(value=None)
+
+ value = matching_variable.value if matching_variable.value is not None else variable_definition.default_value
+ return self._coerce_value(variable_definition, value)
+
+ def _coerce_value(self, variable_definition: InsightVariableDefinition, value: Any) -> ast.Expr:
+ if variable_definition.type == InsightVariableType.LIST:
+ if variable_definition.is_multi:
+ # Saved insights keep the scalar value from before a variable was
+ # toggled to multi — wrap it so {variables.x} is always an array.
+ items = value if isinstance(value, list) else ([] if value is None else [value])
+ return ast.Array(exprs=[ast.Constant(value=item) for item in items])
+ if isinstance(value, list):
+ value = value[0] if value else None
+
+ if (
+ variable_definition.type == InsightVariableType.DATE
+ and isinstance(value, str)
+ and is_relative_date_value(value)
+ ):
+ value = relative_date_parse(value, self.team.timezone_info)
+
+ return ast.Constant(value=value)
def _missing_variable_error(self, variable_code_name: str) -> QueryError:
suggestions = self._get_variable_suggestions(variable_code_name)