: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
chore(data-warehouse): add direct SQL adapter registry and port postgres and mysql onto it (#64945)
Daniel RC070a72af5af1
diff --git a/posthog/hogql/direct_connection.py b/posthog/hogql/direct_connection.pyindex 97dfbe559be2..4ef170392fb5 100644--- a/posthog/hogql/direct_connection.py+++ b/posthog/hogql/direct_connection.py@@ -1,11 +1,10 @@from collections.abc import Callable-from typing import TYPE_CHECKING, Optional, cast+from typing import TYPE_CHECKING, Optionalfrom uuid import UUIDfrom posthog.schema import HogQLQueryModifiersfrom posthog.hogql.database.database import Database-from posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.timings import HogQLTimingsfrom posthog.rbac.user_access_control import UserAccessControl@@ -14,9 +13,6 @@ from products.warehouse_sources.backend.models.external_data_source import Exterif TYPE_CHECKING:from posthog.models import Team, User- from posthog.temporal.data_imports.sources.generated_configs import MySQLSourceConfig, PostgresSourceConfig- from posthog.temporal.data_imports.sources.mysql.mysql import MySQLImplementation- from posthog.temporal.data_imports.sources.postgres.source import PostgresSourceINVALID_CONNECTION_ID_ERROR = (@@ -87,57 +83,3 @@ def resolve_database_for_connection(connection_id=str(source.id) if source else None,)return source, database---def validate_direct_postgres_source_config(- source: ExternalDataSource, team: "Team"-) -> tuple["PostgresSource", "PostgresSourceConfig"]:- from posthog.temporal.data_imports.sources import SourceRegistry- from posthog.temporal.data_imports.sources.postgres.source import PostgresSource-- from products.data_warehouse.backend.types import ExternalDataSourceType-- if not source.is_direct_postgres:- raise ExposedHogQLError("Invalid direct Postgres connection.")-- postgres_source = cast(PostgresSource, SourceRegistry.get_source(ExternalDataSourceType.POSTGRES))- config = postgres_source.parse_config(source.job_inputs or {})-- is_ssh_valid, ssh_valid_errors = postgres_source.ssh_tunnel_is_valid(config, team.pk)- if not is_ssh_valid:- raise ExposedHogQLError(ssh_valid_errors or "Invalid SSH tunnel configuration.")-- valid_host, host_errors = postgres_source.is_database_host_valid(- config.host, team.pk, using_ssh_tunnel=config.ssh_tunnel.enabled if config.ssh_tunnel else False- )- if not valid_host:- raise ExposedHogQLError(host_errors or "Invalid Postgres host.")-- return postgres_source, config---def validate_direct_mysql_source_config(- source: ExternalDataSource, team: "Team"-) -> tuple["MySQLImplementation", "MySQLSourceConfig"]:- from posthog.temporal.data_imports.sources import SourceRegistry- from posthog.temporal.data_imports.sources.mysql.source import MySQLSource-- from products.data_warehouse.backend.types import ExternalDataSourceType-- if not source.is_direct_mysql:- raise ExposedHogQLError("Invalid direct MySQL connection.")-- mysql_source = cast(MySQLSource, SourceRegistry.get_source(ExternalDataSourceType.MYSQL))- config = mysql_source.parse_config(source.job_inputs or {})-- is_ssh_valid, ssh_valid_errors = mysql_source.ssh_tunnel_is_valid(config, team.pk)- if not is_ssh_valid:- raise ExposedHogQLError(ssh_valid_errors or "Invalid SSH tunnel configuration.")-- valid_host, host_errors = mysql_source.is_database_host_valid(- config.host, team.pk, using_ssh_tunnel=config.ssh_tunnel.enabled if config.ssh_tunnel else False- )- if not valid_host:- raise ExposedHogQLError(host_errors or "Invalid MySQL host.")-- return mysql_source.get_implementation, configdiff --git a/posthog/hogql/direct_sql/__init__.py b/posthog/hogql/direct_sql/__init__.pynew file mode 100644index 000000000000..cc75836c09d2--- /dev/null+++ b/posthog/hogql/direct_sql/__init__.py@@ -0,0 +1,23 @@+from posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult, DirectSQLAdapter+from posthog.hogql.direct_sql.capability import direct_capable_source_types, is_direct_capable+from posthog.hogql.direct_sql.mysql_adapter import MySQLAdapter+from posthog.hogql.direct_sql.postgres_adapter import PostgresAdapter+from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement+from posthog.hogql.direct_sql.registry import get_adapter, register_adapter, registered_engines++register_adapter(PostgresAdapter())+register_adapter(MySQLAdapter())++__all__ = [+ "DirectQueryRequest",+ "DirectQueryResult",+ "DirectSQLAdapter",+ "PostgresAdapter",+ "MySQLAdapter",+ "direct_capable_source_types",+ "is_direct_capable",+ "ensure_single_direct_statement",+ "get_adapter",+ "register_adapter",+ "registered_engines",+]diff --git a/posthog/hogql/direct_sql/adapter.py b/posthog/hogql/direct_sql/adapter.pynew file mode 100644index 000000000000..d3c78e9ad8d8--- /dev/null+++ b/posthog/hogql/direct_sql/adapter.py@@ -0,0 +1,54 @@+import dataclasses+from typing import TYPE_CHECKING, Any, Protocol++from posthog.hogql.constants import HogQLDialect, HogQLGlobalSettings+from posthog.hogql.timings import HogQLTimings++if TYPE_CHECKING:+ from posthog.models.team import Team++ from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+++class DirectQueryRequest:+ source: "ExternalDataSource"+ team: "Team"+ sql: str+ values: dict[str, object] | None+ settings: HogQLGlobalSettings+ timings: HogQLTimings+ query_type: str+ debug: bool+++class DirectQueryResult:+ results: list+ types: list[tuple[str, str]]+ print_columns: list[str]+ error: str | None = None+++class DirectSQLAdapter(Protocol):+ """Contract every direct-query engine implements. The registry keys adapters by ``engine``.++ ``dialect`` is the HogQL printer dialect the engine compiles to, or ``None`` for raw-only+ engines (no printer — only ``sendRawQuery`` works). Phase 1 engines (Postgres, MySQL) both+ have a dialect; raw-only engines arrive in Phase 2.+ """++ engine: str+ dialect: HogQLDialect | None++ def validate_source_config(self, source: "ExternalDataSource", team: "Team") -> tuple[Any, Any]:+ """Validate the source is queryable (host/SSRF + SSH tunnel) and return (implementation, config)."""+ ...++ def prepare_raw_sql(self, sql: str) -> str:+ """Apply the engine's read-only / single-statement guard to user-supplied raw SQL."""+ ...++ def execute(self, request: DirectQueryRequest) -> DirectQueryResult:+ """Connect, enforce read-only + timeout, run the SQL, and map results/types back."""+ ...diff --git a/posthog/hogql/direct_sql/capability.py b/posthog/hogql/direct_sql/capability.pynew file mode 100644index 000000000000..367280047ff4--- /dev/null+++ b/posthog/hogql/direct_sql/capability.py@@ -0,0 +1,20 @@+from products.data_warehouse.backend.types import DIRECT_ENGINE_BY_SOURCE_TYPE+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+++def direct_capable_source_types() -> frozenset[str]:+ """Source types that map to a direct-SQL engine (the static capability surface)."""+ return frozenset(DIRECT_ENGINE_BY_SOURCE_TYPE.keys())+++def is_direct_capable(source: ExternalDataSource) -> bool:+ """Whether this source can be queried live via a direct connection.++ Pure-direct sources are always capable. Synced (warehouse) sources are capable only when+ the per-source toggle is on. Either way the source type must map to a known engine.+ """+ if source.direct_engine is None:+ return False+ if source.access_method == ExternalDataSource.AccessMethod.DIRECT:+ return True+ return source.direct_query_enableddiff --git a/posthog/hogql/direct_sql/mysql_adapter.py b/posthog/hogql/direct_sql/mysql_adapter.pynew file mode 100644index 000000000000..ab9bae4df91f--- /dev/null+++ b/posthog/hogql/direct_sql/mysql_adapter.py@@ -0,0 +1,188 @@+from typing import TYPE_CHECKING, cast++import pymysql+import sqlparse+from opentelemetry import trace+from pymysql.constants import FIELD_TYPE as MYSQL_FIELD_TYPE+from sqlparse import tokens as sqlparse_tokens+from sqlparse.sql import Statement++from posthog.hogql.constants import HogQLDialect+from posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult+from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement+from posthog.hogql.errors import ExposedHogQLError++if TYPE_CHECKING:+ from posthog.models.team import Team+ from posthog.temporal.data_imports.sources.generated_configs import MySQLSourceConfig+ from posthog.temporal.data_imports.sources.mysql.mysql import MySQLImplementation++ from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource++DIRECT_MYSQL_DEFAULT_STATEMENT_TIMEOUT_SECONDS = 600+RAW_MYSQL_READ_ONLY_ERROR = "Raw MySQL queries must be read-only SELECT statements."++MYSQL_FIELD_TYPE_TO_CLICKHOUSE_TYPE: dict[int, str] = {+ MYSQL_FIELD_TYPE.TINY: "Int8",+ MYSQL_FIELD_TYPE.SHORT: "Int16",+ MYSQL_FIELD_TYPE.INT24: "Int32",+ MYSQL_FIELD_TYPE.LONG: "Int32",+ MYSQL_FIELD_TYPE.LONGLONG: "Int64",+ MYSQL_FIELD_TYPE.YEAR: "Int32",+ MYSQL_FIELD_TYPE.FLOAT: "Float32",+ MYSQL_FIELD_TYPE.DOUBLE: "Float64",+ MYSQL_FIELD_TYPE.DECIMAL: "Decimal",+ MYSQL_FIELD_TYPE.NEWDECIMAL: "Decimal",+ MYSQL_FIELD_TYPE.DATE: "Date",+ MYSQL_FIELD_TYPE.NEWDATE: "Date",+ MYSQL_FIELD_TYPE.DATETIME: "DateTime",+ MYSQL_FIELD_TYPE.TIMESTAMP: "DateTime",+ MYSQL_FIELD_TYPE.TIME: "String",+ MYSQL_FIELD_TYPE.BIT: "String",+ MYSQL_FIELD_TYPE.JSON: "String",+ MYSQL_FIELD_TYPE.ENUM: "String",+ MYSQL_FIELD_TYPE.SET: "String",+ MYSQL_FIELD_TYPE.TINY_BLOB: "String",+ MYSQL_FIELD_TYPE.MEDIUM_BLOB: "String",+ MYSQL_FIELD_TYPE.LONG_BLOB: "String",+ MYSQL_FIELD_TYPE.BLOB: "String",+ MYSQL_FIELD_TYPE.VAR_STRING: "String",+ MYSQL_FIELD_TYPE.VARCHAR: "String",+ MYSQL_FIELD_TYPE.STRING: "String",+ MYSQL_FIELD_TYPE.GEOMETRY: "String",+}+++def mysql_field_type_to_clickhouse_type(type_code: int | None) -> str:+ if type_code is None:+ return "String"+ return MYSQL_FIELD_TYPE_TO_CLICKHOUSE_TYPE.get(type_code, "String")+++def mysql_error_to_message(error: Exception) -> str:+ if isinstance(error, pymysql.MySQLError):+ args = error.args+ if len(args) >= 2 and isinstance(args[1], str) and args[1].strip():+ return args[1].strip().splitlines()[0]++ message = str(error).strip()+ if not message:+ return "MySQL query failed."+ return message.splitlines()[0]+++def _is_executable_mysql_comment(value: str) -> bool:+ normalized = value.lstrip().upper()+ return normalized.startswith("/*!") or normalized.startswith("/*M!")+++def _raw_mysql_token_values(statement: Statement) -> list[str]:+ token_values: list[str] = []+ for token in statement.flatten():+ if token.ttype in sqlparse_tokens.Comment:+ if _is_executable_mysql_comment(token.value):+ raise ExposedHogQLError(RAW_MYSQL_READ_ONLY_ERROR)+ continue+ if token.is_whitespace or token.ttype in sqlparse_tokens.Literal.String:+ continue+ value = token.value.strip().upper()+ if value:+ token_values.append(value)+ return token_values+++def ensure_read_only_raw_mysql_statement(sql: str) -> str:+ sql = ensure_single_direct_statement(sql)+ statements = [statement for statement in sqlparse.parse(sql) if str(statement).strip(" \t\r\n;")]+ if len(statements) != 1 or statements[0].get_type() != "SELECT":+ raise ExposedHogQLError(RAW_MYSQL_READ_ONLY_ERROR)++ token_values = _raw_mysql_token_values(statements[0])+ for index, value in enumerate(token_values):+ normalized_value = value.strip("`")+ if value == "INTO":+ raise ExposedHogQLError(RAW_MYSQL_READ_ONLY_ERROR)+ if normalized_value == "LOAD_FILE" and index + 1 < len(token_values) and token_values[index + 1] == "(":+ raise ExposedHogQLError(RAW_MYSQL_READ_ONLY_ERROR)+ if value == "FOR" and index + 1 < len(token_values) and token_values[index + 1] in {"UPDATE", "SHARE"}:+ raise ExposedHogQLError(RAW_MYSQL_READ_ONLY_ERROR)+ if token_values[index : index + 4] == ["LOCK", "IN", "SHARE", "MODE"]:+ raise ExposedHogQLError(RAW_MYSQL_READ_ONLY_ERROR)++ return sql+++class MySQLAdapter:+ engine = "mysql"+ dialect: HogQLDialect | None = "mysql"++ def validate_source_config(+ self, source: "ExternalDataSource", team: "Team"+ ) -> tuple["MySQLImplementation", "MySQLSourceConfig"]:+ from posthog.temporal.data_imports.sources import SourceRegistry+ from posthog.temporal.data_imports.sources.mysql.source import MySQLSource++ from products.data_warehouse.backend.types import ExternalDataSourceType++ if not source.is_direct_mysql:+ raise ExposedHogQLError("Invalid direct MySQL connection.")++ mysql_source = cast(MySQLSource, SourceRegistry.get_source(ExternalDataSourceType.MYSQL))+ config = mysql_source.parse_config(source.job_inputs or {})++ is_ssh_valid, ssh_valid_errors = mysql_source.ssh_tunnel_is_valid(config, team.pk)+ if not is_ssh_valid:+ raise ExposedHogQLError(ssh_valid_errors or "Invalid SSH tunnel configuration.")++ valid_host, host_errors = mysql_source.is_database_host_valid(+ config.host, team.pk, using_ssh_tunnel=config.ssh_tunnel.enabled if config.ssh_tunnel else False+ )+ if not valid_host:+ raise ExposedHogQLError(host_errors or "Invalid MySQL host.")++ return mysql_source.get_implementation, config++ def prepare_raw_sql(self, sql: str) -> str:+ return ensure_read_only_raw_mysql_statement(sql)++ def execute(self, request: DirectQueryRequest) -> DirectQueryResult:+ source = request.source+ mysql_implementation, source_config = self.validate_source_config(source, request.team)+ settings = request.settings+ statement_timeout_seconds = max(+ settings.max_execution_time or DIRECT_MYSQL_DEFAULT_STATEMENT_TIMEOUT_SECONDS, 1+ )++ span = trace.get_current_span()+ span.set_attribute("team_id", request.team.pk)+ span.set_attribute("query_type", request.query_type)+ span.set_attribute("source_id", str(source.id))++ try:+ with request.timings.measure("mysql_execute"):+ with mysql_implementation.connect(source_config, read_timeout=statement_timeout_seconds) as connection:+ with connection.cursor() as cursor:+ try:+ # MySQL 8 only and SELECT-only; MariaDB uses a different variable.+ # The read_timeout above is the backstop if this is unavailable.+ cursor.execute(f"SET SESSION MAX_EXECUTION_TIME = {statement_timeout_seconds * 1000}")+ except pymysql.MySQLError:+ pass+ cursor.execute("START TRANSACTION READ ONLY")+ cursor.execute( # nosemgrep: python.django.security.injection.sql.sql-injection-using-db-cursor-execute.sql-injection-db-cursor-execute+ request.sql, request.values or None+ )+ results = cursor.fetchall()+ description = cursor.description or []+ except (pymysql.MySQLError, ExposedHogQLError) as error:+ span.set_attribute("error_type", error.__class__.__name__)+ if request.debug:+ return DirectQueryResult(results=[], types=[], print_columns=[], error=mysql_error_to_message(error))+ raise ExposedHogQLError(mysql_error_to_message(error)) from error++ span.set_attribute("row_count", len(results))+ types: list[tuple[str, str]] = [+ (column[0], mysql_field_type_to_clickhouse_type(column[1])) for column in description+ ]+ print_columns = [column[0] for column in description]+ return DirectQueryResult(results=list(results), types=types, print_columns=print_columns)diff --git a/posthog/hogql/direct_sql/postgres_adapter.py b/posthog/hogql/direct_sql/postgres_adapter.pynew file mode 100644index 000000000000..5cd8f514371b--- /dev/null+++ b/posthog/hogql/direct_sql/postgres_adapter.py@@ -0,0 +1,301 @@+from datetime import date, datetime+from typing import TYPE_CHECKING, TypedDict, cast++import psycopg+from opentelemetry import trace+from psycopg.types.datetime import DateLoader++from posthog.hogql.constants import HogQLDialect+from posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult+from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement+from posthog.hogql.errors import ExposedHogQLError+from posthog.hogql.escape_sql import escape_postgres_identifier++if TYPE_CHECKING:+ from posthog.models.team import Team+ from posthog.temporal.data_imports.sources.generated_configs import PostgresSourceConfig+ from posthog.temporal.data_imports.sources.postgres.source import PostgresSource++ from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource++DIRECT_POSTGRES_CONNECT_TIMEOUT_SECONDS = 15+DIRECT_POSTGRES_DEFAULT_STATEMENT_TIMEOUT_SECONDS = 600++POSTGRES_OID_TO_CLICKHOUSE_TYPE: dict[int, str] = {+ 16: "Bool",+ 20: "Int64",+ 21: "Int16",+ 23: "Int32",+ 26: "UInt32",+ 700: "Float32",+ 701: "Float64",+ 1082: "Date",+ 1114: "DateTime",+ 1184: "DateTime64(6, 'UTC')",+ 1700: "Decimal",+ 17: "String",+ 19: "String",+ 25: "String",+ 1042: "String",+ 1043: "String",+ 114: "String",+ 3802: "String",+ 2950: "UUID",+ 1083: "String",+ 1266: "String",+ 1186: "String",+ 1000: "Array(Bool)",+ 1005: "Array(Int16)",+ 1007: "Array(Int32)",+ 1016: "Array(Int64)",+ 1021: "Array(Float32)",+ 1022: "Array(Float64)",+ 1115: "Array(DateTime)",+ 1185: "Array(DateTime64(6, 'UTC'))",+ 1182: "Array(Date)",+ 1231: "Array(Decimal)",+ 1009: "Array(String)",+ 1015: "Array(String)",+ 2951: "Array(UUID)",+}+++class PostgresConnectionKwargs(TypedDict, total=False):+ host: str+ port: int+ dbname: str+ user: str+ password: str+ connect_timeout: int+ sslmode: str+ options: str+ sslcert: str+ sslkey: str+ sslrootcert: str+++def postgres_oid_to_clickhouse_type(oid: int | None) -> str:+ if oid is None:+ return "String"++ return POSTGRES_OID_TO_CLICKHOUSE_TYPE.get(oid, "String")+++def postgres_error_to_message(error: Exception) -> str:+ if isinstance(error, psycopg.Error):+ diag = getattr(error, "diag", None)+ message_primary = getattr(diag, "message_primary", None) if diag else None+ message_detail = getattr(diag, "message_detail", None) if diag else None+ if message_primary and message_detail:+ return f"{message_primary} {message_detail}"+ if message_primary:+ return message_primary++ message = str(error).strip()+ if not message:+ return "Postgres query failed."+ return message.splitlines()[0]+++def direct_postgres_session_setup_sql(+ schema: str | None,+ connection_metadata: dict[str, object] | None = None,+ host: str | None = None,+) -> str | None:+ engine = connection_metadata.get("engine") if isinstance(connection_metadata, dict) else None+ database = connection_metadata.get("database") if isinstance(connection_metadata, dict) else None+ normalized_schema = schema.strip() if isinstance(schema, str) and schema.strip() else None++ if engine == "duckdb" or (host is not None and host.endswith(".postwh.com")):+ if normalized_schema:+ quoted_schema = escape_postgres_identifier(normalized_schema)+ return f"USE {quoted_schema}"+ if isinstance(database, str) and database.strip():+ quoted_database = escape_postgres_identifier(database.strip())+ return f"USE {quoted_database}"+ return None++ if not normalized_schema:+ return None++ quoted_schema = escape_postgres_identifier(normalized_schema)+ return f"SET search_path TO {quoted_schema}"+++def parse_lenient_direct_postgres_date(value: str) -> date:+ trimmed = value.strip()++ try:+ return date.fromisoformat(trimmed)+ except ValueError:+ pass++ normalized = trimmed[:-1] + "+00:00" if trimmed.endswith("Z") else trimmed+ try:+ return datetime.fromisoformat(normalized).date()+ except ValueError:+ pass++ if len(trimmed) >= 10:+ return date.fromisoformat(trimmed[:10])++ raise ValueError(f"Unable to parse date value: {value!r}")+++class LenientDirectPostgresDateLoader(DateLoader):+ """Handle non-standard DATE text values returned by DuckDB's Postgres wire."""++ def load(self, data) -> date:+ try:+ return super().load(data)+ except psycopg.DataError as exc:+ try:+ return parse_lenient_direct_postgres_date(bytes(data).decode("utf8", "replace"))+ except ValueError:+ raise exc from None+++def get_runtime_direct_postgres_connection_metadata(+ connection: psycopg.Connection,+ connection_metadata: dict[str, object] | None = None,+) -> dict[str, object] | None:+ runtime_connection_metadata = dict(connection_metadata) if isinstance(connection_metadata, dict) else {}+ engine = runtime_connection_metadata.get("engine")+ database = runtime_connection_metadata.get("database")++ if engine is not None and isinstance(database, str) and database.strip():+ return runtime_connection_metadata++ metadata_cursor = connection.execute("SELECT current_database(), version()")+ row = metadata_cursor.fetchone()+ current_database = str(row[0]).strip() if row and row[0] is not None else None+ version = str(row[1]) if row and len(row) > 1 and row[1] is not None else ""++ if current_database and "database" not in runtime_connection_metadata:+ runtime_connection_metadata["database"] = current_database++ if "engine" not in runtime_connection_metadata:+ runtime_connection_metadata["engine"] = (+ "duckdb" if "duckdb" in version.lower() or "duckgres" in version.lower() else "postgres"+ )++ return runtime_connection_metadata or None+++def should_hydrate_runtime_direct_postgres_connection_metadata(+ schema: str | None,+ connection_metadata: dict[str, object] | None = None,+) -> bool:+ normalized_schema = schema.strip() if isinstance(schema, str) and schema.strip() else None+ return normalized_schema is None+++class PostgresAdapter:+ engine = "postgres"+ dialect: HogQLDialect | None = "postgres"++ def validate_source_config(+ self, source: "ExternalDataSource", team: "Team"+ ) -> tuple["PostgresSource", "PostgresSourceConfig"]:+ from posthog.temporal.data_imports.sources import SourceRegistry+ from posthog.temporal.data_imports.sources.postgres.source import PostgresSource++ from products.data_warehouse.backend.types import ExternalDataSourceType++ if not source.is_direct_postgres:+ raise ExposedHogQLError("Invalid direct Postgres connection.")++ postgres_source = cast(PostgresSource, SourceRegistry.get_source(ExternalDataSourceType.POSTGRES))+ config = postgres_source.parse_config(source.job_inputs or {})++ is_ssh_valid, ssh_valid_errors = postgres_source.ssh_tunnel_is_valid(config, team.pk)+ if not is_ssh_valid:+ raise ExposedHogQLError(ssh_valid_errors or "Invalid SSH tunnel configuration.")++ valid_host, host_errors = postgres_source.is_database_host_valid(+ config.host, team.pk, using_ssh_tunnel=config.ssh_tunnel.enabled if config.ssh_tunnel else False+ )+ if not valid_host:+ raise ExposedHogQLError(host_errors or "Invalid Postgres host.")++ return postgres_source, config++ def prepare_raw_sql(self, sql: str) -> str:+ return ensure_single_direct_statement(sql)++ def execute(self, request: DirectQueryRequest) -> DirectQueryResult:+ from posthog.temporal.data_imports.sources.postgres.postgres import _get_sslmode, source_requires_ssl++ source = request.source+ postgres_source, source_config = self.validate_source_config(source, request.team)+ source_schema = source_config.schema+ require_ssl = source_requires_ssl(source, source_config)+ settings = request.settings+ statement_timeout_ms = (+ max(settings.max_execution_time or DIRECT_POSTGRES_DEFAULT_STATEMENT_TIMEOUT_SECONDS, 1) * 1000+ )++ span = trace.get_current_span()+ span.set_attribute("team_id", request.team.pk)+ span.set_attribute("query_type", request.query_type)+ span.set_attribute("source_id", str(source.id))++ try:+ with request.timings.measure("postgres_execute"):+ with postgres_source.with_ssh_tunnel(source_config) as (host, port):+ connection_kwargs: PostgresConnectionKwargs = {+ "host": host,+ "port": port,+ "dbname": source_config.database,+ "user": source_config.user,+ "password": source_config.password,+ "connect_timeout": DIRECT_POSTGRES_CONNECT_TIMEOUT_SECONDS,+ "sslmode": _get_sslmode(require_ssl),+ "options": f"-c default_transaction_read_only=on -c statement_timeout={statement_timeout_ms}",+ # Prevent libpq from probing ~/.postgresql/ for client certs,+ # which fails with "Permission denied" in containers where+ # $HOME is /root/ but the process runs as a non-root user.+ "sslcert": "/tmp/no.txt",+ "sslkey": "/tmp/no.txt",+ "sslrootcert": "/tmp/no.txt",+ }+ if host.endswith(".us.postwh.com"):+ # DuckLake hosts require SSL but do not use certificate-based auth.+ connection_kwargs["sslmode"] = "require"++ with psycopg.connect(**connection_kwargs) as connection:+ runtime_connection_metadata = source.connection_metadata+ if should_hydrate_runtime_direct_postgres_connection_metadata(+ source_schema,+ runtime_connection_metadata,+ ):+ runtime_connection_metadata = get_runtime_direct_postgres_connection_metadata(+ connection,+ runtime_connection_metadata,+ )+ session_setup_sql = direct_postgres_session_setup_sql(+ source_schema,+ runtime_connection_metadata,+ host,+ )+ if session_setup_sql:+ connection.execute(session_setup_sql)+ connection.adapters.register_loader("date", LenientDirectPostgresDateLoader)+ with connection.cursor() as cursor:+ cursor.execute( # nosemgrep: python.django.security.injection.sql.sql-injection-using-db-cursor-execute.sql-injection-db-cursor-execute+ request.sql, request.values or None+ )+ results = cursor.fetchall()+ description = cursor.description or []+ except (psycopg.Error, ExposedHogQLError) as error:+ span.set_attribute("error_type", error.__class__.__name__)+ if request.debug:+ return DirectQueryResult(results=[], types=[], print_columns=[], error=postgres_error_to_message(error))+ raise ExposedHogQLError(postgres_error_to_message(error)) from error++ span.set_attribute("row_count", len(results))+ types: list[tuple[str, str]] = [+ (column.name, postgres_oid_to_clickhouse_type(getattr(column, "type_code", None))) for column in description+ ]+ print_columns = [column.name for column in description]+ return DirectQueryResult(results=results, types=types, print_columns=print_columns)diff --git a/posthog/hogql/direct_sql/raw_sql.py b/posthog/hogql/direct_sql/raw_sql.pynew file mode 100644index 000000000000..6bd6c2708f2f--- /dev/null+++ b/posthog/hogql/direct_sql/raw_sql.py@@ -0,0 +1,19 @@+import sqlparse++from posthog.hogql.errors import ExposedHogQLError+++def ensure_single_direct_statement(sql: str) -> str:+ """Reject multi-statement raw SQL.++ Raw queries run without bound parameters, so psycopg uses the simple query+ protocol, which runs every ``;``-separated statement in one round trip. A+ caller could commit out of the read-only transaction and ``BEGIN READ WRITE``+ to perform writes; restricting to one statement keeps it read-only. The same+ guard protects direct MySQL queries (PyMySQL additionally disables the+ MULTI_STATEMENTS client flag by default).+ """+ statements = [statement for statement in sqlparse.split(sql) if statement.strip(" \t\r\n;")]+ if len(statements) > 1:+ raise ExposedHogQLError("Raw queries must contain a single statement.")+ return sqldiff --git a/posthog/hogql/direct_sql/registry.py b/posthog/hogql/direct_sql/registry.pynew file mode 100644index 000000000000..4ec53e5fe201--- /dev/null+++ b/posthog/hogql/direct_sql/registry.py@@ -0,0 +1,17 @@+from posthog.hogql.direct_sql.adapter import DirectSQLAdapter++_ADAPTERS: dict[str, DirectSQLAdapter] = {}+++def register_adapter(adapter: DirectSQLAdapter) -> None:+ _ADAPTERS[adapter.engine] = adapter+++def get_adapter(engine: str | None) -> DirectSQLAdapter | None:+ if engine is None:+ return None+ return _ADAPTERS.get(engine)+++def registered_engines() -> frozenset[str]:+ return frozenset(_ADAPTERS.keys())diff --git a/posthog/hogql/direct_sql/test/test_registry_and_capability.py b/posthog/hogql/direct_sql/test/test_registry_and_capability.pynew file mode 100644index 000000000000..6ceda5374e1a--- /dev/null+++ b/posthog/hogql/direct_sql/test/test_registry_and_capability.py@@ -0,0 +1,64 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.hogql.direct_sql import (+ MySQLAdapter,+ PostgresAdapter,+ registry as registry_module,+)+from posthog.hogql.direct_sql.capability import direct_capable_source_types, is_direct_capable+from posthog.hogql.direct_sql.registry import get_adapter, register_adapter, registered_engines++from products.data_warehouse.backend.types import ExternalDataSourceType+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+++class TestDirectSQLRegistry(SimpleTestCase):+ def test_get_adapter_returns_registered_engine_adapter(self):+ self.assertIsInstance(get_adapter("postgres"), PostgresAdapter)+ self.assertIsInstance(get_adapter("mysql"), MySQLAdapter)++ @parameterized.expand([("none", None), ("unregistered", "snowflake")])+ def test_get_adapter_returns_none_for_unknown_engine(self, _name, engine):+ self.assertIsNone(get_adapter(engine))++ def test_registered_engines_includes_phase_one_engines(self):+ self.assertEqual({"postgres", "mysql"}, set(registered_engines()))++ def test_register_adapter_round_trips(self):+ class FakeAdapter:+ engine = "fake"+ dialect = None++ try:+ register_adapter(FakeAdapter()) # type: ignore[arg-type]+ self.assertIs(type(get_adapter("fake")), FakeAdapter)+ finally:+ registry_module._ADAPTERS.pop("fake", None)+++class TestDirectSQLCapability(SimpleTestCase):+ @parameterized.expand(+ [+ ("postgres_direct_ignores_toggle", ExternalDataSourceType.POSTGRES, "direct", False, True),+ ("postgres_synced_enabled", ExternalDataSourceType.POSTGRES, "warehouse", True, True),+ ("postgres_synced_disabled", ExternalDataSourceType.POSTGRES, "warehouse", False, False),+ ("mysql_synced_enabled", ExternalDataSourceType.MYSQL, "warehouse", True, True),+ ("unmapped_engine_synced", ExternalDataSourceType.STRIPE, "warehouse", True, False),+ ("unmapped_engine_direct", ExternalDataSourceType.STRIPE, "direct", True, False),+ ]+ )+ def test_is_direct_capable(self, _name, source_type, access_method, direct_query_enabled, expected):+ source = ExternalDataSource(+ source_type=source_type,+ access_method=access_method,+ direct_query_enabled=direct_query_enabled,+ )+ self.assertIs(is_direct_capable(source), expected)++ def test_direct_capable_source_types(self):+ self.assertEqual(+ {ExternalDataSourceType.POSTGRES, ExternalDataSourceType.MYSQL},+ set(direct_capable_source_types()),+ )diff --git a/posthog/hogql/metadata.py b/posthog/hogql/metadata.pyindex 868c071e6f17..3128bf6ab20c 100644--- a/posthog/hogql/metadata.py+++ b/posthog/hogql/metadata.py@@ -9,9 +9,11 @@ from posthog.schema import HogLanguage, HogQLMetadata, HogQLMetadataResponse, Hofrom posthog.hogql import astfrom posthog.hogql.base import ASTfrom posthog.hogql.compiler.bytecode import create_bytecode+from posthog.hogql.constants import HogQLDialectfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Databasefrom posthog.hogql.direct_connection import INVALID_CONNECTION_ID_ERROR, get_direct_connection_source+from posthog.hogql.direct_sql import get_adapterfrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.filters import replace_filtersfrom posthog.hogql.metadata_heuristics import run_metadata_heuristics@@ -105,8 +107,9 @@ def get_hogql_metadata(response.table_names = hogql_table_namesif not printed_sql or not prepared_ast:- direct_dialect: Literal["postgres", "mysql"] = (- "mysql" if source and source.is_direct_mysql else "postgres"+ direct_adapter = get_adapter(source.direct_engine) if source else None+ direct_dialect: HogQLDialect = (+ direct_adapter.dialect if direct_adapter and direct_adapter.dialect else "postgres")printed_sql, prepared_ast = prepare_and_print_ast(clone_expr(hogql_ast),diff --git a/posthog/hogql/query.py b/posthog/hogql/query.pyindex f194bfd81917..8df6928ea5fd 100644--- a/posthog/hogql/query.py+++ b/posthog/hogql/query.py@@ -1,15 +1,7 @@import dataclasses-from datetime import date, datetime-from typing import ClassVar, Literal, Optional, TypedDict, Union, cast+from typing import ClassVar, Literal, Optional, Union, cast-import psycopg-import pymysql-import sqlparsefrom opentelemetry import trace-from psycopg.types.datetime import DateLoader-from pymysql.constants import FIELD_TYPE as MYSQL_FIELD_TYPE-from sqlparse import tokens as sqlparse_tokens-from sqlparse.sql import Statementfrom posthog.schema import (HogLanguage,@@ -23,6 +15,7 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import (+ HogQLDialect,HogQLGlobalSettings,LimitContext,get_default_hogql_global_settings,@@ -37,13 +30,12 @@ from posthog.hogql.database.schema.duckdb_table_functions import ()from posthog.hogql.database.schema.logs import HOGQL_MAX_BYTES_TO_READ_FOR_LOGS_USER_QUERIESfrom posthog.hogql.direct_connection import (+ INVALID_CONNECTION_ID_ERROR,get_direct_connection_source,get_direct_connection_source_none_or_raise,- validate_direct_mysql_source_config,- validate_direct_postgres_source_config,)+from posthog.hogql.direct_sql import DirectQueryRequest, ensure_single_direct_statement, get_adapterfrom posthog.hogql.errors import ExposedHogQLError, InternalHogQLError, QueryError, ResolutionError-from posthog.hogql.escape_sql import escape_postgres_identifierfrom posthog.hogql.feature_extractor import extract_hogql_featuresfrom posthog.hogql.filters import replace_filtersfrom posthog.hogql.hogql import HogQLContext@@ -70,284 +62,6 @@ from posthog.rbac.user_access_control import UserAccessControlfrom posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIMEtracer = trace.get_tracer(__name__)-DIRECT_POSTGRES_CONNECT_TIMEOUT_SECONDS = 15-DIRECT_POSTGRES_DEFAULT_STATEMENT_TIMEOUT_SECONDS = 600-DIRECT_MYSQL_DEFAULT_STATEMENT_TIMEOUT_SECONDS = 600-RAW_MYSQL_READ_ONLY_ERROR = "Raw MySQL queries must be read-only SELECT statements."--POSTGRES_OID_TO_CLICKHOUSE_TYPE: dict[int, str] = {- 16: "Bool",- 20: "Int64",- 21: "Int16",- 23: "Int32",- 26: "UInt32",- 700: "Float32",- 701: "Float64",- 1082: "Date",- 1114: "DateTime",- 1184: "DateTime64(6, 'UTC')",- 1700: "Decimal",- 17: "String",- 19: "String",- 25: "String",- 1042: "String",- 1043: "String",- 114: "String",- 3802: "String",- 2950: "UUID",- 1083: "String",- 1266: "String",- 1186: "String",- 1000: "Array(Bool)",- 1005: "Array(Int16)",- 1007: "Array(Int32)",- 1016: "Array(Int64)",- 1021: "Array(Float32)",- 1022: "Array(Float64)",- 1115: "Array(DateTime)",- 1185: "Array(DateTime64(6, 'UTC'))",- 1182: "Array(Date)",- 1231: "Array(Decimal)",- 1009: "Array(String)",- 1015: "Array(String)",- 2951: "Array(UUID)",-}---MYSQL_FIELD_TYPE_TO_CLICKHOUSE_TYPE: dict[int, str] = {- MYSQL_FIELD_TYPE.TINY: "Int8",- MYSQL_FIELD_TYPE.SHORT: "Int16",- MYSQL_FIELD_TYPE.INT24: "Int32",- MYSQL_FIELD_TYPE.LONG: "Int32",- MYSQL_FIELD_TYPE.LONGLONG: "Int64",- MYSQL_FIELD_TYPE.YEAR: "Int32",- MYSQL_FIELD_TYPE.FLOAT: "Float32",- MYSQL_FIELD_TYPE.DOUBLE: "Float64",- MYSQL_FIELD_TYPE.DECIMAL: "Decimal",- MYSQL_FIELD_TYPE.NEWDECIMAL: "Decimal",- MYSQL_FIELD_TYPE.DATE: "Date",- MYSQL_FIELD_TYPE.NEWDATE: "Date",- MYSQL_FIELD_TYPE.DATETIME: "DateTime",- MYSQL_FIELD_TYPE.TIMESTAMP: "DateTime",- MYSQL_FIELD_TYPE.TIME: "String",- MYSQL_FIELD_TYPE.BIT: "String",- MYSQL_FIELD_TYPE.JSON: "String",- MYSQL_FIELD_TYPE.ENUM: "String",- MYSQL_FIELD_TYPE.SET: "String",- MYSQL_FIELD_TYPE.TINY_BLOB: "String",- MYSQL_FIELD_TYPE.MEDIUM_BLOB: "String",- MYSQL_FIELD_TYPE.LONG_BLOB: "String",- MYSQL_FIELD_TYPE.BLOB: "String",- MYSQL_FIELD_TYPE.VAR_STRING: "String",- MYSQL_FIELD_TYPE.VARCHAR: "String",- MYSQL_FIELD_TYPE.STRING: "String",- MYSQL_FIELD_TYPE.GEOMETRY: "String",-}---def mysql_field_type_to_clickhouse_type(type_code: int | None) -> str:- if type_code is None:- return "String"- return MYSQL_FIELD_TYPE_TO_CLICKHOUSE_TYPE.get(type_code, "String")---def mysql_error_to_message(error: Exception) -> str:- if isinstance(error, pymysql.MySQLError):- args = error.args- if len(args) >= 2 and isinstance(args[1], str) and args[1].strip():- return args[1].strip().splitlines()[0]-- message = str(error).strip()- if not message:- return "MySQL query failed."- return message.splitlines()[0]---class PostgresConnectionKwargs(TypedDict, total=False):- host: str- port: int- dbname: str- user: str- password: str- connect_timeout: int- sslmode: str- options: str- sslcert: str- sslkey: str- sslrootcert: str---def postgres_oid_to_clickhouse_type(oid: int | None) -> str:- if oid is None:- return "String"-- return POSTGRES_OID_TO_CLICKHOUSE_TYPE.get(oid, "String")---def postgres_error_to_message(error: Exception) -> str:- if isinstance(error, psycopg.Error):- diag = getattr(error, "diag", None)- message_primary = getattr(diag, "message_primary", None) if diag else None- message_detail = getattr(diag, "message_detail", None) if diag else None- if message_primary and message_detail:- return f"{message_primary} {message_detail}"- if message_primary:- return message_primary-- message = str(error).strip()- if not message:- return "Postgres query failed."- return message.splitlines()[0]---def ensure_single_direct_statement(sql: str) -> str:- """Reject multi-statement raw SQL.-- Raw queries run without bound parameters, so psycopg uses the simple query- protocol, which runs every ``;``-separated statement in one round trip. A- caller could commit out of the read-only transaction and ``BEGIN READ WRITE``- to perform writes; restricting to one statement keeps it read-only. The same- guard protects direct MySQL queries (PyMySQL additionally disables the- MULTI_STATEMENTS client flag by default).- """- statements = [statement for statement in sqlparse.split(sql) if statement.strip(" \t\r\n;")]- if len(statements) > 1:- raise ExposedHogQLError("Raw queries must contain a single statement.")- return sql---def _is_executable_mysql_comment(value: str) -> bool:- normalized = value.lstrip().upper()- return normalized.startswith("/*!") or normalized.startswith("/*M!")---def _raw_mysql_token_values(statement: Statement) -> list[str]:- token_values: list[str] = []- for token in statement.flatten():- if token.ttype in sqlparse_tokens.Comment:- if _is_executable_mysql_comment(token.value):- raise ExposedHogQLError(RAW_MYSQL_READ_ONLY_ERROR)- continue- if token.is_whitespace or token.ttype in sqlparse_tokens.Literal.String:- continue- value = token.value.strip().upper()- if value:- token_values.append(value)- return token_values---def ensure_read_only_raw_mysql_statement(sql: str) -> str:- sql = ensure_single_direct_statement(sql)- statements = [statement for statement in sqlparse.parse(sql) if str(statement).strip(" \t\r\n;")]- if len(statements) != 1 or statements[0].get_type() != "SELECT":- raise ExposedHogQLError(RAW_MYSQL_READ_ONLY_ERROR)-- token_values = _raw_mysql_token_values(statements[0])- for index, value in enumerate(token_values):- normalized_value = value.strip("`")- if value == "INTO":- raise ExposedHogQLError(RAW_MYSQL_READ_ONLY_ERROR)- if normalized_value == "LOAD_FILE" and index + 1 < len(token_values) and token_values[index + 1] == "(":- raise ExposedHogQLError(RAW_MYSQL_READ_ONLY_ERROR)- if value == "FOR" and index + 1 < len(token_values) and token_values[index + 1] in {"UPDATE", "SHARE"}:- raise ExposedHogQLError(RAW_MYSQL_READ_ONLY_ERROR)- if token_values[index : index + 4] == ["LOCK", "IN", "SHARE", "MODE"]:- raise ExposedHogQLError(RAW_MYSQL_READ_ONLY_ERROR)-- return sql---def direct_postgres_session_setup_sql(- schema: str | None,- connection_metadata: dict[str, object] | None = None,- host: str | None = None,-) -> str | None:- engine = connection_metadata.get("engine") if isinstance(connection_metadata, dict) else None- database = connection_metadata.get("database") if isinstance(connection_metadata, dict) else None- normalized_schema = schema.strip() if isinstance(schema, str) and schema.strip() else None-- if engine == "duckdb" or (host is not None and host.endswith(".postwh.com")):- if normalized_schema:- quoted_schema = escape_postgres_identifier(normalized_schema)- return f"USE {quoted_schema}"- if isinstance(database, str) and database.strip():- quoted_database = escape_postgres_identifier(database.strip())- return f"USE {quoted_database}"- return None-- if not normalized_schema:- return None-- quoted_schema = escape_postgres_identifier(normalized_schema)- return f"SET search_path TO {quoted_schema}"---def parse_lenient_direct_postgres_date(value: str) -> date:- trimmed = value.strip()-- try:- return date.fromisoformat(trimmed)- except ValueError:- pass-- normalized = trimmed[:-1] + "+00:00" if trimmed.endswith("Z") else trimmed- try:- return datetime.fromisoformat(normalized).date()- except ValueError:- pass-- if len(trimmed) >= 10:- return date.fromisoformat(trimmed[:10])-- raise ValueError(f"Unable to parse date value: {value!r}")---class LenientDirectPostgresDateLoader(DateLoader):- """Handle non-standard DATE text values returned by DuckDB's Postgres wire."""-- def load(self, data) -> date:- try:- return super().load(data)- except psycopg.DataError as exc:- try:- return parse_lenient_direct_postgres_date(bytes(data).decode("utf8", "replace"))- except ValueError:- raise exc from None---def get_runtime_direct_postgres_connection_metadata(- connection: psycopg.Connection,- connection_metadata: dict[str, object] | None = None,-) -> dict[str, object] | None:- runtime_connection_metadata = dict(connection_metadata) if isinstance(connection_metadata, dict) else {}- engine = runtime_connection_metadata.get("engine")- database = runtime_connection_metadata.get("database")-- if engine is not None and isinstance(database, str) and database.strip():- return runtime_connection_metadata-- metadata_cursor = connection.execute("SELECT current_database(), version()")- row = metadata_cursor.fetchone()- current_database = str(row[0]).strip() if row and row[0] is not None else None- version = str(row[1]) if row and len(row) > 1 and row[1] is not None else ""-- if current_database and "database" not in runtime_connection_metadata:- runtime_connection_metadata["database"] = current_database-- if "engine" not in runtime_connection_metadata:- runtime_connection_metadata["engine"] = (- "duckdb" if "duckdb" in version.lower() or "duckgres" in version.lower() else "postgres"- )-- return runtime_connection_metadata or None---def should_hydrate_runtime_direct_postgres_connection_metadata(- schema: str | None,- connection_metadata: dict[str, object] | None = None,-) -> bool:- normalized_schema = schema.strip() if isinstance(schema, str) and schema.strip() else None- return normalized_schema is None@dataclasses.dataclass@@ -374,7 +88,7 @@ class HogQLQueryExecutor:direct_sql: Optional[str] = Nonedirect_source_id: Optional[str] = Nonedirect_values: dict[str, object] | None = None- direct_dialect: Optional[Literal["postgres", "mysql"]] = None+ direct_dialect: Optional[HogQLDialect] = Noneconnection_id: Optional[str] = Nonesend_raw_query: bool = Falseuser: Optional[User] = None@@ -650,7 +364,8 @@ class HogQLQueryExecutor:raise ExposedHogQLError("The query references a different source than the selected connection.")source = getattr(self, "_direct_source", None)- dialect: Literal["postgres", "mysql"] = "mysql" if source is not None and source.is_direct_mysql else "postgres"+ adapter = get_adapter(source.direct_engine) if source is not None else None+ dialect: HogQLDialect = adapter.dialect if adapter is not None and adapter.dialect is not None else "postgres"direct_context = dataclasses.replace(self.context,@@ -701,140 +416,37 @@ class HogQLQueryExecutor:return None- @tracer.start_as_current_span("HogQLQueryExecutor._execute_direct_postgres_query")- def _execute_direct_postgres_query(self) -> None:+ @tracer.start_as_current_span("HogQLQueryExecutor._execute_direct_sql_query")+ def _execute_direct_sql_query(self) -> None:assert self.direct_sql is not Noneassert self.direct_source_id is not None- from posthog.temporal.data_imports.sources.postgres.postgres import _get_sslmode, source_requires_ssl-source = get_direct_connection_source(self.team, self.direct_source_id, user=self.user)if source is None:raise ExposedHogQLError("Connection not found or has been deleted")- postgres_source, source_config = validate_direct_postgres_source_config(source, self.team)- source_schema = source_config.schema- require_ssl = source_requires_ssl(source, source_config)- settings = self._effective_direct_settings()- statement_timeout_ms = (- max(settings.max_execution_time or DIRECT_POSTGRES_DEFAULT_STATEMENT_TIMEOUT_SECONDS, 1) * 1000- )-- span = trace.get_current_span()- span.set_attribute("team_id", self.team.pk)- span.set_attribute("query_type", self.query_type)- span.set_attribute("source_id", self.direct_source_id)-- try:- with self.timings.measure("postgres_execute"):- with postgres_source.with_ssh_tunnel(source_config) as (host, port):- connection_kwargs: PostgresConnectionKwargs = {- "host": host,- "port": port,- "dbname": source_config.database,- "user": source_config.user,- "password": source_config.password,- "connect_timeout": DIRECT_POSTGRES_CONNECT_TIMEOUT_SECONDS,- "sslmode": _get_sslmode(require_ssl),- "options": f"-c default_transaction_read_only=on -c statement_timeout={statement_timeout_ms}",- # Prevent libpq from probing ~/.postgresql/ for client certs,- # which fails with "Permission denied" in containers where- # $HOME is /root/ but the process runs as a non-root user.- "sslcert": "/tmp/no.txt",- "sslkey": "/tmp/no.txt",- "sslrootcert": "/tmp/no.txt",- }- if host.endswith(".us.postwh.com"):- # DuckLake hosts require SSL but do not use certificate-based auth.- connection_kwargs["sslmode"] = "require"-- with psycopg.connect(**connection_kwargs) as connection:- runtime_connection_metadata = source.connection_metadata- if should_hydrate_runtime_direct_postgres_connection_metadata(- source_schema,- runtime_connection_metadata,- ):- runtime_connection_metadata = get_runtime_direct_postgres_connection_metadata(- connection,- runtime_connection_metadata,- )- session_setup_sql = direct_postgres_session_setup_sql(- source_schema,- runtime_connection_metadata,- host,- )- if session_setup_sql:- connection.execute(session_setup_sql)- connection.adapters.register_loader("date", LenientDirectPostgresDateLoader)- with connection.cursor() as cursor:- cursor.execute(self.direct_sql, self.direct_values or None)- results = cursor.fetchall()- description = cursor.description or []- except (psycopg.Error, ExposedHogQLError) as error:- span.set_attribute("error_type", error.__class__.__name__)- if self.debug:- self.results = []- self.error = postgres_error_to_message(error)- self.types = []- return- raise ExposedHogQLError(postgres_error_to_message(error)) from error-- span.set_attribute("row_count", len(results))- self.results = results- self.types = [- (column.name, postgres_oid_to_clickhouse_type(getattr(column, "type_code", None))) for column in description- ]- if not self.print_columns:- self.print_columns = [column.name for column in description]-- @tracer.start_as_current_span("HogQLQueryExecutor._execute_direct_mysql_query")- def _execute_direct_mysql_query(self) -> None:- assert self.direct_sql is not None- assert self.direct_source_id is not None-- source = get_direct_connection_source(self.team, self.direct_source_id, user=self.user)- if source is None:- raise ExposedHogQLError("Connection not found or has been deleted")+ adapter = get_adapter(source.direct_engine)+ if adapter is None:+ raise InternalHogQLError(f"No direct SQL adapter registered for engine: {source.direct_engine}")- mysql_implementation, source_config = validate_direct_mysql_source_config(source, self.team)- settings = self._effective_direct_settings()- statement_timeout_seconds = max(- settings.max_execution_time or DIRECT_MYSQL_DEFAULT_STATEMENT_TIMEOUT_SECONDS, 1+ result = adapter.execute(+ DirectQueryRequest(+ source=source,+ team=self.team,+ sql=self.direct_sql,+ values=self.direct_values,+ settings=self._effective_direct_settings(),+ timings=self.timings,+ query_type=self.query_type,+ debug=bool(self.debug),+ ))- span = trace.get_current_span()- span.set_attribute("team_id", self.team.pk)- span.set_attribute("query_type", self.query_type)- span.set_attribute("source_id", self.direct_source_id)-- try:- with self.timings.measure("mysql_execute"):- with mysql_implementation.connect(source_config, read_timeout=statement_timeout_seconds) as connection:- with connection.cursor() as cursor:- try:- # MySQL 8 only and SELECT-only; MariaDB uses a different variable.- # The read_timeout above is the backstop if this is unavailable.- cursor.execute(f"SET SESSION MAX_EXECUTION_TIME = {statement_timeout_seconds * 1000}")- except pymysql.MySQLError:- pass- cursor.execute("START TRANSACTION READ ONLY")- cursor.execute(self.direct_sql, self.direct_values or None)- results = cursor.fetchall()- description = cursor.description or []- except (pymysql.MySQLError, ExposedHogQLError) as error:- span.set_attribute("error_type", error.__class__.__name__)- if self.debug:- self.results = []- self.error = mysql_error_to_message(error)- self.types = []- return- raise ExposedHogQLError(mysql_error_to_message(error)) from error-- span.set_attribute("row_count", len(results))- self.results = list(results)- self.types = [(column[0], mysql_field_type_to_clickhouse_type(column[1])) for column in description]- if not self.print_columns:- self.print_columns = [column[0] for column in description]+ self.results = result.results+ self.types = result.types+ self.error = result.error+ if result.print_columns and not self.print_columns:+ self.print_columns = result.print_columns@tracer.start_as_current_span("HogQLQueryExecutor._generate_clickhouse_sql")def _generate_clickhouse_sql(self):@@ -938,14 +550,12 @@ class HogQLQueryExecutor:raise ExposedHogQLError("Sending a raw query requires a valid connection.")self.connection_id = str(source.id)self.direct_source_id = self.connection_id- if source.is_direct_mysql:- self.direct_dialect = "mysql"- self.direct_sql = ensure_read_only_raw_mysql_statement(str(self.query))- self._execute_direct_mysql_query()- else:- self.direct_dialect = "postgres"- self.direct_sql = ensure_single_direct_statement(str(self.query))- self._execute_direct_postgres_query()+ adapter = get_adapter(source.direct_engine)+ if adapter is None:+ raise ExposedHogQLError(INVALID_CONNECTION_ID_ERROR)+ self.direct_dialect = adapter.dialect+ self.direct_sql = adapter.prepare_raw_sql(str(self.query))+ self._execute_direct_sql_query()def _capture_send_raw_query_translation_error(self) -> None:"""Try a post-success HogQL translation for raw queries.@@ -1073,12 +683,7 @@ class HogQLQueryExecutor:prepared_execution = self._prepare_execution()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}")+ self._execute_direct_sql_query()elif self.clickhouse_sql is not None:if self.clickhouse_sql == "":self.results = []diff --git a/posthog/hogql/test/test_direct_mysql_query.py b/posthog/hogql/test/test_direct_mysql_query.pyindex 4d1f4d32b124..a6ef061a8b0c 100644--- a/posthog/hogql/test/test_direct_mysql_query.py+++ b/posthog/hogql/test/test_direct_mysql_query.py@@ -7,8 +7,9 @@ from unittest.mock import MagicMock, patchimport pymysqlfrom parameterized import parameterized+from posthog.hogql.direct_sql.mysql_adapter import mysql_error_to_message, mysql_field_type_to_clickhouse_typefrom posthog.hogql.errors import ExposedHogQLError, QueryError-from posthog.hogql.query import HogQLQueryExecutor, mysql_error_to_message, mysql_field_type_to_clickhouse_type+from posthog.hogql.query import HogQLQueryExecutorfrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTable@@ -305,7 +306,7 @@ class TestDirectMySQLQuery(APIBaseTest):)with patch(- "posthog.hogql.query.validate_direct_mysql_source_config",+ "posthog.hogql.direct_sql.mysql_adapter.MySQLAdapter.validate_source_config",return_value=(implementation, MagicMock()),):with patch.object(HogQLQueryExecutor, "_capture_send_raw_query_translation_error"):@@ -345,7 +346,7 @@ class TestDirectMySQLQuery(APIBaseTest):)with patch(- "posthog.hogql.query.validate_direct_mysql_source_config",+ "posthog.hogql.direct_sql.mysql_adapter.MySQLAdapter.validate_source_config",return_value=(implementation, MagicMock()),):with patch.object(HogQLQueryExecutor, "_capture_send_raw_query_translation_error"):@@ -382,7 +383,7 @@ class TestDirectMySQLQuery(APIBaseTest):send_raw_query=True,)- with patch("posthog.hogql.query.validate_direct_mysql_source_config") as mock_validate:+ with patch("posthog.hogql.direct_sql.mysql_adapter.MySQLAdapter.validate_source_config") as mock_validate:with self.assertRaisesRegex(ExposedHogQLError, "Raw MySQL queries must be read-only SELECT statements."):executor.execute()@@ -414,7 +415,7 @@ class TestDirectMySQLQuery(APIBaseTest):implementation.connect.return_value.__exit__.return_value = Falsewith patch(- "posthog.hogql.query.validate_direct_mysql_source_config",+ "posthog.hogql.direct_sql.mysql_adapter.MySQLAdapter.validate_source_config",return_value=(implementation, MagicMock()),):response = executor.execute()diff --git a/posthog/hogql/test/test_direct_postgres_query.py b/posthog/hogql/test/test_direct_postgres_query.pyindex 9061863d3785..5eebf1eb1dd0 100644--- a/posthog/hogql/test/test_direct_postgres_query.py+++ b/posthog/hogql/test/test_direct_postgres_query.py@@ -12,18 +12,18 @@ from parameterized import parameterizedfrom posthog.hogql.constants import HogQLGlobalSettingsfrom posthog.hogql.database.schema.duckdb_table_functions import is_dangerous_table_function-from posthog.hogql.errors import ExposedHogQLError, QueryError-from posthog.hogql.escape_sql import escape_postgres_identifier-from posthog.hogql.query import (- HogQLQueryExecutor,+from posthog.hogql.direct_sql.postgres_adapter import (LenientDirectPostgresDateLoader,direct_postgres_session_setup_sql,- ensure_single_direct_statement,get_runtime_direct_postgres_connection_metadata,parse_lenient_direct_postgres_date,postgres_error_to_message,postgres_oid_to_clickhouse_type,)+from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement+from posthog.hogql.errors import ExposedHogQLError, QueryError+from posthog.hogql.escape_sql import escape_postgres_identifier+from posthog.hogql.query import HogQLQueryExecutorfrom posthog.temporal.data_imports.sources.postgres.postgres import SSL_REQUIRED_AFTER_DATE@@ -739,7 +739,7 @@ class TestDirectPostgresQuery(APIBaseTest):self.assertEqual(events_executor.direct_source_id, str(source.id))self.assertEqual(persons_executor.direct_source_id, str(source.id))- @patch("posthog.hogql.query.psycopg.connect")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_selected_connection_allows_table_less_sql(self, mock_connect):source = ExternalDataSource.objects.create(team=self.team,@@ -782,7 +782,7 @@ class TestDirectPostgresQuery(APIBaseTest):self.assertIn("1 AS value", executor.direct_sql)self.assertIn("LIMIT 100", executor.direct_sql)- @patch("posthog.hogql.query.psycopg.connect")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_send_raw_query_registers_lenient_date_loader_for_duckdb_style_dates(self, mock_connect):source = ExternalDataSource.objects.create(team=self.team,@@ -826,7 +826,7 @@ class TestDirectPostgresQuery(APIBaseTest):mocked_connection.execute.assert_called_once_with(f"USE {escape_postgres_identifier(job_inputs['schema'])}")mocked_connection.adapters.register_loader.assert_any_call("date", LenientDirectPostgresDateLoader)- @patch("posthog.hogql.query.psycopg.connect")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_send_raw_query_uses_duckdb_schema_without_hydrating_catalog(self, mock_connect):source = ExternalDataSource.objects.create(team=self.team,@@ -872,7 +872,7 @@ class TestDirectPostgresQuery(APIBaseTest):self.assertEqual(mocked_connection.execute.call_count, 1)mocked_cursor.execute.assert_called_once_with("SELECT * FROM system.query_log LIMIT 100", None)- @patch("posthog.hogql.query.psycopg.connect")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_send_raw_query_uses_schema_for_duckdb_when_catalog_is_available(self, mock_connect):source = ExternalDataSource.objects.create(team=self.team,@@ -917,7 +917,7 @@ class TestDirectPostgresQuery(APIBaseTest):)@patch("posthog.hogql.query.capture_exception")- @patch("posthog.hogql.query.psycopg.connect")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_send_raw_query_executes_raw_query_and_preserves_hogql_when_printable(self, mock_connect, mock_capture_exception):@@ -968,7 +968,7 @@ class TestDirectPostgresQuery(APIBaseTest):mock_capture_exception.assert_not_called()@patch("posthog.hogql.query.capture_exception")- @patch("posthog.hogql.query.psycopg.connect")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_send_raw_query_captures_parse_failures_after_success(self, mock_connect, mock_capture_exception):source = ExternalDataSource.objects.create(team=self.team,@@ -1014,7 +1014,7 @@ class TestDirectPostgresQuery(APIBaseTest):mock_capture_exception.assert_called_once()@patch("posthog.hogql.query.capture_exception")- @patch("posthog.hogql.query.psycopg.connect")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_send_raw_query_uses_catalog_for_duckdb_without_schema(self, mock_connect, mock_capture_exception):source = ExternalDataSource.objects.create(team=self.team,@@ -1058,7 +1058,7 @@ class TestDirectPostgresQuery(APIBaseTest):mocked_cursor.execute.assert_called_once_with("SELECT 1 AS value", None)mock_capture_exception.assert_not_called()- @patch("posthog.hogql.query.psycopg.connect")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_send_raw_query_skips_session_setup_when_schema_is_blank(self, mock_connect):source = ExternalDataSource.objects.create(team=self.team,@@ -1124,7 +1124,7 @@ class TestDirectPostgresQuery(APIBaseTest):def test_ensure_single_direct_statement_allows_single_statement(self, _name: str, sql: str):self.assertEqual(ensure_single_direct_statement(sql), sql)- @patch("posthog.hogql.query.psycopg.connect")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_send_raw_query_rejects_multi_statement_before_execution(self, mock_connect):source = ExternalDataSource.objects.create(team=self.team,@@ -1209,7 +1209,7 @@ class TestDirectPostgresQuery(APIBaseTest):executor.direct_source_id = missing_source_idwith self.assertRaises(ExposedHogQLError) as error:- executor._execute_direct_postgres_query()+ executor._execute_direct_sql_query()self.assertEqual(str(error.exception), "Connection not found or has been deleted")@@ -1223,7 +1223,7 @@ class TestDirectPostgresQuery(APIBaseTest):)@override_settings(CLOUD_DEPLOYMENT="US")- @patch("posthog.hogql.query.psycopg.connect")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_execute_direct_postgres_query_blocks_internal_host(self, mock_connect):source = ExternalDataSource.objects.create(team=self.team,@@ -1266,7 +1266,7 @@ class TestDirectPostgresQuery(APIBaseTest):self.assertEqual(str(error.exception), "Hosts with internal IP addresses are not allowed")mock_connect.assert_not_called()- @patch("posthog.hogql.query.psycopg.connect")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_execute_direct_postgres_query_exposes_database_errors(self, mock_connect):source = ExternalDataSource.objects.create(team=self.team,@@ -1322,7 +1322,7 @@ class TestDirectPostgresQuery(APIBaseTest):"-c default_transaction_read_only=on -c statement_timeout=60000",)- @patch("posthog.hogql.query.psycopg.connect")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_execute_direct_postgres_query_uses_custom_statement_timeout(self, mock_connect):source = ExternalDataSource.objects.create(team=self.team,@@ -1376,7 +1376,7 @@ class TestDirectPostgresQuery(APIBaseTest):)self.assertTrue(any(timing.k.endswith("/postgres_execute") for timing in executor.timings.to_list()))- @patch("posthog.hogql.query.psycopg.connect")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_execute_direct_postgres_query_records_postgres_execute_timing(self, mock_connect):source = ExternalDataSource.objects.create(team=self.team,@@ -1426,7 +1426,7 @@ class TestDirectPostgresQuery(APIBaseTest):self.assertTrue(any(timing.k.endswith("/postgres_execute") for timing in response.timings or []))- @patch("posthog.hogql.query.psycopg.connect")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_execute_direct_postgres_query_reraises_unexpected_errors(self, mock_connect):source = ExternalDataSource.objects.create(team=self.team,@@ -1514,7 +1514,7 @@ class TestDirectPostgresQuery(APIBaseTest):)@override_settings(DEBUG=False, TEST=False)@patch("products.warehouse_sources.backend.models.ssh_tunnel.SSHTunnelForwarder")- @patch("posthog.hogql.query.psycopg.connect")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_direct_postgres_ssl(self, _name, job_inputs, expected_sslmode, mock_connect, mock_tunnel_cls):mock_tunnel = MagicMock()mock_tunnel.local_bind_host = "127.0.0.1"@@ -1577,7 +1577,7 @@ class TestDirectPostgresQuery(APIBaseTest):self.assertEqual(mock_connect.call_args.kwargs["sslmode"], expected_sslmode)@override_settings(DEBUG=False, TEST=False, E2E_TESTING=True)- @patch("posthog.hogql.query.psycopg.connect")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_execute_direct_postgres_query_uses_prefer_sslmode_in_e2e_for_new_sources(self, mock_connect):source = ExternalDataSource.objects.create(team=self.team,@@ -1630,7 +1630,7 @@ class TestDirectPostgresQuery(APIBaseTest):self.assertEqual(mock_connect.call_args.kwargs["sslmode"], "prefer")@override_settings(DEBUG=False, TEST=False)- @patch("posthog.hogql.query.psycopg.connect")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_execute_direct_postgres_query_adds_ssl_cert_paths_for_postwh_hosts(self, mock_connect):source = ExternalDataSource.objects.create(team=self.team,diff --git a/products/data_warehouse/backend/types.py b/products/data_warehouse/backend/types.pyindex e6e92ff42dd8..ff373b10d282 100644--- a/products/data_warehouse/backend/types.py+++ b/products/data_warehouse/backend/types.py@@ -677,5 +677,14 @@ class ExternalDataSourceType(models.TextChoices):CHATWOOT = "Chatwoot", "Chatwoot"+# Maps a source type to the direct-SQL engine that can query it live. A source type is only+# direct-query-capable if it appears here AND has an adapter registered in posthog/hogql/direct_sql.+# Adding an engine = one entry here + one adapter module + one registry call.+DIRECT_ENGINE_BY_SOURCE_TYPE: dict[str, str] = {+ ExternalDataSourceType.POSTGRES: "postgres",+ ExternalDataSourceType.MYSQL: "mysql",+}++class DataWarehouseManagedViewSetKind(models.TextChoices):REVENUE_ANALYTICS = "revenue_analytics", "Revenue Analytics"diff --git a/products/warehouse_sources/backend/models/external_data_source.py b/products/warehouse_sources/backend/models/external_data_source.pyindex cb631c0ed740..ed9628b55842 100644--- a/products/warehouse_sources/backend/models/external_data_source.py+++ b/products/warehouse_sources/backend/models/external_data_source.py@@ -10,7 +10,7 @@ from posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.utils import CreatedMetaFields, DeletedMetaFields, UpdatedMetaFields, UUIDTModel, sane_reprfrom posthog.sync import database_sync_to_async-from products.data_warehouse.backend.types import ExternalDataSourceType+from products.data_warehouse.backend.types import DIRECT_ENGINE_BY_SOURCE_TYPE, ExternalDataSourceTypelogger = structlog.get_logger(__name__)@@ -89,6 +89,16 @@ class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFielddef is_direct_mysql(self) -> bool:return self.is_direct_query and self.source_type == ExternalDataSourceType.MYSQL+ @property+ def direct_engine(self) -> str | None:+ """The direct-SQL engine for this source's type, or None if no engine maps to it.++ This keys off ``source_type`` only and ignores ``access_method``/toggles — a non-None+ result means "an engine exists for this type", not "this source is queryable". Whether a+ source may actually be queried live is decided by ``is_direct_capable`` and the adapters.+ """+ return DIRECT_ENGINE_BY_SOURCE_TYPE.get(self.source_type)+@propertydef supports_scheduled_sync(self) -> bool:return not self.is_direct_query