: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
refactor(data-warehouse): add shared helpers to SQLSource(Implementation) (#59697)
Daniel RC60a50754d0c5
diff --git a/posthog/temporal/data_imports/sources/common/sql/base.py b/posthog/temporal/data_imports/sources/common/sql/base.pyindex c0f4e9396573..464cb7e130f3 100644--- a/posthog/temporal/data_imports/sources/common/sql/base.py+++ b/posthog/temporal/data_imports/sources/common/sql/base.py@@ -44,6 +44,36 @@ class SQLSource(SimpleSource[ConfigType], Generic[ConfigType]):def get_implementation(self) -> SQLSourceImplementation[ConfigType, Any, Any]:"""The driver-layer implementation for this source."""+ @classmethod+ def default_non_retryable_errors(cls) -> dict[str, str | None]:+ """Non-retryable error patterns shared by multiple SQL sources.++ Subclasses opt in by merging this into their own+ `get_non_retryable_errors` return dict, e.g.+ `return {**self.default_non_retryable_errors(), ...}`. The base+ `SQLSource` itself does not call this — every existing source's+ behavior is preserved until it explicitly opts in.++ The two entries here are the ones currently duplicated across+ ≥2 SQL sources today:++ - "Source column type changed" (MySQL, MSSQL, Snowflake,+ BigQuery, Redshift)+ - "Cannot build decimal array from values" (MySQL, MSSQL)+ """+ return {+ "Source column type changed": (+ "A column's type changed in your source database (for example an integer column was widened to bigint) "+ "and no longer fits the type we stored. We can't widen an existing column in place — please reset and "+ "fully re-sync this table to adopt the new type."+ ),+ "Cannot build decimal array from values": (+ "One of your numeric columns contains values that exceed our decimal storage limits "+ "(max precision 76, max scale 32). Please constrain the column with a lower precision/scale, "+ "cast it to text in a view, or round the values at the source."+ ),+ }+def _default_primary_key_from_columns(self, columns: list[tuple[str, str, bool]]) -> list[str] | None:"""Fallback: use `id` when the driver didn't detect a PK but one is present.diff --git a/posthog/temporal/data_imports/sources/common/sql/implementation.py b/posthog/temporal/data_imports/sources/common/sql/implementation.pyindex 4063849eff10..b7303a3ff4e9 100644--- a/posthog/temporal/data_imports/sources/common/sql/implementation.py+++ b/posthog/temporal/data_imports/sources/common/sql/implementation.py@@ -232,6 +232,35 @@ class SQLSourceImplementation(Generic[ConfigT, ConnT, CursorT], ABC):"""return None+ def get_rows_to_sync(+ self,+ cursor: CursorT,+ inner_query: str,+ inner_query_args: Any,+ logger: FilteringBoundLogger,+ ) -> int:+ """Count rows the given `inner_query` will produce. Returns 0 on error.++ Mirrors the shape shared by MySQL, MSSQL, and Snowflake today.+ Drivers can still override — MySQL injects a+ `/*+ MAX_EXECUTION_TIME(60000) */` optimizer hint, for example —+ but the default suits any driver whose `COUNT(*) FROM (...)` is+ not pathologically slow.+ """+ try:+ cursor.execute(f"SELECT COUNT(*) FROM ({inner_query}) as t", inner_query_args)+ row = cursor.fetchone()+ if row is None:+ logger.debug("get_rows_to_sync: No results returned. Using 0 as rows to sync")+ return 0+ rows_to_sync_int = int(row[0] or 0)+ logger.debug(f"get_rows_to_sync: rows_to_sync_int={rows_to_sync_int}")+ return rows_to_sync_int+ except Exception as e:+ logger.debug(f"get_rows_to_sync: Error: {e}. Using 0 as rows to sync", exc_info=e)+ capture_exception(e)+ return 0+def fetch_average_row_size(self,cursor: CursorT,diff --git a/posthog/temporal/data_imports/sources/common/sql/tests/test_base.py b/posthog/temporal/data_imports/sources/common/sql/tests/test_base.pyindex 955d56ccce5f..d6c9ed0da7b6 100644--- a/posthog/temporal/data_imports/sources/common/sql/tests/test_base.py+++ b/posthog/temporal/data_imports/sources/common/sql/tests/test_base.py@@ -218,3 +218,26 @@ class TestGetSchemas:assert schema.source_schema == "public"assert schema.source_table_name == "original_t"assert schema.supports_cdc is True+++class TestDefaultNonRetryableErrors:+ @pytest.mark.parametrize(+ "key,expected_substring",+ [+ ("Source column type changed", "reset and fully re-sync"),+ ("Cannot build decimal array from values", "decimal storage limits"),+ ],+ )+ def test_includes_expected_entry(self, key: str, expected_substring: str) -> None:+ # Calling without an instance proves the classmethod shape too — the+ # eventual subclass call site is `cls.default_non_retryable_errors()`.+ errors = SQLSource.default_non_retryable_errors()+ assert key in errors+ message = errors[key]+ assert message is not None+ assert expected_substring in message++ def test_returns_exactly_the_two_shared_entries(self) -> None:+ errors = SQLSource.default_non_retryable_errors()+ assert isinstance(errors, dict)+ assert len(errors) == 2diff --git a/posthog/temporal/data_imports/sources/common/sql/tests/test_implementation.py b/posthog/temporal/data_imports/sources/common/sql/tests/test_implementation.pyindex 5a106f4e4478..074860e2ff30 100644--- a/posthog/temporal/data_imports/sources/common/sql/tests/test_implementation.py+++ b/posthog/temporal/data_imports/sources/common/sql/tests/test_implementation.py@@ -165,3 +165,46 @@ class TestGetChunkSize:cursor = MagicMock()impl.get_chunk_size(cursor, "db", "t", "SELECT x FROM y", {"a": 1}, logger)assert impl.fetch_average_row_size_calls == [(cursor, "db", "t", "SELECT x FROM y", {"a": 1})]+++class TestGetRowsToSync:+ def test_returns_count_from_cursor(self, logger):+ impl = _FakeImplementation()+ cursor = MagicMock()+ cursor.fetchone.return_value = (42,)+ result = impl.get_rows_to_sync(cursor, "SELECT 1", None, logger)+ assert result == 42++ def test_wraps_query_in_count_subquery(self, logger):+ impl = _FakeImplementation()+ cursor = MagicMock()+ cursor.fetchone.return_value = (7,)+ impl.get_rows_to_sync(cursor, "SELECT x FROM y", {"a": 1}, logger)+ cursor.execute.assert_called_once_with("SELECT COUNT(*) FROM (SELECT x FROM y) as t", {"a": 1})++ @pytest.mark.parametrize(+ "configure_cursor",+ [+ pytest.param(lambda c: setattr(c, "fetchone", MagicMock(return_value=None)), id="fetchone_none"),+ pytest.param(lambda c: setattr(c, "fetchone", MagicMock(return_value=(None,))), id="count_null"),+ pytest.param(+ lambda c: setattr(c, "execute", MagicMock(side_effect=RuntimeError("connection lost"))),+ id="execute_exception",+ ),+ pytest.param(+ lambda c: setattr(c, "fetchone", MagicMock(side_effect=RuntimeError("read failed"))),+ id="fetchone_exception",+ ),+ ],+ )+ def test_returns_zero(self, logger, configure_cursor):+ impl = _FakeImplementation()+ cursor = MagicMock()+ configure_cursor(cursor)+ assert impl.get_rows_to_sync(cursor, "SELECT 1", None, logger) == 0++ def test_casts_count_to_int(self, logger):+ impl = _FakeImplementation()+ cursor = MagicMock()+ cursor.fetchone.return_value = ("123",)+ assert impl.get_rows_to_sync(cursor, "SELECT 1", None, logger) == 123