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(hogql): handle missing team in Database.create_for lookup (#62318)

posthog[bot]30813dc17a60
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 2250ab8313ae..1d3a0e7aa9df 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -975,7 +975,10 @@ class Database(BaseModel):
raise ValueError("team_id and team must be the same")
if team is None:
- team = Team.objects.get(pk=team_id)
+ try:
+ team = Team.objects.get(pk=team_id)
+ except Team.DoesNotExist:
+ raise QueryError(f"Team with id {team_id} does not exist") from None
# Team is definitely not None at this point, make mypy believe that
team = cast("Team", team)
diff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.py
index 197869360d53..5320543c82c5 100644
--- a/posthog/hogql/database/test/test_database.py
+++ b/posthog/hogql/database/test/test_database.py
@@ -41,7 +41,7 @@ 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
+from posthog.hogql.errors import ExposedHogQLError, QueryError
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
@@ -73,6 +73,12 @@ class TestDatabase(BaseTest, QueryMatchingTest):
with self.assertRaises(ValueError, msg="Either team_id or team must be provided"):
Database.create_for()
+ def test_create_hogql_database_raises_query_error_for_missing_team(self):
+ missing_team_id = self.team.pk + 10_000
+ with self.assertRaises(QueryError) as cm:
+ Database.create_for(team_id=missing_team_id)
+ self.assertIn(str(missing_team_id), str(cm.exception))
+
@pytest.mark.usefixtures("unittest_snapshot")
def test_serialize_database_no_person_on_events(self):
with override_settings(PERSON_ON_EVENTS_V2_OVERRIDE=False):