:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(hogql): offer a quick fix for a misspelled field name (#86017)
George Munyoro29f51c8cf945
diff --git a/posthog/hogql/errors.py b/posthog/hogql/errors.pyindex f8c38dd4055c..f6f61a3c9c12 100644--- a/posthog/hogql/errors.py+++ b/posthog/hogql/errors.py@@ -11,6 +11,10 @@ class BaseHogQLError(Exception, ABC):message: strstart: Optional[int]end: Optional[int]+ fix: Optional[str]+ """Literal text the editor substitutes for the range between `start` and `end`, offered as a+ quick fix. Only set it when that range is known: the editor falls back to marking the whole+ query when a notice has no span, so a fix without one replaces everything the user typed."""def __init__(self,@@ -19,6 +23,7 @@ class BaseHogQLError(Exception, ABC):start: Optional[int] = None,end: Optional[int] = None,node: Optional["Expr"] = None,+ fix: Optional[str] = None,):super().__init__(message)if node is not None and node.start is not None and node.end is not None:@@ -27,6 +32,7 @@ class BaseHogQLError(Exception, ABC):else:self.start = startself.end = end+ self.fix = fix# Exposed vs. internaldiff --git a/posthog/hogql/metadata.py b/posthog/hogql/metadata.pyindex e636bcc4b8e7..fcb60e046562 100644--- a/posthog/hogql/metadata.py+++ b/posthog/hogql/metadata.py@@ -133,10 +133,13 @@ def get_hogql_metadata(# cpp-json (ANTLR) and rust-py word EOF differently; collapse both into a single human-readable string.if "mismatched input '<EOF>' expecting" in error or "unexpected token in expression: Eof" in error:error = "Unexpected end of query"- if e.end and e.start and e.end < e.start:- response.errors.append(HogQLNotice(message=error, start=e.end, end=e.start))- else:- response.errors.append(HogQLNotice(message=error, start=e.start, end=e.end))+ start, end = e.start, e.end+ if start is not None and end is not None and end < start:+ start, end = end, start+ # A notice without a span marks the whole query, so a fix carried alongside one would+ # replace everything the user typed instead of the token the suggestion stands in for.+ fix = e.fix if start is not None and end is not None else None+ response.errors.append(HogQLNotice(message=error, start=start, end=end, fix=fix))elif (settings.DEBUG): # We don't want to accidentally expose too much data via errors, so expose only when debug is enableddiff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.pyindex be41c24111b5..6083db38a84b 100644--- a/posthog/hogql/resolver.py+++ b/posthog/hogql/resolver.py@@ -50,6 +50,7 @@ from posthog.hogql.resolver_utils import (lookup_field_by_name,lookup_table_by_name,suggest_field_names,+ suggested_field_fix,)from posthog.hogql.type_system import (infer_array_access_constant_type,@@ -2312,6 +2313,9 @@ class Resolver(CloningVisitor):suggestions = suggest_field_names(scope, name, self.context)suggestion_suffix = f". Did you mean: {', '.join(suggestions)}?" if suggestions else ""+ # The message lists every close match, but a quick fix can only substitute one, so it+ # offers the best of them. `get_close_matches` returns them in descending similarity.+ fix = suggested_field_fix(node, suggestions[0]) if suggestions else Noneif self.dialect == "clickhouse":# To debug, add a breakpoint() here and print self.context.database#@@ -2321,13 +2325,14 @@ class Resolver(CloningVisitor):## One likely cause is that the database context isn't set up as you# expect it to be.- raise QueryError(f"Unable to resolve field: {name}{suggestion_suffix}")+ raise QueryError(f"Unable to resolve field: {name}{suggestion_suffix}", node=node, fix=fix)else:type = ast.UnresolvedFieldType(name=name)self.context.add_error(start=node.start,end=node.end,message=f"Unable to resolve field: {name}{suggestion_suffix}",+ fix=fix,)# Recursively resolve the rest of the chain until we can point to the deepest node.diff --git a/posthog/hogql/resolver_utils.py b/posthog/hogql/resolver_utils.pyindex c8a1951fb912..0ba511667090 100644--- a/posthog/hogql/resolver_utils.py+++ b/posthog/hogql/resolver_utils.py@@ -27,6 +27,7 @@ from posthog.hogql.database.models import (UUIDDatabaseField,)from posthog.hogql.errors import QueryError, ResolutionError, SyntaxError+from posthog.hogql.escape_sql import escape_hogql_identifierdef lookup_field_by_name(@@ -167,6 +168,25 @@ def suggest_field_names(return difflib.get_close_matches(name, candidates, n=limit, cutoff=0.6)+def suggested_field_fix(node: ast.Field, suggestion: str) -> Optional[str]:+ """Replacement text for the range `node` marks, or None when no edit is safe to offer.++ Three conditions have to hold. The node needs a span, because a notice without one marks the+ whole query and applying the fix would overwrite it. The chain has to be a single name, because+ the span covers the whole chain while the suggestion only stands in for its head, and a head+ that is really a table alias draws its suggestions from field names, so the edit would be+ confidently wrong. And the name has to survive escaping, which rejects a few.+ """+ if node.start is None or node.end is None:+ return None+ if len(node.chain) != 1:+ return None+ try:+ return escape_hogql_identifier(suggestion)+ except QueryError:+ return None++def lookup_table_by_name(scope: ast.SelectQueryType, ctes: dict[str, ast.CTE], node: ast.Field) -> Optional[ast.TableOrSelectType]:diff --git a/posthog/hogql/test/test_metadata.py b/posthog/hogql/test/test_metadata.pyindex 774f422b5057..fde5cb52177e 100644--- a/posthog/hogql/test/test_metadata.py+++ b/posthog/hogql/test/test_metadata.py@@ -7,6 +7,8 @@ from django.conf import settingsfrom django.db import DatabaseErrorfrom django.test import override_settings+from parameterized import parameterized+from posthog.schema import (HogLanguage,HogQLMetadata,@@ -182,6 +184,34 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):},)+ @parameterized.expand(+ [+ ("SELECT tiemstamp FROM events", "tiemstamp", "timestamp"),+ ("SELECT distnct_id FROM events", "distnct_id", "distinct_id"),+ ]+ )+ def test_metadata_offers_a_quick_fix_for_a_misspelled_field(self, query: str, misspelling: str, expected_fix: str):+ metadata = self._select(query)++ self.assertFalse(metadata.isValid)+ self.assertEqual(len(metadata.errors), 1)+ error = metadata.errors[0]+ self.assertIn(f"Did you mean: {expected_fix}", error.message)+ self.assertEqual(error.fix, expected_fix)+ # The editor substitutes `fix` for the marked range, so the range has to cover the+ # misspelling and nothing else. A span of None marks the whole query.+ self.assertEqual(query[error.start : error.end], misspelling)++ def test_metadata_offers_no_quick_fix_when_the_misspelling_heads_a_chain(self):+ metadata = self._select("SELECT evnt.foo FROM events")++ self.assertFalse(metadata.isValid)+ self.assertEqual(len(metadata.errors), 1)+ # Asserting the suggestion is present keeps this pinned on the chain rule: the marked range+ # covers `evnt.foo`, so substituting `event` for it would drop the rest of the chain.+ self.assertIn("Did you mean: event", metadata.errors[0].message)+ self.assertIsNone(metadata.errors[0].fix)+def test_metadata_warns_for_unknown_event_literal(self):EventDefinition.objects.create(team=self.team, name="paid_bill")