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(data-warehouse): introduce DirectSQLTable base and printer class registry (#64684)

Daniel RCaa37eccca0c5
diff --git a/posthog/hogql/constants.py b/posthog/hogql/constants.py
index f8ba13267dfb..8cd8907685e9 100644
--- a/posthog/hogql/constants.py
+++ b/posthog/hogql/constants.py
@@ -50,6 +50,11 @@ BREAKDOWN_VALUE_MAX_LENGTH = 400
type HogQLDialect = Literal["hogql", "clickhouse", "postgres", "duckdb", "mysql"]
+# All dialects that compile to an external SQL database queried directly (as opposed to
+# ClickHouse / HogQL). MySQL shares the standard-SQL keyword surface (CURRENT_DATE & co.)
+# but not Postgres-specific features like PIVOT/UNPIVOT, TRY_CAST, or positional references.
+SQL_TARGET_DIALECTS: frozenset[HogQLDialect] = frozenset({"postgres", "duckdb", "mysql"})
+
type HogQLParserBackend = Literal["python", "cpp-json", "rust-json", "rust-py"]
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 76afdde78e6c..dd14f1451ee7 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -20,8 +20,7 @@ from pydantic import BaseModel, ConfigDict
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
-from posthog.hogql.database.direct_mysql_table import DirectMySQLTable
-from posthog.hogql.database.direct_postgres_table import DirectPostgresTable
+from posthog.hogql.database.direct_sql_table import DirectSQLTable
from posthog.hogql.database.lazy_join_tags import (
DATA_WAREHOUSE,
DATA_WAREHOUSE_EXPERIMENTS,
@@ -635,9 +634,7 @@ class Database(BaseModel):
@staticmethod
def _is_helper_function_table(table: object) -> bool:
- return isinstance(table, FunctionCallTable) and not isinstance(
- table, (DirectPostgresTable, DirectMySQLTable, PostgresTable, S3Table)
- )
+ return isinstance(table, FunctionCallTable) and not isinstance(table, (DirectSQLTable, PostgresTable, S3Table))
def _remove_lazy_joins_to_disallowed_tables(self, allowed_table_names: set[str]) -> None:
def should_keep_join(field: LazyJoin) -> bool:
diff --git a/posthog/hogql/database/direct_mysql_table.py b/posthog/hogql/database/direct_mysql_table.py
index 3a703a4bdbd7..3ce8e87b4a62 100644
--- a/posthog/hogql/database/direct_mysql_table.py
+++ b/posthog/hogql/database/direct_mysql_table.py
@@ -1,19 +1,13 @@
-from posthog.hogql.database.models import FunctionCallTable
+from posthog.hogql.database.direct_sql_table import DirectSQLTable
from posthog.hogql.errors import QueryError
-from posthog.hogql.escape_sql import escape_hogql_identifier, escape_mysql_identifier
+from posthog.hogql.escape_sql import escape_mysql_identifier
-class DirectMySQLTable(FunctionCallTable):
- requires_args: bool = False
+class DirectMySQLTable(DirectSQLTable):
# In MySQL a "schema" and a "database" are the same namespace; this holds the
# database the table lives in.
mysql_schema: str
mysql_table_name: str
- external_data_source_id: str
- connection_metadata: dict[str, object] | None = None
-
- def to_printed_hogql(self) -> str:
- return escape_hogql_identifier(self.name)
def to_printed_mysql(self, context) -> str:
if not self.mysql_schema.strip():
diff --git a/posthog/hogql/database/direct_postgres_table.py b/posthog/hogql/database/direct_postgres_table.py
index 3567853426b6..9222d301a54a 100644
--- a/posthog/hogql/database/direct_postgres_table.py
+++ b/posthog/hogql/database/direct_postgres_table.py
@@ -1,18 +1,12 @@
-from posthog.hogql.database.models import FunctionCallTable
+from posthog.hogql.database.direct_sql_table import DirectSQLTable
from posthog.hogql.errors import QueryError
-from posthog.hogql.escape_sql import escape_hogql_identifier, escape_postgres_identifier
+from posthog.hogql.escape_sql import escape_postgres_identifier
-class DirectPostgresTable(FunctionCallTable):
- requires_args: bool = False
+class DirectPostgresTable(DirectSQLTable):
postgres_catalog: str | None = None
postgres_schema: str
postgres_table_name: str
- external_data_source_id: str
- connection_metadata: dict[str, object] | None = None
-
- def to_printed_hogql(self) -> str:
- return escape_hogql_identifier(self.name)
def to_printed_postgres(self, context) -> str:
parts = []
diff --git a/posthog/hogql/database/direct_sql_table.py b/posthog/hogql/database/direct_sql_table.py
new file mode 100644
index 000000000000..f3987dea1868
--- /dev/null
+++ b/posthog/hogql/database/direct_sql_table.py
@@ -0,0 +1,15 @@
+from posthog.hogql.database.models import FunctionCallTable
+from posthog.hogql.escape_sql import escape_hogql_identifier
+
+
+class DirectSQLTable(FunctionCallTable):
+ """Shared base for tables that print into an external SQL database queried directly
+ (Postgres, MySQL, ...). Holds the members common to every engine; subclasses add the
+ engine-specific schema/table fields and ``to_printed_<dialect>`` rendering."""
+
+ requires_args: bool = False
+ external_data_source_id: str
+ connection_metadata: dict[str, object] | None = None
+
+ def to_printed_hogql(self) -> str:
+ return escape_hogql_identifier(self.name)
diff --git a/posthog/hogql/database/postgres_utils.py b/posthog/hogql/database/postgres_utils.py
index 3941a0886f74..75471cc42fb4 100644
--- a/posthog/hogql/database/postgres_utils.py
+++ b/posthog/hogql/database/postgres_utils.py
@@ -2,8 +2,7 @@ import dataclasses
from collections.abc import Sequence
from typing import Any, Protocol
-from posthog.hogql.database.direct_mysql_table import DirectMySQLTable
-from posthog.hogql.database.direct_postgres_table import DirectPostgresTable
+from posthog.hogql.database.direct_sql_table import DirectSQLTable
from posthog.hogql.database.lazy_join_tags import FOREIGN_KEY
from posthog.hogql.database.models import LazyJoin, Table
from posthog.hogql.database.utils import get_join_field_chain
@@ -218,9 +217,9 @@ def _is_same_external_scope(
source = warehouse_table.external_data_source
if source is not None and source.access_method == ExternalDataSource.AccessMethod.DIRECT:
- return isinstance(
- target_hogql_table, (DirectPostgresTable, DirectMySQLTable)
- ) and target_hogql_table.external_data_source_id == str(source.id)
+ return isinstance(target_hogql_table, DirectSQLTable) and target_hogql_table.external_data_source_id == str(
+ source.id
+ )
if "." not in source_table_name or "." not in target_table_name:
return False
diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.py
index 838efcdc9a54..8641a0ba1fed 100644
--- a/posthog/hogql/printer/utils.py
+++ b/posthog/hogql/printer/utils.py
@@ -7,7 +7,7 @@ if TYPE_CHECKING:
from posthog.hogql import ast
from posthog.hogql.base import _T_AST
-from posthog.hogql.constants import HogQLDialect, HogQLGlobalSettings
+from posthog.hogql.constants import SQL_TARGET_DIALECTS, HogQLDialect, HogQLGlobalSettings
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
from posthog.hogql.errors import InternalHogQLError
@@ -45,6 +45,14 @@ from posthog.models.team import Team
from products.access_control.backend.property_access_control import get_restricted_properties_for_team
+PRINTER_CLASSES: dict[HogQLDialect, type[BasePrinter]] = {
+ "clickhouse": ClickHousePrinter,
+ "postgres": PostgresPrinter,
+ "duckdb": DuckDBPrinter,
+ "mysql": MySQLPrinter,
+ "hogql": HogQLPrinter,
+}
+
def to_printed_hogql(query: ast.Expr, team: Team, modifiers: "HogQLQueryModifiers | None" = None) -> str:
"""Prints the HogQL query without mutating the node"""
@@ -165,7 +173,7 @@ def prepare_ast_for_printing(
with context.timings.measure("projection_pushdown"):
node = pushdown_projections(node, context)
- if dialect in ("postgres", "duckdb", "mysql"):
+ if dialect in SQL_TARGET_DIALECTS:
with context.timings.measure("resolve_lazy_tables"):
resolve_lazy_tables(node, dialect, stack, context, resolver_factory=resolver_factory)
@@ -272,46 +280,17 @@ def print_prepared_ast(
pretty: bool = False,
) -> str:
with context.timings.measure("printer"):
- printer: BasePrinter
printer_stack = cast(list[ast.AST], stack or [])
- match dialect:
- case "clickhouse":
- printer = ClickHousePrinter(
- context=context,
- stack=printer_stack,
- settings=settings,
- pretty=pretty,
- )
- case "postgres":
- printer = PostgresPrinter(
- context=context,
- stack=printer_stack,
- settings=settings,
- pretty=pretty,
- )
- case "duckdb":
- printer = DuckDBPrinter(
- context=context,
- stack=printer_stack,
- settings=settings,
- pretty=pretty,
- )
- case "mysql":
- printer = MySQLPrinter(
- context=context,
- stack=printer_stack,
- settings=settings,
- pretty=pretty,
- )
- case "hogql":
- printer = HogQLPrinter(
- context=context,
- stack=printer_stack,
- settings=settings,
- pretty=pretty,
- )
- case _:
- raise InternalHogQLError(f"Invalid SQL dialect: {dialect}")
+ printer_class = PRINTER_CLASSES.get(dialect)
+ if printer_class is None:
+ raise InternalHogQLError(f"Invalid SQL dialect: {dialect}")
+
+ printer = printer_class(
+ context=context,
+ stack=printer_stack,
+ settings=settings,
+ pretty=pretty,
+ )
return printer.visit(node)
diff --git a/posthog/hogql/query.py b/posthog/hogql/query.py
index ad259062280b..80d0625324fc 100644
--- a/posthog/hogql/query.py
+++ b/posthog/hogql/query.py
@@ -29,8 +29,7 @@ from posthog.hogql.constants import (
get_default_limit_for_context,
)
from posthog.hogql.database.database import Database
-from posthog.hogql.database.direct_mysql_table import DirectMySQLTable
-from posthog.hogql.database.direct_postgres_table import DirectPostgresTable
+from posthog.hogql.database.direct_sql_table import DirectSQLTable
from posthog.hogql.database.schema.duckdb_table_functions import (
GenerateSeriesTable,
OpaqueFunctionCallTable,
@@ -43,7 +42,7 @@ from posthog.hogql.direct_connection import (
validate_direct_mysql_source_config,
validate_direct_postgres_source_config,
)
-from posthog.hogql.errors import ExposedHogQLError, QueryError, ResolutionError
+from posthog.hogql.errors import ExposedHogQLError, InternalHogQLError, QueryError, ResolutionError
from posthog.hogql.escape_sql import escape_postgres_identifier
from posthog.hogql.feature_extractor import extract_hogql_features
from posthog.hogql.filters import replace_filters
@@ -387,7 +386,7 @@ class HogQLQueryExecutor:
class _PreparedExecution:
sql: str
context: HogQLContext
- engine: Literal["clickhouse", "direct_postgres", "direct_mysql"]
+ engine: Literal["clickhouse", "direct_sql"]
@tracer.start_as_current_span("HogQLQueryExecutor.__post_init__")
def __post_init__(self):
@@ -612,7 +611,7 @@ class HogQLQueryExecutor:
direct_source_ids = {
table_type.table.external_data_source_id
for table_type in base_table_types
- if isinstance(table_type.table, (DirectPostgresTable, DirectMySQLTable))
+ if isinstance(table_type.table, DirectSQLTable)
}
direct_source_id: str | None = None
@@ -629,9 +628,7 @@ class HogQLQueryExecutor:
if len(direct_source_ids) > 1:
raise ExposedHogQLError("Direct queries can only reference a single source.")
- has_non_direct_tables = any(
- not isinstance(table_type.table, (DirectPostgresTable, DirectMySQLTable)) for table_type in base_table_types
- )
+ has_non_direct_tables = any(not isinstance(table_type.table, DirectSQLTable) for table_type in base_table_types)
if has_non_direct_tables:
if self.connection_id is None:
return None
@@ -648,7 +645,6 @@ class HogQLQueryExecutor:
source = getattr(self, "_direct_source", None)
dialect: Literal["postgres", "mysql"] = "mysql" if source is not None and source.is_direct_mysql else "postgres"
- engine: Literal["direct_postgres", "direct_mysql"] = "direct_mysql" if dialect == "mysql" else "direct_postgres"
direct_context = dataclasses.replace(
self.context,
@@ -683,7 +679,7 @@ class HogQLQueryExecutor:
return self._PreparedExecution(
sql=self.direct_sql,
context=direct_context,
- engine=engine,
+ engine="direct_sql",
)
def _get_select_query_type(self) -> ast.SelectQueryType | ast.SelectSetQueryType | None:
@@ -1070,10 +1066,13 @@ class HogQLQueryExecutor:
else:
prepared_execution = self._prepare_execution()
- if prepared_execution.engine == "direct_postgres":
- self._execute_direct_postgres_query()
- elif prepared_execution.engine == "direct_mysql":
- self._execute_direct_mysql_query()
+ if prepared_execution.engine == "direct_sql":
+ if self.direct_dialect == "mysql":
+ self._execute_direct_mysql_query()
+ elif self.direct_dialect == "postgres":
+ self._execute_direct_postgres_query()
+ else:
+ raise InternalHogQLError(f"Unsupported direct SQL dialect: {self.direct_dialect}")
elif self.clickhouse_sql is not None:
if self.clickhouse_sql == "":
self.results = []
diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.py
index 25ca3ac0125d..fd5c7c8289f8 100644
--- a/posthog/hogql/resolver.py
+++ b/posthog/hogql/resolver.py
@@ -8,7 +8,7 @@ import re2
from posthog.hogql import ast
from posthog.hogql.ast import ConstantType, FieldTraverserType
from posthog.hogql.base import _T_AST
-from posthog.hogql.constants import HogQLDialect
+from posthog.hogql.constants import SQL_TARGET_DIALECTS, HogQLDialect
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
from posthog.hogql.database.models import FunctionCallTable, LazyTable, SavedQuery, StringJSONDatabaseField
@@ -115,11 +115,6 @@ assert POSTGRES_KEYWORD_TYPES.keys() == ast.VALID_KEYWORD_NAMES, (
# takes the PG code path in the resolver.
_POSTGRES_FAMILY: frozenset[HogQLDialect] = frozenset({"postgres", "duckdb"})
-# All dialects that compile to an external SQL database queried directly (as opposed to
-# ClickHouse / HogQL). MySQL shares the standard-SQL keyword surface (CURRENT_DATE & co.)
-# but not Postgres-specific features like PIVOT/UNPIVOT, TRY_CAST, or positional references.
-_DIRECT_SQL_FAMILY: frozenset[HogQLDialect] = frozenset({"postgres", "duckdb", "mysql"})
-
def resolve_constant_data_type(constant: Any) -> ConstantType:
if constant is None:
@@ -1878,7 +1873,7 @@ class Resolver(CloningVisitor):
scope = self._get_scope()
name = str(node.chain[0])
- if self.dialect in _DIRECT_SQL_FAMILY and len(node.chain) == 1:
+ if self.dialect in SQL_TARGET_DIALECTS and len(node.chain) == 1:
keyword = name.lower()
if keyword in POSTGRES_KEYWORD_TYPES and name not in scope.columns and name not in scope.aliases:
keyword_type = POSTGRES_KEYWORD_TYPES[keyword]
@@ -1921,7 +1916,7 @@ class Resolver(CloningVisitor):
if (
not type
and len(node.chain) == 1
- and self.dialect in _DIRECT_SQL_FAMILY
+ and self.dialect in SQL_TARGET_DIALECTS
and name.lower() in POSTGRES_KEYWORD_TYPES
and name in scope.columns
):