: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): bind snowflake datetime format strings (#102803)
Marius Andra8186c0db1805
diff --git a/docs/published/handbook/engineering/databases/hogql-python.md b/docs/published/handbook/engineering/databases/hogql-python.mdindex 47062ffbbf3d..74cbab5e1af5 100644--- a/docs/published/handbook/engineering/databases/hogql-python.md+++ b/docs/published/handbook/engineering/databases/hogql-python.md@@ -75,6 +75,12 @@ query_result.columns == ['event', 'timestamp'] # might be useful if you selectYou can mix and match `parse_expr` and `ast` nodes as you please. The example above _still_ took a shortcut for the where clause because it was easier to write.+## Snowflake date formatting++For direct Snowflake queries, `formatDateTime` requires a literal format string and translates supported strftime specifiers into Snowflake format elements.+The printer binds the translated format as a query parameter, preserving literal quotes and backslashes in the parameter value.+Pass the printed SQL and `HogQLContext.values` together to the database driver.+## Database schema and featuresThe HogQL database schema is in flux. You will soon be able to explore it in the [PostHog app itself](https://github.com/PostHog/posthog/pull/14591).diff --git a/posthog/hogql/printer/snowflake.py b/posthog/hogql/printer/snowflake.pyindex 2e8bba1289b7..2d0a9b7f1a65 100644--- a/posthog/hogql/printer/snowflake.py+++ b/posthog/hogql/printer/snowflake.py@@ -225,10 +225,8 @@ class SnowflakePrinter(PostgresPrinter):raise QueryError(f"Array slices are not supported {self._dialect_error_suffix()}; use ARRAY_SLICE().")def visit_call(self, node: ast.Call) -> str:- # dateDiff / formatDateTime can't be plain handlers: their first argument- # (date part / format string) must be inlined as a literal, but by the time- # a handler runs it has already been bound as a parameter. Intercept here,- # where the raw AST Constant is still available.+ # Validate dateDiff units and translate formatDateTime formats before+ # generic handlers bind their AST constants as parameters.name = node.name.lower()if name == "datediff":return self._visit_date_diff(node)@@ -257,11 +255,8 @@ class SnowflakePrinter(PostgresPrinter):raise QueryError(f"formatDateTime requires a literal format string {self._dialect_error_suffix()}.")snowflake_format = self._translate_strftime_format(format_node.value)time_sql = self.visit(node.args[0])- # The format is inlined into a single-quoted SQL literal, so any `'` it carries (a literal- # quote the user escaped as `''` in HogQL) must be re-escaped as `''` — otherwise it closes- # the string early, breaking the query or allowing injection.- escaped_format = snowflake_format.replace("'", "''")- return f"TO_CHAR({time_sql}, '{escaped_format}')"+ format_sql = self.context.add_value(snowflake_format)+ return f"TO_CHAR({time_sql}, {format_sql})"def _translate_strftime_format(self, fmt: str) -> str:# Translate ClickHouse/strftime %-specifiers to Snowflake TO_CHAR elements.diff --git a/posthog/hogql/printer/test/test_snowflake_printer.py b/posthog/hogql/printer/test/test_snowflake_printer.pyindex 85391c4e1cd7..cb0c69252be7 100644--- a/posthog/hogql/printer/test/test_snowflake_printer.py+++ b/posthog/hogql/printer/test/test_snowflake_printer.py@@ -12,7 +12,7 @@ from posthog.hogql.errors import QueryErrorfrom posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.printer import prepare_and_print_ast, prepare_ast_for_printing, print_prepared_ast-SNOWFLAKE_EMIT_CASES: list[tuple[str, str, str]] = [+SNOWFLAKE_EMIT_CASES: list[tuple[str, str, str] | tuple[str, str, str, dict[str, str]]] = [# Casts (Snowflake type synonyms; no UUID type → VARCHAR)("toString", "toString(1)", "CAST(1 AS VARCHAR)"),("toFloat", "toFloat('1.5')", "CAST(%(hogql_val_0)s AS DOUBLE)"),@@ -58,30 +58,43 @@ SNOWFLAKE_EMIT_CASES: list[tuple[str, str, str]] = [("toIntervalDay", "toIntervalDay(7)", "INTERVAL '7 day'"),("addDays", "addDays(now(), 7)", "DATEADD('day', 7, CURRENT_TIMESTAMP())"),("subtractMonths", "subtractMonths(now(), 3)", "DATEADD('month', -(3), CURRENT_TIMESTAMP())"),- # dateDiff / formatDateTime — unit / format inlined as a literal("dateDiff", "dateDiff('day', now(), now())", "DATEDIFF('day', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP())"),("formatDateTime","formatDateTime(now(), '%Y-%m-%d %H:%M:%S')",- "TO_CHAR(CURRENT_TIMESTAMP(), 'YYYY-MM-DD HH24:MI:SS')",+ "TO_CHAR(CURRENT_TIMESTAMP(), %(hogql_val_0)s)",+ {"hogql_val_0": "YYYY-MM-DD HH24:MI:SS"},),# A literal double-quote is escaped as "" inside the quoted run, not dropped.("formatDateTime_escapes_literal_quote","formatDateTime(now(), '%Y\"q\"')",- 'TO_CHAR(CURRENT_TIMESTAMP(), \'YYYY"""q"""\')',+ "TO_CHAR(CURRENT_TIMESTAMP(), %(hogql_val_0)s)",+ {"hogql_val_0": 'YYYY"""q"""'},),("formatDateTime_escapes_lone_quote","formatDateTime(now(), '%H\"%M')",- 'TO_CHAR(CURRENT_TIMESTAMP(), \'HH24""""MI\')',+ "TO_CHAR(CURRENT_TIMESTAMP(), %(hogql_val_0)s)",+ {"hogql_val_0": 'HH24""""MI'},),- # A literal single-quote (escaped `''` in HogQL) must be re-escaped as `''` so it can't close- # the surrounding SQL string literal — guards the formatDateTime injection vector.("formatDateTime_escapes_single_quote","formatDateTime(now(), '%Y''T''%H')",- "TO_CHAR(CURRENT_TIMESTAMP(), 'YYYY\"''T''\"HH24')",+ "TO_CHAR(CURRENT_TIMESTAMP(), %(hogql_val_0)s)",+ {"hogql_val_0": "YYYY\"'T'\"HH24"},+ ),+ (+ "formatDateTime_backslash_and_quote",+ r"formatDateTime(now(), '\\''')",+ "TO_CHAR(CURRENT_TIMESTAMP(), %(hogql_val_0)s)",+ {"hogql_val_0": "\\'"},+ ),+ (+ "formatDateTime_literal_text_backslash_and_quote",+ r"formatDateTime(now(), '%Y label\\''%H')",+ "TO_CHAR(CURRENT_TIMESTAMP(), %(hogql_val_0)s)",+ {"hogql_val_0": 'YYYY" label\\\'"HH24'},),# Conditional / null("if", "if(1, 2, 3)", "CASE WHEN 1 THEN 2 ELSE 3 END"),@@ -179,8 +192,13 @@ class TestSnowflakePrinter(BaseTest):)@parameterized.expand(SNOWFLAKE_EMIT_CASES)- def test_snowflake_emit(self, _name: str, hogql_expr: str, expected: str):- self.assertEqual(self._expr(hogql_expr), expected)+ def test_snowflake_emit(+ self, _name: str, hogql_expr: str, expected: str, expected_values: Optional[dict[str, str]] = None+ ) -> None:+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ self.assertEqual(self._expr(hogql_expr, context), expected)+ if expected_values is not None:+ self.assertEqual(context.values, expected_values)@parameterized.expand([