: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(snowflake): allow quoted identifiers with spaces in incremental sync (#88842)
Tom Owers08749678f842
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/identifiers.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/identifiers.pyindex be7245ed9fc0..3eac75f3e1a4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/identifiers.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/identifiers.py@@ -2,18 +2,22 @@The single place where *unparameterized* strings (schema / table / columnnames) are allowed to reach a SQL query. Every SQL source must go through-an `IdentifierQuoter` implementation so the allowlist check is uniform and-cannot be bypassed by subclasses. The allowlist is strict (alphanumeric,-`_`, `-`, `.`, `$`, `@`) — anything else raises `InvalidIdentifierError`.--The allowlist is derived from today's `mysql._sanitize_identifier` (the-only driver that already validated identifiers) but is intentionally a-superset: the old MySQL helper rejected identifiers that started with a-digit followed by letters (e.g. `"23abc"`), whereas this allowlist accepts-any mix of `_ALLOWED_CHARACTERS`. Quoted MySQL identifiers legitimately-allow digit prefixes, and every other SQL dialect we target treats quoted-identifiers as opaque strings — so the widening is a correctness-improvement rather than a behavior regression.+an `IdentifierQuoter` implementation so validation is uniform and cannot be+bypassed by subclasses.++The backtick quoter (MySQL/MariaDB/ClickHouse) uses a strict allowlist+(alphanumeric, `_`, `-`, `.`, `$`, `@`) derived from today's+`mysql._sanitize_identifier` — the only driver that already validated+identifiers. It's intentionally a superset: the old MySQL helper rejected+identifiers that started with a digit followed by letters (e.g. `"23abc"`),+whereas this allowlist accepts any mix of `_ALLOWED_CHARACTERS`. Quoted+MySQL identifiers legitimately allow digit prefixes, so the widening is a+correctness improvement rather than a behavior regression.++The bracket quoter (T-SQL) and ANSI quoter (Postgres/Redshift/Snowflake/+DuckDB) instead escape their dialect's own delimiter, because their delimited+identifiers legitimately contain spaces and punctuation the allowlist would+reject — see each class's docstring below."""from __future__ import annotations@@ -98,11 +102,29 @@ class BacktickIdentifierQuoter(_BaseQuoter):class AnsiIdentifierQuoter(_BaseQuoter):- """ANSI SQL quoting with double-quotes (Postgres, Redshift, Snowflake)."""+ """ANSI SQL quoting with double-quotes (Postgres, Redshift, Snowflake, DuckDB).++ Unlike the backtick quoter, this one does NOT use the strict alphanumeric+ allowlist. ANSI delimited identifiers legitimately contain spaces and+ other punctuation that the allowlist rejects (real Snowflake schemas have+ columns like `Date Established`), and the allowlist crashed the import on+ them. Double-quote quoting makes any such name safe by doubling a literal+ embedded `"` — the standard ANSI SQL escaping rule — so that is the actual+ safety boundary here. Control characters are still rejected since quoting+ can't neutralise them and they never appear in a real identifier.+ """_open = '"'_close = '"'+ def quote(self, identifier: str) -> str:+ if not identifier:+ raise InvalidIdentifierError("Identifier may not be empty")+ if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in identifier):+ raise InvalidIdentifierError(f"Invalid SQL identifier: {identifier!r}")+ escaped = identifier.replace('"', '""')+ return f"{self._open}{escaped}{self._close}"+class BracketIdentifierQuoter(_BaseQuoter):"""T-SQL quoting with square brackets (MSSQL, Azure SQL Server).diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_identifiers.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_identifiers.pyindex 26c77a8034fc..ab04b945fd61 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_identifiers.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_identifiers.py@@ -64,20 +64,41 @@ class TestBacktickIdentifierQuoter:class TestAnsiIdentifierQuoter:quoter = AnsiIdentifierQuoter()- def test_quotes_with_double_quotes(self) -> None:- assert self.quoter.quote("my_table") == '"my_table"'+ @pytest.mark.parametrize(+ "identifier,expected",+ [+ ("my_table", '"my_table"'),+ # ANSI delimited identifiers accept characters the alphanumeric+ # allowlist rejects; this is a real Snowflake column name.+ ("Date Established", '"Date Established"'),+ # A literal `"` is escaped by doubling, the standard ANSI rule.+ ('a"b', '"a""b"'),+ ('users"; DROP TABLE x; --', '"users""; DROP TABLE x; --"'),+ ],+ )+ def test_quotes_with_double_quotes(self, identifier: str, expected: str) -> None:+ assert self.quoter.quote(identifier) == expecteddef test_quote_qualified_with_double_quotes(self) -> None:assert self.quoter.quote_qualified("public", "users") == '"public"."users"'- def test_rejects_sql_injection_attempt(self) -> None:+ @pytest.mark.parametrize(+ "identifier",+ [+ "a\nb",+ "a\tb",+ "a\x00b",+ "",+ ],+ )+ def test_rejects_unsafe_identifiers(self, identifier: str) -> None:with pytest.raises(InvalidIdentifierError):- self.quoter.quote('users"; DROP TABLE x; --')+ self.quoter.quote(identifier)def test_invalid_identifier_error_is_a_value_error(self) -> None:"""Back-compat: code catching plain ValueError still works."""with pytest.raises(ValueError):- self.quoter.quote("bad;id")+ self.quoter.quote("a\nb")class TestBracketIdentifierQuoter:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.pyindex fe2c0df1ddc8..fcc206c7d088 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py@@ -176,6 +176,12 @@ class TestBuildQuery:_, params = _build_query("DB", "PUBLIC", "t", True, "created_at", IncrementalFieldType.DateTime, None)assert params[1] is not None+ def test_incremental_field_with_space_is_quoted_not_rejected(self):+ # Real Snowflake column names can contain spaces (e.g. "Date Established").+ sql, _ = _build_query("DB", "PUBLIC", "t", True, "Date Established", IncrementalFieldType.DateTime, None)+ assert 'WHERE "Date Established"' in sql+ assert 'ORDER BY "Date Established" ASC' in sql+class TestBuildQueryRowFilters:def _filter(self, column, operator, value, category=ColumnTypeCategory.INTEGER):