: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
fix(hogql): align direct query validation with connection dialects (#127813)
Marius Andra820472e71779
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.mdindex 45043b7e102b..695b544632df 100644--- a/docs/published/handbook/engineering/data-warehouse.md+++ b/docs/published/handbook/engineering/data-warehouse.md@@ -10,6 +10,10 @@ Projects with a connected warehouse source or warehouse table use ordinary emptyOnboarding only checks warehouse setup for non-demo projects without events. Source detection returns an existence flag without serializing schemas, and table detection omits columns. Navigation refreshes an empty result so returning after source creation opens the Sources list.+## Direct SQL validation++**Send raw query** checks statement boundaries and read-only restrictions using the selected connection's SQL dialect. Quoted strings, identifiers, and comments follow that dialect, including backslashes in LIKE and regex patterns. Queries with unfinished quotes or comments are rejected before execution. For PostgreSQL, Redshift, and MySQL, quoting must have the same boundaries with and without session-level backslash escaping; use doubled quotes when embedding a quote in a string.+## Model namespace reservationThe shared PostHog catalog reserves `models.*` for authored data models. New warehouse tables, endpoint saved queries, and managed viewsets cannot claim that namespace. The bare name `models` is reserved for the namespace container; use a name such as `models.revenue` for a model. Names such as `models_v2` remain available. Saved queries with no origin are treated as authored models for compatibility.diff --git a/posthog/hogql/direct_sql/bigquery_adapter.py b/posthog/hogql/direct_sql/bigquery_adapter.pyindex 577344de5d69..6393faed981b 100644--- a/posthog/hogql/direct_sql/bigquery_adapter.py+++ b/posthog/hogql/direct_sql/bigquery_adapter.py@@ -4,7 +4,6 @@ import base64from concurrent import futuresfrom typing import TYPE_CHECKING, Any, cast-import sqlparsefrom opentelemetry import tracefrom sqlparse import tokens as sqlparse_tokens@@ -12,7 +11,7 @@ from posthog.hogql.constants import HogQLDialectfrom posthog.hogql.direct_query_metrics import DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL, observe_direct_queryfrom posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult, parse_direct_source_configfrom posthog.hogql.direct_sql.capability import bigquery_direct_query_enabled, is_direct_capable-from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement+from posthog.hogql.direct_sql.raw_sql import parse_direct_statementsfrom posthog.hogql.errors import ExposedHogQLError, InternalHogQLErrorif TYPE_CHECKING:@@ -83,8 +82,7 @@ def bigquery_error_to_message(error: Exception) -> str:def ensure_read_only_raw_bigquery_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;")]+ statements = parse_direct_statements(sql, dialect="bigquery")if len(statements) != 1 or statements[0].get_type() != "SELECT":raise ExposedHogQLError(RAW_BIGQUERY_READ_ONLY_ERROR)# BigQuery has no read-only session switch, and a single query job will run adiff --git a/posthog/hogql/direct_sql/clickhouse_adapter.py b/posthog/hogql/direct_sql/clickhouse_adapter.pyindex 2714ade2c4c2..dfd09f22db85 100644--- a/posthog/hogql/direct_sql/clickhouse_adapter.py+++ b/posthog/hogql/direct_sql/clickhouse_adapter.py@@ -2,7 +2,6 @@ from collections.abc import Iteratorfrom time import perf_counterfrom typing import TYPE_CHECKING, Any, cast-import sqlparsefrom opentelemetry import tracefrom sqlparse import tokens as sqlparse_tokensfrom sqlparse.sql import TokenList@@ -12,7 +11,7 @@ from posthog.hogql.constants import HogQLDialectfrom posthog.hogql.direct_query_metrics import DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL, observe_direct_queryfrom posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult, parse_direct_source_configfrom posthog.hogql.direct_sql.capability import is_direct_capable-from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement+from posthog.hogql.direct_sql.raw_sql import parse_direct_statementsfrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.dataclasses import frozen@@ -182,8 +181,7 @@ def ensure_read_only_raw_clickhouse_statement(sql: str) -> str:``max_block_size`` to defeat the timeout and per-block memory bounds. HogQL-authored queriesdon't take this raw path, so they can still set whatever settings the printer emits."""- sql = ensure_single_direct_statement(sql)- statements = [statement for statement in sqlparse.parse(sql) if str(statement).strip(" \t\r\n;")]+ statements = parse_direct_statements(sql, dialect="clickhouse")if len(statements) != 1 or statements[0].get_type() != "SELECT":raise ExposedHogQLError(RAW_CLICKHOUSE_READ_ONLY_ERROR)statement = statements[0]diff --git a/posthog/hogql/direct_sql/duckgres_adapter.py b/posthog/hogql/direct_sql/duckgres_adapter.pyindex b0a1953f70cd..de51bd44630b 100644--- a/posthog/hogql/direct_sql/duckgres_adapter.py+++ b/posthog/hogql/direct_sql/duckgres_adapter.py@@ -383,7 +383,7 @@ class DuckgresRawAdapter:)def prepare_raw_sql(self, sql: str) -> str:- return ensure_single_direct_statement(sql)+ return ensure_single_direct_statement(sql, dialect="duckdb")def _resolve_source_config(self, request: DirectQueryRequest) -> _DuckgresConnectionConfig:metadata = request.source.connection_metadatadiff --git a/posthog/hogql/direct_sql/motherduck_adapter.py b/posthog/hogql/direct_sql/motherduck_adapter.pyindex 6f3f348aa50b..583cb1062339 100644--- a/posthog/hogql/direct_sql/motherduck_adapter.py+++ b/posthog/hogql/direct_sql/motherduck_adapter.py@@ -4,7 +4,6 @@ import reimport threadingfrom typing import TYPE_CHECKING, cast-import sqlparsefrom opentelemetry import tracefrom sqlparse import tokens as sqlparse_tokensfrom sqlparse.sql import Token@@ -13,7 +12,7 @@ from posthog.hogql.constants import HogQLDialectfrom posthog.hogql.direct_query_metrics import DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL, observe_direct_queryfrom posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult, parse_direct_source_configfrom posthog.hogql.direct_sql.capability import is_direct_capable-from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement+from posthog.hogql.direct_sql.raw_sql import parse_direct_statementsfrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.motherduck_connection_cache import cached_motherduck_connection@@ -134,8 +133,7 @@ def _opens_call(tokens: list[Token], index: int) -> bool:def ensure_read_only_raw_motherduck_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;")]+ statements = parse_direct_statements(sql, dialect="duckdb")if len(statements) != 1 or statements[0].get_type() != "SELECT":raise ExposedHogQLError(RAW_MOTHERDUCK_READ_ONLY_ERROR)# The connection itself is read-only (DuckDB rejects writes engine-side) and runs indiff --git a/posthog/hogql/direct_sql/mysql_adapter.py b/posthog/hogql/direct_sql/mysql_adapter.pyindex 98733d2c0897..1c0dd0b8ae1d 100644--- a/posthog/hogql/direct_sql/mysql_adapter.py+++ b/posthog/hogql/direct_sql/mysql_adapter.py@@ -1,7 +1,6 @@from typing import TYPE_CHECKING, castimport pymysql-import sqlparsefrom opentelemetry import tracefrom pymysql.constants import FIELD_TYPE as MYSQL_FIELD_TYPEfrom sqlparse import tokens as sqlparse_tokens@@ -11,7 +10,7 @@ from sshtunnel import BaseSSHTunnelForwarderErrorfrom posthog.hogql.constants import HogQLDialectfrom posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult, parse_direct_source_configfrom posthog.hogql.direct_sql.capability import is_direct_capable-from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement+from posthog.hogql.direct_sql.raw_sql import parse_direct_statementsfrom posthog.hogql.errors import ExposedHogQLErrorif TYPE_CHECKING:@@ -96,8 +95,7 @@ def _raw_mysql_token_values(statement: Statement) -> list[str]: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;")]+ statements = parse_direct_statements(sql, dialect="mysql")if len(statements) != 1 or statements[0].get_type() != "SELECT":raise ExposedHogQLError(RAW_MYSQL_READ_ONLY_ERROR)diff --git a/posthog/hogql/direct_sql/postgres_adapter.py b/posthog/hogql/direct_sql/postgres_adapter.pyindex 4fad8c571e2b..f465d96d7b11 100644--- a/posthog/hogql/direct_sql/postgres_adapter.py+++ b/posthog/hogql/direct_sql/postgres_adapter.py@@ -160,7 +160,7 @@ class PostgresAdapter:return postgres_source, configdef prepare_raw_sql(self, sql: str) -> str:- return ensure_single_direct_statement(sql)+ return ensure_single_direct_statement(sql, dialect="postgres")def execute(self, request: DirectQueryRequest) -> DirectQueryResult:source = request.sourcediff --git a/posthog/hogql/direct_sql/raw_sql.py b/posthog/hogql/direct_sql/raw_sql.pyindex fac1081ddde8..8960190e3c31 100644--- a/posthog/hogql/direct_sql/raw_sql.py+++ b/posthog/hogql/direct_sql/raw_sql.py@@ -1,9 +1,127 @@-import sqlparse+from functools import lru_cache+from typing import TYPE_CHECKING, cast++from sqlparse import tokens as sqlparse_tokens+from sqlparse.engine.grouping import group+from sqlparse.exceptions import SQLParseError+from sqlparse.lexer import tokenize+from sqlparse.sql import Statement, Tokenfrom posthog.hogql.errors import ExposedHogQLError+if TYPE_CHECKING:+ from sqlglot.tokens import (+ Token as DialectToken,+ Tokenizer,+ )+++@lru_cache(maxsize=16)+def _tokenizer_class(dialect: str, alternate_escapes: bool = False) -> type["Tokenizer"]:+ from sqlglot import Dialect # noqa: PLC0415 -- load dialect grammars only for direct queries++ base = Dialect.get_or_raise(dialect).tokenizer_class+ escapes = list(base.STRING_ESCAPES)+ if alternate_escapes:+ escapes = [escape for escape in escapes if escape != "\\"] if "\\" in escapes else [*escapes, "\\"]+ tokenizer = cast(+ "type[Tokenizer]", type("DirectQueryTokenizer", (base,), {"STRING_ESCAPES": escapes, "COMMANDS": set()})+ )+ # SQLGlot also understands template comments, which database servers do not.+ tokenizer._COMMENTS = {key: value for key, value in tokenizer._COMMENTS.items() if key != "{#"}+ return tokenizer+++def _lex_direct_sql(sql: str, dialect: str) -> list["DialectToken"]:+ from sqlglot.errors import TokenError # noqa: PLC0415 -- load dialect grammars only for direct queries++ try:+ lexed = _tokenizer_class(dialect)(dialect=dialect).tokenize(sql)+ if dialect in {"postgres", "redshift", "mysql"}:+ # Connection settings can change backslash handling. Accept either interpretation+ # only when both agree on boundaries; ordinary LIKE/regex escapes still work.+ alternate = _tokenizer_class(dialect, alternate_escapes=True)(dialect=dialect).tokenize(sql)+ if [(t.start, t.end, t.token_type) for t in lexed] != [(t.start, t.end, t.token_type) for t in alternate]:+ raise ExposedHogQLError("Raw query quoting must be unambiguous for this connection.")+ except TokenError as error:+ raise ExposedHogQLError("Raw query contains invalid quoting or comments.") from error++ if dialect == "mysql" and any(+ comment.upper().startswith(("!", "M!")) for token in lexed for comment in token.comments+ ):+ raise ExposedHogQLError("Raw MySQL queries must be read-only SELECT statements.")+ return lexed+++def _guard_tokens(token: "DialectToken", *, is_call: bool, is_qualified: bool, sql: str, dialect: str) -> list[Token]:+ from sqlglot.tokens import TokenType # noqa: PLC0415 -- load dialect grammars only for direct queries++ literal_types = {+ TokenType.STRING,+ TokenType.BIT_STRING,+ TokenType.HEX_STRING,+ TokenType.BYTE_STRING,+ TokenType.NATIONAL_STRING,+ TokenType.RAW_STRING,+ TokenType.HEREDOC_STRING,+ TokenType.UNICODE_STRING,+ }+ if token.token_type == TokenType.IDENTIFIER:+ if is_call:+ return [Token(sqlparse_tokens.Name, token.text)]+ kind = sqlparse_tokens.Name if dialect == "mysql" else sqlparse_tokens.String.Symbol+ quote = "`" if dialect == "mysql" else '"'+ return [Token(kind, quote + token.text + quote)]+ if token.token_type in literal_types:+ # ANSI_QUOTES can make a double-quoted MySQL callee an identifier.+ if dialect == "mysql" and sql[token.start] == '"' and is_call:+ return [Token(sqlparse_tokens.Name, token.text)]+ return [Token(sqlparse_tokens.String.Single, "'literal'")]+ if is_qualified and token.text.replace("$", "_").isidentifier():+ return [Token(sqlparse_tokens.Name, token.text)]+ classified = list(tokenize(token.text + ("(" if is_call else "")))+ return [Token(kind, value) for kind, value in (classified[:-1] if is_call else classified)]+++def _single_statement_tokens(sql: str, dialect: str) -> list["DialectToken"]:+ from sqlglot.tokens import TokenType # noqa: PLC0415 -- load dialect grammars only for direct queries++ statement: list[DialectToken] = []+ terminated = False+ for token in _lex_direct_sql(sql, dialect):+ if token.token_type == TokenType.SEMICOLON:+ terminated = bool(statement)+ elif terminated:+ raise ExposedHogQLError("Raw queries must contain a single statement.")+ else:+ statement.append(token)+ return statement+++def parse_direct_statements(sql: str, *, dialect: str) -> list[Statement]:+ """Build the guard's token tree using the connection's literal and comment rules.++ sqlparse still groups CTEs and classifies keywords, but never lexes raw literals,+ identifiers or comments. The original SQL, not this validation tree, is executed.+ """+ from sqlglot.tokens import TokenType # noqa: PLC0415 -- load dialect grammars only for direct queries++ lexed = _single_statement_tokens(sql, dialect)+ tokens: list[Token] = []+ for index, token in enumerate(lexed):+ is_call = index + 1 < len(lexed) and lexed[index + 1].token_type == TokenType.L_PAREN+ is_qualified = (index > 0 and lexed[index - 1].token_type == TokenType.DOT) or (+ index + 1 < len(lexed) and lexed[index + 1].token_type == TokenType.DOT+ )+ tokens.extend(_guard_tokens(token, is_call=is_call, is_qualified=is_qualified, sql=sql, dialect=dialect))+ tokens.append(Token(sqlparse_tokens.Whitespace, " "))+ try:+ return [group(Statement(tokens))] if tokens else []+ except (SQLParseError, RecursionError) as error:+ raise ExposedHogQLError("Raw query is too complex to validate. Simplify the query and try again.") from error+-def ensure_single_direct_statement(sql: str) -> str:+def ensure_single_direct_statement(sql: str, *, dialect: str) -> str:"""Reject multi-statement raw SQL.Raw queries run without bound parameters, so psycopg uses the simple query@@ -13,7 +131,5 @@ def ensure_single_direct_statement(sql: str) -> str:guard protects direct MySQL queries (PyMySQL additionally disables theMULTI_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.")+ _single_statement_tokens(sql, dialect)return sqldiff --git a/posthog/hogql/direct_sql/redshift_adapter.py b/posthog/hogql/direct_sql/redshift_adapter.pyindex c9035f4acb6e..481a03dcf926 100644--- a/posthog/hogql/direct_sql/redshift_adapter.py+++ b/posthog/hogql/direct_sql/redshift_adapter.py@@ -1,7 +1,6 @@from typing import TYPE_CHECKING, castimport psycopg-import sqlparsefrom opentelemetry import tracefrom sqlparse import tokens as sqlparse_tokensfrom sshtunnel import BaseSSHTunnelForwarderError@@ -11,7 +10,7 @@ from posthog.hogql.direct_query_metrics import DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTfrom posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult, parse_direct_source_configfrom posthog.hogql.direct_sql.capability import is_direct_capablefrom posthog.hogql.direct_sql.pgwire import postgres_error_to_message, postgres_oid_to_clickhouse_type-from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement+from posthog.hogql.direct_sql.raw_sql import parse_direct_statementsfrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.escape_sql import escape_postgres_identifier@@ -81,8 +80,7 @@ def ensure_read_only_raw_redshift_statement(sql: str) -> str:so a literal or alias like ``'DELETE'`` or a quoted column ``"pg_cancel_backend"`` isunaffected."""- sql = ensure_single_direct_statement(sql)- statements = [statement for statement in sqlparse.parse(sql) if str(statement).strip(" \t\r\n;")]+ statements = parse_direct_statements(sql, dialect="redshift")if len(statements) != 1 or statements[0].get_type() != "SELECT":raise ExposedHogQLError(RAW_REDSHIFT_READ_ONLY_ERROR)for token in statements[0].flatten():diff --git a/posthog/hogql/direct_sql/snowflake_adapter.py b/posthog/hogql/direct_sql/snowflake_adapter.pyindex 47cb6278f497..5522fb1f8a51 100644--- a/posthog/hogql/direct_sql/snowflake_adapter.py+++ b/posthog/hogql/direct_sql/snowflake_adapter.py@@ -3,7 +3,6 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING, cast-import sqlparsefrom opentelemetry import tracefrom sqlparse import tokens as sqlparse_tokens@@ -11,7 +10,7 @@ from posthog.hogql.constants import HogQLDialectfrom posthog.hogql.direct_query_metrics import DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL, observe_direct_queryfrom posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult, parse_direct_source_configfrom posthog.hogql.direct_sql.capability import is_direct_capable-from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement+from posthog.hogql.direct_sql.raw_sql import parse_direct_statementsfrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.snowflake_connection_cache import cached_snowflake_connection@@ -119,8 +118,7 @@ def validate_snowflake_account_id(account_id: str | None) -> str:def ensure_read_only_raw_snowflake_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;")]+ statements = parse_direct_statements(sql, dialect="snowflake")if len(statements) != 1 or statements[0].get_type() != "SELECT":raise ExposedHogQLError(RAW_SNOWFLAKE_READ_ONLY_ERROR)# Snowflake has no read-only session/transaction switch — the Postgres path setsdiff --git a/posthog/hogql/direct_sql/test/test_raw_sql.py b/posthog/hogql/direct_sql/test/test_raw_sql.pynew file mode 100644index 000000000000..99d8fe54c873--- /dev/null+++ b/posthog/hogql/direct_sql/test/test_raw_sql.py@@ -0,0 +1,145 @@+from collections.abc import Callable++from unittest.mock import patch++from django.test import SimpleTestCase++from parameterized import parameterized+from sqlparse.exceptions import SQLParseError++from posthog.hogql.direct_sql.bigquery_adapter import ensure_read_only_raw_bigquery_statement+from posthog.hogql.direct_sql.clickhouse_adapter import ensure_read_only_raw_clickhouse_statement+from posthog.hogql.direct_sql.motherduck_adapter import ensure_read_only_raw_motherduck_statement+from posthog.hogql.direct_sql.mysql_adapter import ensure_read_only_raw_mysql_statement+from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement+from posthog.hogql.direct_sql.redshift_adapter import ensure_read_only_raw_redshift_statement+from posthog.hogql.direct_sql.snowflake_adapter import ensure_read_only_raw_snowflake_statement+from posthog.hogql.direct_sql.trino_adapter import ensure_read_only_raw_trino_statement+from posthog.hogql.errors import ExposedHogQLError+++class TestDirectSQLQuoting(SimpleTestCase):+ @parameterized.expand(+ [+ ("postgres", r"SELECT '\\logs\\' AS label"),+ ("duckdb", r"SELECT '\logs\' AS label"),+ ("redshift", r"SELECT '\\logs\\' AS label"),+ ("trino", r"SELECT '\logs\' AS label"),+ ("mysql", r"SELECT 'folder\\report' AS label"),+ ("clickhouse", r"SELECT 'folder\\report' AS label"),+ ("snowflake", r"SELECT 'folder\\report' AS label"),+ ("bigquery", r"SELECT r'''folder\report; 'sample' ''' AS label"),+ ("postgres", "SELECT $label$one; 'two'$label$ AS label"),+ ("duckdb", "SELECT $label$one; 'two'$label$ AS label"),+ ("snowflake", "SELECT $$one; 'two'$$ AS label"),+ ("postgres", r"SELECT E'one\'two' AS label"),+ ("duckdb", r"SELECT E'one\'two' AS label"),+ ("mysql", "SELECT 17 # ; SELECT 29\n"),+ ("bigquery", 'SELECT """one; \'two\'""" AS label'),+ ("postgres", "SELECT " + " + ".join(["17"] * 1000)),+ ]+ )+ def test_accepts_dialect_literals(self, dialect: str, sql: str) -> None:+ self.assertEqual(ensure_single_direct_statement(sql, dialect=dialect), sql)++ @parameterized.expand(+ [+ (dialect,)+ for dialect in ["postgres", "duckdb", "redshift", "trino", "mysql", "clickhouse", "snowflake", "bigquery"]+ ]+ )+ def test_counts_statements_after_literals(self, dialect: str) -> None:+ sql = r"SELECT 'folder\\' AS label; SELECT 'marker' AS value"+ with self.assertRaises(ExposedHogQLError):+ ensure_single_direct_statement(sql, dialect=dialect)++ @parameterized.expand(+ [+ ("postgres", "SELECT 'unfinished"),+ ("duckdb", "SELECT $label$unfinished"),+ ("trino", "SELECT /* unfinished"),+ ("bigquery", 'SELECT """unfinished'),+ ("postgres", "SELECT 17 {# ; SELECT 29 #}"),+ ("mysql", "SELECT 17--2; SELECT 29"),+ ("postgres", r"SELECT 'one\'two' AS label"),+ ("redshift", r"SELECT 'one\'two' AS label"),+ ("mysql", r"SELECT 'one\'two' AS label"),+ ]+ )+ def test_rejects_invalid_or_ambiguous_boundaries(self, dialect: str, sql: str) -> None:+ with self.assertRaises(ExposedHogQLError):+ ensure_single_direct_statement(sql, dialect=dialect)++ @parameterized.expand([("postgres",), ("redshift",), ("mysql",)])+ def test_requires_consistent_session_quoting(self, dialect: str) -> None:+ with self.assertRaisesMessage(ExposedHogQLError, "quoting must be unambiguous"):+ ensure_single_direct_statement(r"SELECT '\' AS label -- '", dialect=dialect)++ @parameterized.expand([("grouping_limit", SQLParseError), ("recursion_limit", RecursionError)])+ def test_exposes_grouping_errors(self, _name: str, error: type[Exception]) -> None:+ with patch("posthog.hogql.direct_sql.raw_sql.group", side_effect=error("limit reached")):+ with self.assertRaisesMessage(ExposedHogQLError, "too complex to validate"):+ ensure_read_only_raw_motherduck_statement("SELECT 17")++ @parameterized.expand(+ [+ ("duckdb", ensure_read_only_raw_motherduck_statement, "read_text('example.txt')"),+ ("clickhouse", ensure_read_only_raw_clickhouse_statement, "file('example.csv', 'CSV')"),+ ("redshift", ensure_read_only_raw_redshift_statement, "set_config('example', 'value', false)"),+ ("snowflake", ensure_read_only_raw_snowflake_statement, "last_query_id()"),+ ("mysql", ensure_read_only_raw_mysql_statement, "load_file('example.txt')"),+ ("duckdb_quoted", ensure_read_only_raw_motherduck_statement, "\"read_text\"('example.txt')"),+ ("clickhouse_quoted", ensure_read_only_raw_clickhouse_statement, "\"file\"('example.csv', 'CSV')"),+ ("redshift_quoted", ensure_read_only_raw_redshift_statement, "\"set_config\"('example', 'value', false)"),+ ("snowflake_quoted", ensure_read_only_raw_snowflake_statement, '"LAST_QUERY_ID"()'),+ ("snowflake_system_quoted", ensure_read_only_raw_snowflake_statement, '"SYSTEM$EXAMPLE"()'),+ ("mysql_quoted", ensure_read_only_raw_mysql_statement, "`load_file`('example.txt')"),+ ]+ )+ def test_checks_functions_after_literals(self, _name: str, validate: Callable[[str], str], call: str) -> None:+ sql = r"SELECT 'folder\\' AS label, " + call + " AS value, 'marker' AS note"+ with self.assertRaises(ExposedHogQLError):+ validate(sql)++ @parameterized.expand(+ [+ ("duckdb", ensure_read_only_raw_motherduck_statement),+ ("clickhouse", ensure_read_only_raw_clickhouse_statement),+ ("redshift", ensure_read_only_raw_redshift_statement),+ ("snowflake", ensure_read_only_raw_snowflake_statement),+ ("mysql", ensure_read_only_raw_mysql_statement),+ ("trino", ensure_read_only_raw_trino_statement),+ ("bigquery", ensure_read_only_raw_bigquery_statement),+ ("mysql_quoted_into", ensure_read_only_raw_mysql_statement, "SELECT `INTO` FROM example_rows"),+ ("mysql_quoted_alias", ensure_read_only_raw_mysql_statement, "SELECT `FOR` AS `UPDATE` FROM example_rows"),+ (+ "qualified_keyword",+ ensure_read_only_raw_motherduck_statement,+ 'SELECT example.update FROM (SELECT 17 AS "update") AS example',+ ),+ (+ "keyword_qualifier",+ ensure_read_only_raw_motherduck_statement,+ 'SELECT update.value FROM (SELECT 17 AS value) AS "update"',+ ),+ ]+ )+ def test_preserves_read_only_queries(+ self,+ _name: str,+ validate: Callable[[str], str],+ sql: str = r"WITH labels AS (SELECT 'folder\\report' AS label) SELECT * FROM labels WHERE label LIKE '%\_%'",+ ) -> None:+ self.assertEqual(validate(sql), sql)++ @parameterized.expand(+ [+ ("inline", "SELECT 17 /*! + 29 */"),+ ("after_terminator", "SELECT 17; /*! SELECT 29 */"),+ ("mariadb", "SELECT 17 /*M! + 29 */"),+ ("quoted_call", "SELECT \"load_file\"('example.txt')"),+ ]+ )+ def test_rejects_mysql_special_forms(self, _name: str, sql: str) -> None:+ with self.assertRaises(ExposedHogQLError):+ ensure_read_only_raw_mysql_statement(sql)diff --git a/posthog/hogql/direct_sql/trino_adapter.py b/posthog/hogql/direct_sql/trino_adapter.pyindex 1477a997cb5a..77e136b02961 100644--- a/posthog/hogql/direct_sql/trino_adapter.py+++ b/posthog/hogql/direct_sql/trino_adapter.py@@ -6,7 +6,6 @@ from collections.abc import Iteratorfrom contextlib import AbstractContextManager, contextmanagerfrom typing import TYPE_CHECKING, Any, cast-import sqlparseimport structlogfrom opentelemetry import tracefrom sqlparse import tokens as sqlparse_tokens@@ -15,7 +14,7 @@ from posthog.hogql.constants import HogQLDialectfrom posthog.hogql.direct_query_metrics import DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL, observe_direct_queryfrom posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult, parse_direct_source_configfrom posthog.hogql.direct_sql.capability import is_direct_capable-from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement+from posthog.hogql.direct_sql.raw_sql import parse_direct_statementsfrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.timings import HogQLTimingsfrom posthog.hogql.trino_parameters import convert_pyformat_placeholders@@ -45,8 +44,7 @@ DIRECT_TRINO_TIMEOUT_ERROR = "Trino query timed out."def ensure_read_only_raw_trino_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;")]+ statements = parse_direct_statements(sql, dialect="trino")if len(statements) != 1 or statements[0].get_type() != "SELECT":raise ExposedHogQLError(RAW_TRINO_READ_ONLY_ERROR)for token in statements[0].flatten():diff --git a/posthog/hogql/query.py b/posthog/hogql/query.pyindex cfc062a67e6b..100c31972e08 100644--- a/posthog/hogql/query.py+++ b/posthog/hogql/query.py@@ -506,7 +506,8 @@ class HogQLQueryExecutor:context=direct_context,dialect=dialect,pretty=self.pretty if self.pretty is not None else True,- )+ ),+ dialect=dialect,)self.direct_context = direct_contextself.direct_values = direct_context.values@@ -590,7 +591,7 @@ class HogQLQueryExecutor:self.hogql = transpiled.hogqlself.print_columns = list(transpiled.print_columns)- self.direct_sql = ensure_single_direct_statement(transpiled.sql)+ self.direct_sql = ensure_single_direct_statement(transpiled.sql, dialect="trino")self.direct_values = transpiled.valuesself.direct_source_id = str(source.id)self.direct_dialect = "trino"diff --git a/posthog/hogql/test/test_direct_postgres_query.py b/posthog/hogql/test/test_direct_postgres_query.pyindex da27cdf2ea56..148289eeb88c 100644--- a/posthog/hogql/test/test_direct_postgres_query.py+++ b/posthog/hogql/test/test_direct_postgres_query.py@@ -1322,7 +1322,7 @@ class TestDirectPostgresQuery(APIBaseTest):)def test_ensure_single_direct_statement_rejects_multi_statement(self, _name: str, sql: str):with self.assertRaises(ExposedHogQLError):- ensure_single_direct_statement(sql)+ ensure_single_direct_statement(sql, dialect="postgres")@parameterized.expand([@@ -1335,7 +1335,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)+ self.assertEqual(ensure_single_direct_statement(sql, dialect="postgres"), sql)@patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_send_raw_query_rejects_multi_statement_before_execution(self, mock_connect):diff --git a/pyproject.toml b/pyproject.tomlindex 83f540bdc3a3..8a8307672246 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -221,6 +221,7 @@ dependencies = ["posthog-hogland==0.4.1","requests-oauthlib~=2.0.0","adlfs~=2026.8.0",+ "sqlglot==30.25.0",][dependency-groups]diff --git a/uv.lock b/uv.lockindex 7b2b4a2e6f4b..e8d49a556320 100644--- a/uv.lock+++ b/uv.lock@@ -6061,6 +6061,7 @@ dependencies = [{ name = "snowflake-connector-python" },{ name = "social-auth-app-django" },{ name = "social-auth-core" },+ { name = "sqlglot" },{ name = "sqlparse" },{ name = "sshtunnel" },{ name = "statshog" },@@ -6360,6 +6361,7 @@ requires-dist = [{ name = "snowflake-connector-python", specifier = "==4.7.5" },{ name = "social-auth-app-django", specifier = "~=5.9.0" },{ name = "social-auth-core", specifier = "~=4.8.7" },+ { name = "sqlglot", specifier = "==30.25.0" },{ name = "sqlparse", specifier = "==0.5.4" },{ name = "sshtunnel", specifier = "==0.4.0" },{ name = "statshog", specifier = "==1.0.6" },@@ -8263,11 +8265,11 @@ wheels = [[[package]]name = "sqlglot"-version = "28.5.0"+version = "30.25.0"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/bf/8c/a4d24b6103305467506c1dea9c3ca8dc92773a91bae246c2517c256a0cf9/sqlglot-28.5.0.tar.gz", hash = "sha256:b3213b3e867dcc306074f1c90480aeee89a0e635cf0dfe70eb4a3af7b61972e6", size = 5652688, upload-time = "2025-12-17T23:38:00.121Z" }+sdist = { url = "https://files.pythonhosted.org/packages/ff/bd/3885516929bfea13c635d5721c468e664defe56a89c073ecf8640f5a5c8a/sqlglot-30.25.0.tar.gz", hash = "sha256:d2d6e4d4865a210b1e33a801b105a6782ef12280cc2b6d0969bdc2634aef427a", size = 6154689, upload-time = "2026-10-26T15:11:29.706Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/ec/f7/6a7effd2526f64bcb0d2264c0dbebc7f8508add3f2c0748540d1448a24a3/sqlglot-28.5.0-py3-none-any.whl", hash = "sha256:5798bfdb6e9bc36c964e6c64d7222624d98b2631cc20f44628a82eba7cf7b4bf", size = 561086, upload-time = "2025-12-17T23:37:57.972Z" },+ { url = "https://files.pythonhosted.org/packages/5f/44/a510d696c082e245832348bcfca5de9adfefd65829cd96fa5bf39244ca7b/sqlglot-30.25.0-py3-none-any.whl", hash = "sha256:7d5a292d5f61b7fc860e65a8fa41083c726db0e27fb6efb224cca63c3a5980f7", size = 798009, upload-time = "2026-10-26T15:11:27.897Z" },][[package]]