: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): collapse mysql driver into SQLSourceImplementation (#55946)
Tom Owers275005c778d9
diff --git a/posthog/temporal/data_imports/sources/common/mixins.py b/posthog/temporal/data_imports/sources/common/mixins.pyindex 56e7c45ffbfb..f77b2c50ac38 100644--- a/posthog/temporal/data_imports/sources/common/mixins.py+++ b/posthog/temporal/data_imports/sources/common/mixins.py@@ -61,40 +61,54 @@ def _is_host_safe(host: str, team_id: int) -> tuple[bool, str | None]:return True, None-class SSHTunnelMixin:- """Mixin for sources that support SSH tunnels"""+@contextmanager+def open_ssh_tunnel(config) -> Generator[tuple[str, int], Any, None]:+ """Yield `(host, port)` for a database connection, going through an SSH tunnel if configured."""+ if hasattr(config, "ssh_tunnel") and config.ssh_tunnel and config.ssh_tunnel.enabled:+ ssh_tunnel = SSHTunnel.from_config(config.ssh_tunnel)- @contextmanager- def with_ssh_tunnel(self, config) -> Generator[tuple[str, int], Any, None]:- if hasattr(config, "ssh_tunnel") and config.ssh_tunnel and config.ssh_tunnel.enabled:- ssh_tunnel = SSHTunnel.from_config(config.ssh_tunnel)+ with ssh_tunnel.get_tunnel(config.host, config.port) as tunnel:+ if tunnel is None:+ raise Exception("Can't open tunnel to SSH server")++ yield tunnel.local_bind_host, tunnel.local_bind_port+ else:+ yield config.host, config.port++def make_ssh_tunnel_factory(config) -> Callable[[], _GeneratorContextManager[tuple[str, int]]]:+ """Return a zero-arg factory that opens a fresh `open_ssh_tunnel(config)` context each call.++ The dlt pipeline factories accept a tunnel-factory callable so the tunnel can be+ (re)opened inside the pipeline process.+ """+ if hasattr(config, "ssh_tunnel") and config.ssh_tunnel and config.ssh_tunnel.enabled:+ ssh_tunnel = SSHTunnel.from_config(config.ssh_tunnel)++ @contextmanager+ def with_ssh_func():with ssh_tunnel.get_tunnel(config.host, config.port) as tunnel:if tunnel is None:raise Exception("Can't open tunnel to SSH server")-yield tunnel.local_bind_host, tunnel.local_bind_port- else:- yield config.host, config.port- def make_ssh_tunnel_func(self, config) -> Callable[[], _GeneratorContextManager[tuple[str, int]]]:- if hasattr(config, "ssh_tunnel") and config.ssh_tunnel and config.ssh_tunnel.enabled:- ssh_tunnel = SSHTunnel.from_config(config.ssh_tunnel)+ return with_ssh_func- @contextmanager- def with_ssh_func():- with ssh_tunnel.get_tunnel(config.host, config.port) as tunnel:- if tunnel is None:- raise Exception("Can't open tunnel to SSH server")- yield tunnel.local_bind_host, tunnel.local_bind_port+ @contextmanager+ def without_ssh_func():+ yield config.host, config.port- return with_ssh_func+ return without_ssh_func- @contextmanager- def without_ssh_func():- yield config.host, config.port- return without_ssh_func+class SSHTunnelMixin:+ """Mixin for sources that support SSH tunnels"""++ def with_ssh_tunnel(self, config) -> _GeneratorContextManager[tuple[str, int]]:+ return open_ssh_tunnel(config)++ def make_ssh_tunnel_func(self, config) -> Callable[[], _GeneratorContextManager[tuple[str, int]]]:+ return make_ssh_tunnel_factory(config)def ssh_tunnel_is_valid(self, config, team_id: int) -> tuple[bool, str | None]:if hasattr(config, "ssh_tunnel") and config.ssh_tunnel and config.ssh_tunnel.enabled:diff --git a/posthog/temporal/data_imports/sources/common/sql/__init__.py b/posthog/temporal/data_imports/sources/common/sql/__init__.pynew file mode 100644index 000000000000..a60d56a38497--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/sql/__init__.py@@ -0,0 +1,56 @@+"""Shared plumbing for SQL-based data-import sources.++This package concentrates the orchestration and safety primitives that used to+be copy-pasted across every SQL source (`postgres/postgres.py`, `mysql/mysql.py`,+etc). A new SQL source should be implementable by subclassing `SQLSource` and+providing a small set of driver-specific hooks — connection, identifier quoter,+incremental-field filter, and schema/row discovery.++Only the types that existed in the old `common/sql.py` are re-exported from+this package's root so existing `from ...common.sql import Column, Table`+imports keep working. New callers should import from the submodules directly.+"""++from posthog.temporal.data_imports.sources.common.sql.identifiers import (+ AnsiIdentifierQuoter,+ BacktickIdentifierQuoter,+ IdentifierQuoter,+ InvalidIdentifierError,+)+from posthog.temporal.data_imports.sources.common.sql.implementation import TableStats+from posthog.temporal.data_imports.sources.common.sql.incremental import (+ IncrementalFieldFilter,+ build_incremental_fields,+ initial_value_for_incremental_type,+)+from posthog.temporal.data_imports.sources.common.sql.query_builder import ParamStyle, SafeSQL, SelectQueryBuilder+from posthog.temporal.data_imports.sources.common.sql.types import (+ Column,+ ColumnType,+ Table,+ TableBase,+ TableReference,+ TableSchemas,+ resolve_detected_primary_keys,+)++__all__ = [+ "AnsiIdentifierQuoter",+ "BacktickIdentifierQuoter",+ "Column",+ "ColumnType",+ "IdentifierQuoter",+ "IncrementalFieldFilter",+ "InvalidIdentifierError",+ "ParamStyle",+ "SafeSQL",+ "SelectQueryBuilder",+ "Table",+ "TableBase",+ "TableReference",+ "TableSchemas",+ "TableStats",+ "build_incremental_fields",+ "initial_value_for_incremental_type",+ "resolve_detected_primary_keys",+]diff --git a/posthog/temporal/data_imports/sources/common/sql/base.py b/posthog/temporal/data_imports/sources/common/sql/base.pynew file mode 100644index 000000000000..c0f4e9396573--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/sql/base.py@@ -0,0 +1,105 @@+"""`SQLSource` template for SQL-based data-import sources.++Every SQL source decomposes into two concerns:++- A PostHog-layer wrapper (config schema, credentials validation,+ error-to-message mapping, registry registration). That's *this* class.+- A driver-layer implementation (connection lifecycle, metadata+ queries, dlt pipeline build). That's `SQLSourceImplementation`, held+ by every `SQLSource` subclass via the `get_implementation` property.++The wrapper stays thin: `get_schemas` opens a connection once via+`impl.connect(config)`, threads it through each query method, and+assembles `SourceSchema` rows; `source_for_pipeline` delegates straight+to `impl.build_pipeline`. Subclasses usually only define:++ get_implementation → MyDriverImplementation()+ source_type, get_source_config, validate_credentials++— no driver code bleeds into the source file.+"""++from __future__ import annotations++from abc import abstractmethod+from typing import Any, Generic++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import ConfigType, SimpleSource+from posthog.temporal.data_imports.sources.common.schema import SourceSchema+from posthog.temporal.data_imports.sources.common.sql.implementation import SQLSourceImplementation+from posthog.temporal.data_imports.sources.common.sql.incremental import build_incremental_fields+++class SQLSource(SimpleSource[ConfigType], Generic[ConfigType]):+ """Base class for SQL-based data-import sources.++ Subclasses expose a `SQLSourceImplementation` via+ `get_implementation`. Everything else on this class is template+ wiring around it.+ """++ @property+ @abstractmethod+ def get_implementation(self) -> SQLSourceImplementation[ConfigType, Any, Any]:+ """The driver-layer implementation for this 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.++ Mirrors what every SQL source has always done just before building+ a `SourceSchema`.+ """+ if any(col[0] == "id" for col in columns):+ return ["id"]+ return None++ def get_schemas(+ self,+ config: ConfigType,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ impl = self.get_implementation+ with impl.connect(config) as conn:+ columns_by_table = impl.get_columns(conn, config, names)+ if not columns_by_table:+ return []+ tables = list(columns_by_table.keys())+ primary_keys = impl.get_primary_keys(conn, config, tables)+ row_counts = impl.get_row_counts(conn, config, tables) if with_counts else {}+ foreign_keys = impl.get_foreign_keys(conn, config, tables)+ metadata = impl.get_source_metadata(conn, config, tables)+ cdc_support = impl.get_cdc_support(conn, config, tables)+ indexed_columns_by_table = impl.get_leading_index_columns(conn, config, tables)++ incremental_filter = impl.get_incremental_filter()++ schemas: list[SourceSchema] = []+ for table_name, columns in columns_by_table.items():+ incremental_triples = incremental_filter(columns)+ detected_pks = primary_keys.get(table_name) or self._default_primary_key_from_columns(columns)+ indexed_columns = indexed_columns_by_table.get(table_name) if indexed_columns_by_table is not None else None++ schemas.append(+ SourceSchema(+ name=table_name,+ supports_incremental=len(incremental_triples) > 0,+ supports_append=len(incremental_triples) > 0,+ supports_cdc=cdc_support.get(table_name, False),+ incremental_fields=build_incremental_fields(incremental_triples, indexed_columns),+ columns=columns,+ row_count=row_counts.get(table_name),+ foreign_keys=foreign_keys.get(table_name, []),+ source_catalog=metadata.catalog_by_table.get(table_name),+ source_schema=metadata.schema_by_table.get(table_name),+ source_table_name=metadata.table_name_by_table.get(table_name),+ detected_primary_keys=detected_pks,+ )+ )+ return schemas++ def source_for_pipeline(self, config: ConfigType, inputs: SourceInputs) -> SourceResponse:+ return self.get_implementation.build_pipeline(config, inputs)diff --git a/posthog/temporal/data_imports/sources/common/sql/identifiers.py b/posthog/temporal/data_imports/sources/common/sql/identifiers.pynew file mode 100644index 000000000000..ad6af29fba6c--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/sql/identifiers.py@@ -0,0 +1,104 @@+"""Identifier quoting and allowlist validation for SQL-based sources.++The single place where *unparameterized* strings (schema / table / column+names) 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.+"""++from __future__ import annotations++import re+from typing import Protocol+++class InvalidIdentifierError(ValueError):+ """Raised when an identifier fails the allowlist check.++ Subclasses `ValueError` so existing callers that catch `ValueError`+ (`mysql._sanitize_identifier` raised plain `ValueError`) keep working.+ """+++_ALLOWED_EXTRA_CHARS = set("._-$@")+_ALL_DIGITS = re.compile(r"^\d+$")+++def _validate_identifier(identifier: str) -> None:+ """Allowlist check shared by every concrete quoter.++ Accepts: alphanumeric plus `.`, `_`, `-`, `$`, `@`. An identifier that+ is nothing but digits is also allowed (matches today's MySQL behavior+ where `"851"` is quoted verbatim). Anything else — whitespace, a+ semicolon, a quote character, a NUL byte — raises.+ """+ if not identifier:+ raise InvalidIdentifierError("Identifier may not be empty")++ if _ALL_DIGITS.match(identifier):+ return++ for ch in identifier:+ if ch.isalnum() or ch in _ALLOWED_EXTRA_CHARS:+ continue+ raise InvalidIdentifierError(f"Invalid SQL identifier: {identifier!r}")+++class IdentifierQuoter(Protocol):+ """Driver-specific quoting of a validated identifier.++ Subclasses implement the quoting style that matches their dialect+ (backticks for MySQL, double-quotes for Postgres/ANSI, square brackets+ for T-SQL). `quote` MUST call `_validate_identifier` on the input before+ any quoting so a subclass cannot skip the allowlist check.+ """++ def quote(self, identifier: str) -> str: ...++ def quote_qualified(self, *parts: str) -> str:+ """Quote each part and join with '.' for a fully-qualified reference."""+ ...+++class _BaseQuoter:+ """Shared implementation detail for the two concrete quoters below.++ Deliberately not exported — external callers use the `IdentifierQuoter`+ protocol, which is all the `SelectQueryBuilder` needs.+ """++ _open: str+ _close: str++ def quote(self, identifier: str) -> str:+ _validate_identifier(identifier)+ return f"{self._open}{identifier}{self._close}"++ def quote_qualified(self, *parts: str) -> str:+ if not parts:+ raise InvalidIdentifierError("quote_qualified requires at least one part")+ return ".".join(self.quote(p) for p in parts)+++class BacktickIdentifierQuoter(_BaseQuoter):+ """MySQL / MariaDB / ClickHouse quoting with backticks."""++ _open = "`"+ _close = "`"+++class AnsiIdentifierQuoter(_BaseQuoter):+ """ANSI SQL quoting with double-quotes (Postgres, Redshift, Snowflake)."""++ _open = '"'+ _close = '"'diff --git a/posthog/temporal/data_imports/sources/common/sql/implementation.py b/posthog/temporal/data_imports/sources/common/sql/implementation.pynew file mode 100644index 000000000000..4063849eff10--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/sql/implementation.py@@ -0,0 +1,340 @@+"""Driver-side composition object for SQL sources.++`SQLSourceImplementation` is the contract every SQL driver implements.+It owns the *driver-shaped* parts of the source — connection lifecycle,+`information_schema`-style metadata queries, per-cursor streaming+metadata, and the dlt pipeline build — so that `SQLSource` (the+PostHog-layer wrapper) stays a thin template over the driver.++One implementation per driver, per-instance stateless: each public+method takes the `config` it needs. `SQLSource.get_schemas` opens the+connection once via `connect(config)` and threads the resulting+connection through every query method — giving every driver the+"single-tunnel-per-listing" behavior without each source having to+orchestrate it themselves.++Required methods: `connect`, `get_columns`, `get_incremental_filter`,+`build_pipeline`. Optional listing methods (`get_primary_keys`,+`get_row_counts`, …) return empty by default. Optional streaming+methods (`fetch_table_stats`, `fetch_average_row_size`) return `None`+by default so a driver opts into partition/chunk sizing by overriding+them — the base class does the math (`get_partition_settings`,+`get_chunk_size`) on top of those two hooks.+"""++from __future__ import annotations++import math+import dataclasses+from abc import ABC, abstractmethod+from contextlib import AbstractContextManager+from typing import Any, Generic, Protocol, TypeVar++from structlog.types import FilteringBoundLogger++from posthog.exceptions_capture import capture_exception+from posthog.temporal.data_imports.pipelines.pipeline.consts import DEFAULT_CHUNK_SIZE, DEFAULT_TABLE_SIZE_BYTES+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.pipelines.pipeline.utils import DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES+from posthog.temporal.data_imports.sources.common.config import Config+from posthog.temporal.data_imports.sources.common.sql.incremental import IncrementalFieldFilter+from posthog.temporal.data_imports.sources.common.sql.types import Column, Table++from products.data_warehouse.backend.types import PartitionSettings+++class _CursorLike(Protocol):+ """The bare minimum surface the shared math uses on a DB-API cursor.++ Narrow Protocol (instead of typing against `pymysql.cursors.Cursor`,+ `psycopg.Cursor`, etc.) so the base class stays driver-agnostic.+ Concrete implementations are `Generic[CursorT]` and can tighten this+ to their real cursor type.+ """++ def execute(self, query: str, args: Any = ...) -> Any: ...+ def fetchone(self) -> Any: ...+ def fetchall(self) -> Any: ...+++ConfigT = TypeVar("ConfigT", bound=Config)+ConnT = TypeVar("ConnT")+CursorT = TypeVar("CursorT", bound=_CursorLike)++[email protected](frozen=True)+class TableStats:+ """Table-level statistics used to compute partition settings.++ Populated from driver-specific metadata tables — `information_schema.TABLES`+ on MySQL, `pg_class` on Postgres, etc. Both values are estimates:+ nothing downstream needs them to be exact, they just need to be close+ enough to pick a reasonable partition size.+ """++ table_size_bytes: int+ row_count: int+++class SourceMetadata:+ """Per-table catalog / schema / table-name overrides.++ Sources that distinguish catalog (project/account) from schema+ (database/dataset) from table (logical name) populate these+ dictionaries; most SQL sources leave them empty and let the base+ derive identity from the config.+ """++ catalog_by_table: dict[str, str | None] = dataclasses.field(default_factory=dict)+ schema_by_table: dict[str, str | None] = dataclasses.field(default_factory=dict)+ table_name_by_table: dict[str, str | None] = dataclasses.field(default_factory=dict)+++class SQLSourceImplementation(Generic[ConfigT, ConnT, CursorT], ABC):+ """Driver-side contract paired with `SQLSource`.++ `ConfigT` is the driver's typed config class (e.g.+ `MySQLSourceConfig`). `ConnT` is whatever the driver's native+ connection object is (`pymysql.Connection`, `psycopg.Connection`,+ `snowflake.connector.SnowflakeConnection`, a REST client, …).+ `CursorT` is the cursor type returned by `conn.cursor()` — used by+ the shared partition/chunk sizing math.+ """++ # ------------------------------------------------------------------+ # Required+ # ------------------------------------------------------------------++ @abstractmethod+ def connect(self, config: ConfigT) -> AbstractContextManager[ConnT]:+ """Open a driver connection for the duration of schema discovery.++ Implementations own the full lifecycle — SSH tunnel (if any),+ TLS, auth, cursor setup — and clean it up on exit.+ """++ @abstractmethod+ def get_columns(+ self,+ conn: ConnT,+ config: ConfigT,+ names: list[str] | None,+ ) -> dict[str, list[tuple[str, str, bool]]]:+ """Return `{table_name: [(column_name, data_type, nullable), …]}`.++ `names` scopes the listing; `None` means "every table visible in+ this schema/database".+ """++ @abstractmethod+ def get_incremental_filter(self) -> IncrementalFieldFilter:+ """Map driver column-type strings onto `IncrementalFieldType`s."""++ @abstractmethod+ def build_pipeline(self, config: ConfigT, inputs: SourceInputs) -> SourceResponse:+ """Construct the dlt `SourceResponse` for a single schema sync."""++ # ------------------------------------------------------------------+ # Optional listing queries — base returns empty so drivers opt in+ # ------------------------------------------------------------------++ def get_primary_keys(+ self,+ conn: ConnT,+ config: ConfigT,+ tables: list[str],+ ) -> dict[str, list[str] | None]:+ return {}++ def get_row_counts(+ self,+ conn: ConnT,+ config: ConfigT,+ tables: list[str],+ ) -> dict[str, int | None]:+ return {}++ def get_foreign_keys(+ self,+ conn: ConnT,+ config: ConfigT,+ tables: list[str],+ ) -> dict[str, list[tuple[str, str, str]]]:+ return {}++ def get_source_metadata(+ self,+ conn: ConnT,+ config: ConfigT,+ tables: list[str],+ ) -> SourceMetadata:+ return SourceMetadata()++ def get_cdc_support(+ self,+ conn: ConnT,+ config: ConfigT,+ tables: list[str],+ ) -> dict[str, bool]:+ return {}++ def get_leading_index_columns(+ self,+ conn: ConnT,+ config: ConfigT,+ tables: list[str],+ ) -> dict[str, set[str]] | None:+ """Return `{table_name: {leading_index_column, …}}` per table, or `None`.++ Drives the UI warning when a user picks an incremental field with+ no index on the source. Returning `None` means "lookup failed —+ don't warn, treat every field as indexed". Tables present with an+ empty set mean "we looked, no indexes here — warn for every+ candidate". Drivers opt in by overriding; the default skips the+ feature (every field reported as indexed).+ """+ return None++ # ------------------------------------------------------------------+ # Optional streaming queries — called from within `build_pipeline`+ # on a live cursor. Base returns `None` so drivers opt into partition+ # and chunk sizing by overriding.+ # ------------------------------------------------------------------++ def get_table_metadata(+ self,+ cursor: CursorT,+ schema: str,+ table_name: str,+ ) -> Table[Column] | None:+ """Return rich column metadata for building a PyArrow schema.++ Drivers override with a narrower return (`Table[<driver>Column]`)+ — every SQL source has this concept (the Arrow schema fed to+ dlt). Covariance on `Table`'s `ColumnType` makes the narrower+ override LSP-compliant.+ """+ return None++ def fetch_table_stats(+ self,+ cursor: CursorT,+ schema: str,+ table_name: str,+ logger: FilteringBoundLogger,+ ) -> TableStats | None:+ """Return an estimate of the table's size + row count, or `None`.++ Drivers that want `get_partition_settings` to produce non-None+ must override this — e.g. query `information_schema.TABLES` on+ MySQL or `pg_class` on Postgres.+ """+ return None++ def fetch_average_row_size(+ self,+ cursor: CursorT,+ schema: str,+ table_name: str,+ inner_query: str,+ inner_query_args: Any,+ logger: FilteringBoundLogger,+ ) -> int | None:+ """Return the average row size in bytes sampled from the filtered query.++ Drivers that want `get_chunk_size` to tune the streaming chunk+ size must override this — e.g. `LENGTH(col)` sampling on MySQL,+ `percentile_cont(octet_length(...))` on Postgres.+ """+ return None++ # ------------------------------------------------------------------+ # Shared math — concrete, identical across every SQL driver today+ # ------------------------------------------------------------------++ def get_partition_settings(+ self,+ cursor: CursorT,+ schema: str,+ table_name: str,+ logger: FilteringBoundLogger,+ partition_size_bytes: int = DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES,+ ) -> PartitionSettings | None:+ """Compute `PartitionSettings` from `fetch_table_stats`.++ Returns None when stats are missing or the table is empty; the+ caller decides what to do in that case.+ """+ try:+ stats = self.fetch_table_stats(cursor, schema, table_name, logger)+ except Exception as e:+ logger.debug(f"get_partition_settings: Error fetching stats: {e}. Returning None", exc_info=e)+ capture_exception(e)+ return None++ if stats is None or stats.row_count == 0:+ logger.debug("get_partition_settings: no usable stats returning None")+ return None++ avg_row_size = stats.table_size_bytes / stats.row_count+ if avg_row_size <= 0:+ logger.debug("get_partition_settings: non-positive avg_row_size, returning None")+ return None++ # A partition must hold at least one row.+ partition_size = max(round(partition_size_bytes / avg_row_size), 1)+ partition_count = math.floor(stats.row_count / partition_size)++ if partition_count == 0:+ logger.debug(f"get_partition_settings: partition_count == 0, returning partition_size={partition_size}")+ return PartitionSettings(partition_count=1, partition_size=partition_size)++ logger.debug(f"get_partition_settings: partition_count={partition_count}, partition_size={partition_size}")+ return PartitionSettings(partition_count=partition_count, partition_size=partition_size)++ def get_chunk_size(+ self,+ cursor: CursorT,+ schema: str,+ table_name: str,+ inner_query: str,+ inner_query_args: Any,+ logger: FilteringBoundLogger,+ default_chunk_size: int = DEFAULT_CHUNK_SIZE,+ target_chunk_size_bytes: int = DEFAULT_TABLE_SIZE_BYTES,+ ) -> int:+ """Compute a safe `fetchmany` chunk size from the sampled row size.++ Falls back to `default_chunk_size` whenever sampling fails or+ returns a non-positive value — matches what every SQL source+ does today.+ """+ try:+ row_size_bytes = self.fetch_average_row_size(+ cursor, schema, table_name, inner_query, inner_query_args, logger+ )+ except Exception as e:+ logger.debug(+ f"get_chunk_size: Error: {e}. Using default_chunk_size={default_chunk_size}",+ exc_info=e,+ )+ capture_exception(e)+ return default_chunk_size++ if row_size_bytes is None or row_size_bytes <= 0:+ logger.debug(f"get_chunk_size: Could not calculate row size. Using default_chunk_size={default_chunk_size}")+ return default_chunk_size++ # Cap at `default_chunk_size` so narrow rows don't blow up the+ # row count. `target_chunk_size_bytes` bounds memory in *bytes*,+ # but each fetched row becomes a Python dict with its own+ # overhead — an unbounded row count can exceed the byte budget+ # once serialized.+ chunk_size = min(int(target_chunk_size_bytes / row_size_bytes), default_chunk_size)+ chunk_size = max(chunk_size, 1)+ logger.debug(+ f"get_chunk_size: row_size_bytes={row_size_bytes}. "+ f"target_chunk_size_bytes={target_chunk_size_bytes}. Using CHUNK_SIZE={chunk_size}"+ )+ return chunk_sizediff --git a/posthog/temporal/data_imports/sources/common/sql/incremental.py b/posthog/temporal/data_imports/sources/common/sql/incremental.pynew file mode 100644index 000000000000..33827376e6a4--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/sql/incremental.py@@ -0,0 +1,65 @@+"""Incremental-field filter contract for SQL sources.++Every SQL source exposes a `filter_<name>_incremental_fields(columns)` helper+that maps the driver's column-type strings onto `IncrementalFieldType`s. The+contract here formalizes what those helpers return and provides a shared+utility to build the `IncrementalField` dicts that `SourceSchema` expects —+removing the identical loop currently copied in every `source.py` façade.+"""++from __future__ import annotations++from typing import Protocol++from posthog.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_value++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++class IncrementalFieldFilter(Protocol):+ """Map driver column tuples onto incremental-capable fields.++ The input tuple is `(name, data_type, nullable)` matching today's+ `filter_<driver>_incremental_fields` signature. The output tuple is+ `(name, IncrementalFieldType, nullable)`.+ """++ def __call__(self, columns: list[tuple[str, str, bool]]) -> list[tuple[str, IncrementalFieldType, bool]]: ...+++def build_incremental_fields(+ triples: list[tuple[str, IncrementalFieldType, bool]],+ indexed_columns: set[str] | None = None,+) -> list[IncrementalField]:+ """Convert `(name, type, nullable)` tuples into `IncrementalField` dicts.++ This loop used to live unchanged in every `source.py` (postgres, mysql,+ mssql, snowflake, bigquery, redshift, clickhouse) — centralizing it+ here so schema discovery stays consistent.++ `indexed_columns` is the leading index column set for the table the+ triples came from. `None` means "discovery wasn't run / failed" — the+ UI treats every field as indexed (no warning). When provided, each+ field reports `is_indexed=True` iff its column is the leading column+ of some index.+ """+ return [+ {+ "label": name,+ "type": field_type,+ "field": name,+ "field_type": field_type,+ "nullable": nullable,+ "is_indexed": True if indexed_columns is None else name in indexed_columns,+ }+ for name, field_type, nullable in triples+ ]+++def initial_value_for_incremental_type(field_type: IncrementalFieldType) -> object:+ """Thin wrapper around `pipelines.helpers.incremental_type_to_initial_value`.++ Re-exported from this module so callers in `common/sql/` don't have to+ reach into the pipelines package directly (keeps the module graph clean).+ """+ return incremental_type_to_initial_value(field_type)diff --git a/posthog/temporal/data_imports/sources/common/sql/query_builder.py b/posthog/temporal/data_imports/sources/common/sql/query_builder.pynew file mode 100644index 000000000000..546d9a4d8283--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/sql/query_builder.py@@ -0,0 +1,134 @@+"""Safe `SELECT` builder shared by every SQL source.++Assembles a read query from already-quoted identifiers (via an+`IdentifierQuoter`) and a value passed through as a driver-native parameter.+Values are **never** interpolated into the SQL string — they only ever leave+this module inside the returned `params` mapping, which the caller passes+straight to the DB cursor (`cursor.execute(sql, params)`).++Supported parameter placeholder styles match the drivers used today:++- `ParamStyle.PYFORMAT_NAMED` — `%(name)s` (psycopg, pymysql, pymssql).+- `ParamStyle.QMARK` — `?` positional (pyodbc/ADO-style).+- `ParamStyle.NUMERIC` — `:1`, `:2` … (snowflake-connector binding=numeric).+- `ParamStyle.NAMED` — `:name` (snowflake `qmark`-style, BigQuery+ parameterized queries).++Every existing hand-rolled `_build_query` in `mysql.py`, `mssql.py`,+`snowflake.py`, `bigquery.py`, `redshift.py`, `clickhouse.py` can be+expressed as a `SelectQueryBuilder` call.+"""++from __future__ import annotations++import enum+from dataclasses import dataclass+from typing import Any, Union++from posthog.temporal.data_imports.pipelines.helpers import (+ incremental_type_to_initial_value,+ incremental_type_to_operator,+)+from posthog.temporal.data_imports.sources.common.sql.identifiers import IdentifierQuoter++from products.data_warehouse.backend.types import IncrementalFieldType+++class ParamStyle(enum.Enum):+ PYFORMAT_NAMED = "pyformat_named"+ QMARK = "qmark"+ NUMERIC = "numeric"+ NAMED = "named"+++@dataclass(frozen=True)+class SafeSQL:+ """A SQL statement that never contains an interpolated value.++ `sql` is the statement text with driver-appropriate placeholders;+ `params` is the mapping (or positional list) the caller hands to the+ cursor. Together they form the only safe way to execute a query+ assembled by this package.+ """++ sql: str+ params: Union[dict[str, Any], list[Any]]+++@dataclass(frozen=True)+class SelectQueryBuilder:+ """Builder for a `SELECT * FROM <table> [WHERE ...] [ORDER BY ...]` query.++ `quoter` controls how identifiers are quoted; `param_style` controls how+ parameter placeholders are emitted. Builder instances are frozen so the+ same builder can be reused across calls without risk of accidental state+ leak between sources.+ """++ quoter: IdentifierQuoter+ param_style: ParamStyle = ParamStyle.PYFORMAT_NAMED++ def select_all(+ self,+ *,+ schema: str,+ table_name: str,+ incremental_field: str | None = None,+ incremental_field_type: IncrementalFieldType | None = None,+ incremental_last_value: Any | None = None,+ extra_table_hint: str | None = None,+ order_by_incremental: bool = True,+ ) -> SafeSQL:+ """Build a full `SELECT * FROM schema.table` with optional incremental predicate.++ When `incremental_field` is provided, appends+ `WHERE <incremental_field> <op> :last_value [ORDER BY <incremental_field> ASC]`.+ `<op>` is `>=` for `Date` (day-granularity boundary) and `>` for+ every other type — same semantics as `incremental_type_to_operator`.+ `incremental_last_value` falls back to the type's initial value so+ the semantics match today's `_build_query` implementations.++ `extra_table_hint` is appended verbatim after the table reference+ (e.g. MySQL `FORCE INDEX (...)`). Callers who use it must have+ already validated it through their quoter — the builder itself+ does not parse hint syntax.+ """+ table_ref = self.quoter.quote_qualified(schema, table_name)+ hint = f" {extra_table_hint}" if extra_table_hint else ""++ if incremental_field is None:+ return SafeSQL(sql=f"SELECT * FROM {table_ref}{hint}", params=self._empty_params())++ if incremental_field_type is None:+ raise ValueError("incremental_field_type is required when incremental_field is set")++ value = (+ incremental_last_value+ if incremental_last_value is not None+ else incremental_type_to_initial_value(incremental_field_type)+ )+ quoted_field = self.quoter.quote(incremental_field)+ placeholder, params = self._single_param("incremental_value", value)+ operator = incremental_type_to_operator(incremental_field_type)++ parts = [f"SELECT * FROM {table_ref}{hint}", f"WHERE {quoted_field} {operator} {placeholder}"]+ if order_by_incremental:+ parts.append(f"ORDER BY {quoted_field} ASC")++ return SafeSQL(sql=" ".join(parts), params=params)++ def _empty_params(self) -> dict[str, Any] | list[Any]:+ if self.param_style in (ParamStyle.PYFORMAT_NAMED, ParamStyle.NAMED):+ return {}+ return []++ def _single_param(self, name: str, value: Any) -> tuple[str, dict[str, Any] | list[Any]]:+ if self.param_style == ParamStyle.PYFORMAT_NAMED:+ return f"%({name})s", {name: value}+ if self.param_style == ParamStyle.NAMED:+ return f":{name}", {name: value}+ if self.param_style == ParamStyle.QMARK:+ return "?", [value]+ if self.param_style == ParamStyle.NUMERIC:+ return ":1", [value]+ raise ValueError(f"Unsupported param style: {self.param_style}")diff --git a/posthog/temporal/data_imports/sources/common/sql/tests/__init__.py b/posthog/temporal/data_imports/sources/common/sql/tests/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/temporal/data_imports/sources/common/sql/tests/test_base.py b/posthog/temporal/data_imports/sources/common/sql/tests/test_base.pynew file mode 100644index 000000000000..955d56ccce5f--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/sql/tests/test_base.py@@ -0,0 +1,220 @@+from __future__ import annotations++import dataclasses+from contextlib import contextmanager+from typing import Any++import pytest+from unittest.mock import MagicMock++from posthog.schema import SourceConfig++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.config import Config+from posthog.temporal.data_imports.sources.common.sql.base import SQLSource+from posthog.temporal.data_imports.sources.common.sql.implementation import SourceMetadata, SQLSourceImplementation+from posthog.temporal.data_imports.sources.common.sql.incremental import IncrementalFieldFilter++from products.data_warehouse.backend.types import ExternalDataSourceType, IncrementalFieldType+++class _FakeConfig(Config):+ name: str = "fake"+++def _fake_filter(+ columns: list[tuple[str, str, bool]],+) -> list[tuple[str, IncrementalFieldType, bool]]:+ """Treat any column typed 'timestamp' as incremental-capable."""+ return [+ (name, IncrementalFieldType.Timestamp, nullable)+ for name, data_type, nullable in columns+ if data_type == "timestamp"+ ]+++class _FakeImplData:+ columns_by_table: dict[str, list[tuple[str, str, bool]]] = dataclasses.field(default_factory=dict)+ primary_keys_by_table: dict[str, list[str] | None] = dataclasses.field(default_factory=dict)+ row_counts_by_table: dict[str, int | None] = dataclasses.field(default_factory=dict)+ foreign_keys_by_table: dict[str, list[tuple[str, str, str]]] = dataclasses.field(default_factory=dict)+ source_metadata: SourceMetadata = dataclasses.field(default_factory=SourceMetadata)+ cdc_by_table: dict[str, bool] = dataclasses.field(default_factory=dict)+++class _FakeImplementation(SQLSourceImplementation[_FakeConfig, object, Any]):+ """Records the arguments it receives so tests can assert on the wiring."""++ def __init__(self, data: _FakeImplData | None = None) -> None:+ self.data = data or _FakeImplData()+ self.get_columns_calls: list[tuple[list[str] | None]] = []+ self.get_primary_keys_called = False+ self.get_row_counts_called = False+ self.get_foreign_keys_called = False++ @contextmanager+ def connect(self, config: _FakeConfig):+ yield object()++ def get_columns(+ self, conn: object, config: _FakeConfig, names: list[str] | None+ ) -> dict[str, list[tuple[str, str, bool]]]:+ self.get_columns_calls.append((names,))+ if names is None:+ return self.data.columns_by_table+ return {k: v for k, v in self.data.columns_by_table.items() if k in names}++ def get_primary_keys(self, conn: object, config: _FakeConfig, tables: list[str]) -> dict[str, list[str] | None]:+ self.get_primary_keys_called = True+ return self.data.primary_keys_by_table++ def get_row_counts(self, conn: object, config: _FakeConfig, tables: list[str]) -> dict[str, int | None]:+ self.get_row_counts_called = True+ return self.data.row_counts_by_table++ def get_foreign_keys(+ self, conn: object, config: _FakeConfig, tables: list[str]+ ) -> dict[str, list[tuple[str, str, str]]]:+ self.get_foreign_keys_called = True+ return self.data.foreign_keys_by_table++ def get_source_metadata(self, conn: object, config: _FakeConfig, tables: list[str]) -> SourceMetadata:+ return self.data.source_metadata++ def get_cdc_support(self, conn: object, config: _FakeConfig, tables: list[str]) -> dict[str, bool]:+ return self.data.cdc_by_table++ def get_incremental_filter(self) -> IncrementalFieldFilter:+ return _fake_filter++ def build_pipeline(self, config: _FakeConfig, inputs: SourceInputs) -> SourceResponse:+ raise NotImplementedError("not exercised in get_schemas tests")+++class _FakeSQLSource(SQLSource[_FakeConfig]):+ def __init__(self, impl: _FakeImplementation) -> None:+ self._implementation = impl++ @property+ def get_implementation(self) -> _FakeImplementation:+ return self._implementation++ @property+ def source_type(self) -> ExternalDataSourceType:+ return ExternalDataSourceType.POSTGRES++ @property+ def get_source_config(self) -> SourceConfig:+ return MagicMock(spec=SourceConfig)+++def _make_source(**data: Any) -> tuple[_FakeSQLSource, _FakeImplementation]:+ impl = _FakeImplementation(_FakeImplData(**data))+ return _FakeSQLSource(impl), impl+++class TestGetSchemas:+ def test_returns_one_source_schema_per_table(self) -> None:+ source, _ = _make_source(+ columns_by_table={+ "messages": [("id", "int", False), ("ts", "timestamp", False)],+ "users": [("id", "int", False)],+ }+ )+ result = source.get_schemas(_FakeConfig(), team_id=1)+ assert {s.name for s in result} == {"messages", "users"}++ def test_incremental_fields_derived_via_filter(self) -> None:+ source, _ = _make_source(columns_by_table={"messages": [("id", "int", False), ("ts", "timestamp", False)]})+ [schema] = source.get_schemas(_FakeConfig(), team_id=1)+ fields: list[Any] = list(schema.incremental_fields)+ assert len(fields) == 1+ assert fields[0]["field"] == "ts"+ assert schema.supports_incremental is True+ assert schema.supports_append is True++ def test_no_incremental_fields_disables_incremental_flags(self) -> None:+ source, _ = _make_source(columns_by_table={"tbl": [("id", "int", False)]})+ [schema] = source.get_schemas(_FakeConfig(), team_id=1)+ assert schema.incremental_fields == []+ assert schema.supports_incremental is False++ def test_detected_primary_keys_passed_through(self) -> None:+ source, _ = _make_source(+ columns_by_table={"messages": [("id", "int", False)]},+ primary_keys_by_table={"messages": ["id"]},+ )+ [schema] = source.get_schemas(_FakeConfig(), team_id=1)+ assert schema.detected_primary_keys == ["id"]++ def test_falls_back_to_id_column_when_no_pk_detected(self) -> None:+ source, _ = _make_source(+ columns_by_table={"messages": [("id", "int", False), ("body", "text", True)]},+ primary_keys_by_table={"messages": None},+ )+ [schema] = source.get_schemas(_FakeConfig(), team_id=1)+ assert schema.detected_primary_keys == ["id"]++ def test_no_pk_fallback_when_no_id_column(self) -> None:+ source, _ = _make_source(columns_by_table={"messages": [("body", "text", True)]})+ [schema] = source.get_schemas(_FakeConfig(), team_id=1)+ assert schema.detected_primary_keys is None++ def test_row_counts_passed_through_when_with_counts_true(self) -> None:+ source, impl = _make_source(+ columns_by_table={"messages": [("id", "int", False)]},+ row_counts_by_table={"messages": 42},+ )+ [schema] = source.get_schemas(_FakeConfig(), team_id=1, with_counts=True)+ assert schema.row_count == 42+ assert impl.get_row_counts_called is True++ def test_row_counts_skipped_when_with_counts_false(self) -> None:+ source, impl = _make_source(+ columns_by_table={"messages": [("id", "int", False)]},+ row_counts_by_table={"messages": 42},+ )+ [schema] = source.get_schemas(_FakeConfig(), team_id=1, with_counts=False)+ assert schema.row_count is None+ assert impl.get_row_counts_called is False++ def test_foreign_keys_passed_through(self) -> None:+ source, _ = _make_source(+ columns_by_table={"messages": [("id", "int", False)]},+ foreign_keys_by_table={"messages": [("author_id", "users", "id")]},+ )+ [schema] = source.get_schemas(_FakeConfig(), team_id=1)+ assert schema.foreign_keys == [("author_id", "users", "id")]++ @pytest.mark.parametrize("names", [None, ["messages"]])+ def test_names_forwarded_to_get_columns(self, names: list[str] | None) -> None:+ source, impl = _make_source(+ columns_by_table={+ "messages": [("id", "int", False)],+ "users": [("id", "int", False)],+ }+ )+ source.get_schemas(_FakeConfig(), team_id=1, names=names)+ assert impl.get_columns_calls == [(names,)]++ def test_empty_discovery_returns_empty_list(self) -> None:+ source, _ = _make_source(columns_by_table={})+ assert source.get_schemas(_FakeConfig(), team_id=1) == []++ def test_source_metadata_passed_through(self) -> None:+ source, _ = _make_source(+ columns_by_table={"t": [("id", "int", False)]},+ source_metadata=SourceMetadata(+ catalog_by_table={"t": "my_db"},+ schema_by_table={"t": "public"},+ table_name_by_table={"t": "original_t"},+ ),+ cdc_by_table={"t": True},+ )+ [schema] = source.get_schemas(_FakeConfig(), team_id=1)+ assert schema.source_catalog == "my_db"+ assert schema.source_schema == "public"+ assert schema.source_table_name == "original_t"+ assert schema.supports_cdc is Truediff --git a/posthog/temporal/data_imports/sources/common/sql/tests/test_identifiers.py b/posthog/temporal/data_imports/sources/common/sql/tests/test_identifiers.pynew file mode 100644index 000000000000..27b7fa2cb624--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/sql/tests/test_identifiers.py@@ -0,0 +1,79 @@+from __future__ import annotations++import pytest++from posthog.temporal.data_imports.sources.common.sql.identifiers import (+ AnsiIdentifierQuoter,+ BacktickIdentifierQuoter,+ InvalidIdentifierError,+)+++class TestBacktickIdentifierQuoter:+ quoter = BacktickIdentifierQuoter()++ @pytest.mark.parametrize(+ "identifier,expected",+ [+ ("mydb", "`mydb`"),+ ("my_table", "`my_table`"),+ ("851", "`851`"),+ ("$col", "`$col`"),+ ("db@prod", "`db@prod`"),+ ("a-b", "`a-b`"),+ ("a.b", "`a.b`"),+ ],+ )+ def test_accepts_allowed_identifiers(self, identifier: str, expected: str) -> None:+ assert self.quoter.quote(identifier) == expected++ @pytest.mark.parametrize(+ "identifier",+ [+ "bad;id",+ "drop table x",+ "a'b",+ 'a"b',+ "a`b",+ "a\nb",+ "a b",+ "a/*b*/",+ "",+ ],+ )+ def test_rejects_unsafe_identifiers(self, identifier: str) -> None:+ with pytest.raises(InvalidIdentifierError):+ self.quoter.quote(identifier)++ def test_quote_qualified_joins_with_dot(self) -> None:+ assert self.quoter.quote_qualified("schema", "table") == "`schema`.`table`"++ def test_quote_qualified_with_three_parts(self) -> None:+ assert self.quoter.quote_qualified("catalog", "schema", "table") == "`catalog`.`schema`.`table`"++ def test_quote_qualified_requires_at_least_one_part(self) -> None:+ with pytest.raises(InvalidIdentifierError):+ self.quoter.quote_qualified()++ def test_quote_qualified_rejects_any_unsafe_part(self) -> None:+ with pytest.raises(InvalidIdentifierError):+ self.quoter.quote_qualified("schema", "bad;table")+++class TestAnsiIdentifierQuoter:+ quoter = AnsiIdentifierQuoter()++ def test_quotes_with_double_quotes(self) -> None:+ assert self.quoter.quote("my_table") == '"my_table"'++ def 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:+ with pytest.raises(InvalidIdentifierError):+ self.quoter.quote('users"; DROP TABLE x; --')++ 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")diff --git a/posthog/temporal/data_imports/sources/common/sql/tests/test_implementation.py b/posthog/temporal/data_imports/sources/common/sql/tests/test_implementation.pynew file mode 100644index 000000000000..5a106f4e4478--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/sql/tests/test_implementation.py@@ -0,0 +1,167 @@+"""Tests for the shared partition/chunk sizing math on `SQLSourceImplementation`.++These cover the *shared* math (`get_partition_settings`, `get_chunk_size`)+that the base class builds on top of `fetch_table_stats` and+`fetch_average_row_size`. Driver-specific query behavior is tested next to+each implementation (e.g. `mysql/tests/test_mysql.py`).+"""++from __future__ import annotations++import dataclasses+from contextlib import contextmanager+from typing import Any++import pytest+from unittest.mock import MagicMock++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.config import Config+from posthog.temporal.data_imports.sources.common.sql.implementation import SQLSourceImplementation, TableStats+from posthog.temporal.data_imports.sources.common.sql.incremental import IncrementalFieldFilter+++class _FakeConfig(Config):+ name: str = "fake"+++class _FakeImplementation(SQLSourceImplementation[_FakeConfig, Any, Any]):+ """Minimal implementation that lets tests drive the base-class math directly."""++ def __init__(+ self,+ *,+ stats: TableStats | None = None,+ raises_on_stats: bool = False,+ row_size: int | None = None,+ raises_on_row_size: bool = False,+ ) -> None:+ self._stats = stats+ self._raises_on_stats = raises_on_stats+ self._row_size = row_size+ self._raises_on_row_size = raises_on_row_size+ self.fetch_table_stats_calls: list[tuple[Any, ...]] = []+ self.fetch_average_row_size_calls: list[tuple[Any, ...]] = []++ @contextmanager+ def connect(self, config): # pragma: no cover — not exercised by these tests+ yield object()++ def get_columns(self, conn, config, names): # pragma: no cover+ return {}++ def get_incremental_filter(self) -> IncrementalFieldFilter: # pragma: no cover+ return lambda columns: []++ def build_pipeline(self, config, inputs: SourceInputs) -> SourceResponse: # pragma: no cover+ raise NotImplementedError++ def fetch_table_stats(self, cursor, schema, table_name, logger):+ self.fetch_table_stats_calls.append((cursor, schema, table_name))+ if self._raises_on_stats:+ raise RuntimeError("stats query blew up")+ return self._stats++ def fetch_average_row_size(self, cursor, schema, table_name, inner_query, inner_query_args, logger):+ self.fetch_average_row_size_calls.append((cursor, schema, table_name, inner_query, inner_query_args))+ if self._raises_on_row_size:+ raise RuntimeError("row size query blew up")+ return self._row_size+++def logger():+ return MagicMock()+++class TestGetPartitionSettings:+ def test_returns_none_when_stats_missing(self, logger):+ impl = _FakeImplementation(stats=None)+ assert impl.get_partition_settings(MagicMock(), "db", "t", logger) is None++ def test_returns_none_when_table_empty(self, logger):+ impl = _FakeImplementation(stats=TableStats(table_size_bytes=0, row_count=0))+ assert impl.get_partition_settings(MagicMock(), "db", "t", logger) is None++ def test_returns_none_when_fetch_raises(self, logger):+ impl = _FakeImplementation(raises_on_stats=True)+ assert impl.get_partition_settings(MagicMock(), "db", "t", logger) is None+ # We still called through to the driver hook.+ assert len(impl.fetch_table_stats_calls) == 1++ def test_single_partition_fallback_when_partition_count_is_zero(self, logger):+ # Tiny table: 100 bytes, 2 rows → avg_row_size = 50 → partition_size huge+ # → floor(2 / big) = 0 → we fall back to 1 partition.+ impl = _FakeImplementation(stats=TableStats(table_size_bytes=100, row_count=2))+ result = impl.get_partition_settings(MagicMock(), "db", "t", logger)+ assert result is not None+ assert result.partition_count == 1+ # partition_size = round(default_target / 50), which for default 500MB is huge+ assert result.partition_size > 1++ def test_computes_partition_settings_from_stats(self, logger):+ # 1M rows * 100 bytes/row = 100MB. With partition_size_bytes=1MB,+ # partition_size = round(1_000_000 / 100) = 10_000 rows per partition,+ # partition_count = floor(1_000_000 / 10_000) = 100.+ impl = _FakeImplementation(stats=TableStats(table_size_bytes=100_000_000, row_count=1_000_000))+ result = impl.get_partition_settings(MagicMock(), "db", "t", logger, partition_size_bytes=1_000_000)+ assert result is not None+ assert result.partition_size == 10_000+ assert result.partition_count == 100++ def test_partition_size_never_below_one(self, logger):+ # Pathological: huge rows. avg_row_size = 10**12 → partition_size+ # = round(1e6 / 1e12) = 0 but code clamps to 1.+ impl = _FakeImplementation(stats=TableStats(table_size_bytes=10**15, row_count=1000))+ result = impl.get_partition_settings(MagicMock(), "db", "t", logger, partition_size_bytes=1_000_000)+ assert result is not None+ assert result.partition_size >= 1++ def test_passes_through_schema_and_table(self, logger):+ impl = _FakeImplementation(stats=None)+ cursor = MagicMock()+ impl.get_partition_settings(cursor, "mydb", "mytable", logger)+ assert impl.fetch_table_stats_calls == [(cursor, "mydb", "mytable")]+++class TestGetChunkSize:+ @pytest.mark.parametrize(+ "row_size,target_size,default_chunk_size,expected",+ [+ (100, 1_000_000, 20_000, 10_000), # happy path — below cap+ (1, 1_000_000, 20_000, 20_000), # tiny rows — would yield 1M, capped at default_chunk_size+ (10**9, 1_000, 20_000, 1), # huge rows — clamped to 1+ ],+ )+ def test_computes_chunk_size_from_row_size(self, logger, row_size, target_size, default_chunk_size, expected):+ impl = _FakeImplementation(row_size=row_size)+ result = impl.get_chunk_size(+ MagicMock(),+ "db",+ "t",+ "SELECT 1",+ {},+ logger,+ target_chunk_size_bytes=target_size,+ default_chunk_size=default_chunk_size,+ )+ assert result == expected++ def test_falls_back_to_default_on_none(self, logger):+ impl = _FakeImplementation(row_size=None)+ assert impl.get_chunk_size(MagicMock(), "db", "t", "SELECT 1", {}, logger, default_chunk_size=42) == 42++ def test_falls_back_to_default_on_zero(self, logger):+ impl = _FakeImplementation(row_size=0)+ assert impl.get_chunk_size(MagicMock(), "db", "t", "SELECT 1", {}, logger, default_chunk_size=77) == 77++ def test_falls_back_to_default_on_exception(self, logger):+ impl = _FakeImplementation(raises_on_row_size=True)+ assert impl.get_chunk_size(MagicMock(), "db", "t", "SELECT 1", {}, logger, default_chunk_size=99) == 99++ def test_passes_inner_query_through(self, logger):+ impl = _FakeImplementation(row_size=500)+ 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})]diff --git a/posthog/temporal/data_imports/sources/common/sql/tests/test_incremental.py b/posthog/temporal/data_imports/sources/common/sql/tests/test_incremental.pynew file mode 100644index 000000000000..abfbc227c017--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/sql/tests/test_incremental.py@@ -0,0 +1,81 @@+from __future__ import annotations++import datetime++import pytest++from posthog.temporal.data_imports.sources.common.sql.incremental import (+ build_incremental_fields,+ initial_value_for_incremental_type,+)++from products.data_warehouse.backend.types import IncrementalFieldType+++def test_build_incremental_fields_emits_dict_per_triple() -> None:+ triples: list[tuple[str, IncrementalFieldType, bool]] = [+ ("created_at", IncrementalFieldType.DateTime, False),+ ("id", IncrementalFieldType.Integer, False),+ ]+ result = build_incremental_fields(triples)+ # `indexed_columns=None` (the default) means "discovery wasn't run" — the UI+ # treats every field as indexed so no warning ever fires.+ assert result == [+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ "nullable": False,+ "is_indexed": True,+ },+ {+ "label": "id",+ "type": IncrementalFieldType.Integer,+ "field": "id",+ "field_type": IncrementalFieldType.Integer,+ "nullable": False,+ "is_indexed": True,+ },+ ]+++def test_build_incremental_fields_preserves_nullable_flag() -> None:+ result = build_incremental_fields([("updated_at", IncrementalFieldType.Timestamp, True)])+ assert result[0]["nullable"] is True+++def test_build_incremental_fields_empty_input() -> None:+ assert build_incremental_fields([]) == []+++def test_build_incremental_fields_marks_indexed_columns() -> None:+ triples: list[tuple[str, IncrementalFieldType, bool]] = [+ ("created_at", IncrementalFieldType.DateTime, False),+ ("id", IncrementalFieldType.Integer, False),+ ]+ result = build_incremental_fields(triples, indexed_columns={"id"})+ assert result[0]["is_indexed"] is False+ assert result[1]["is_indexed"] is True+++def test_build_incremental_fields_empty_indexed_set_marks_none_indexed() -> None:+ triples: list[tuple[str, IncrementalFieldType, bool]] = [+ ("created_at", IncrementalFieldType.DateTime, False),+ ]+ result = build_incremental_fields(triples, indexed_columns=set())+ assert result[0]["is_indexed"] is False+++ "field_type,expected",+ [+ (IncrementalFieldType.Integer, 0),+ (IncrementalFieldType.Numeric, 0),+ (IncrementalFieldType.DateTime, datetime.datetime(1970, 1, 1, tzinfo=datetime.UTC)),+ (IncrementalFieldType.Timestamp, datetime.datetime(1970, 1, 1, tzinfo=datetime.UTC)),+ (IncrementalFieldType.Date, datetime.date(1970, 1, 1)),+ ],+)+def test_initial_value_for_incremental_type(field_type: IncrementalFieldType, expected: object) -> None:+ assert initial_value_for_incremental_type(field_type) == expecteddiff --git a/posthog/temporal/data_imports/sources/common/sql/tests/test_query_builder.py b/posthog/temporal/data_imports/sources/common/sql/tests/test_query_builder.pynew file mode 100644index 000000000000..5f1753e4d003--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/sql/tests/test_query_builder.py@@ -0,0 +1,150 @@+from __future__ import annotations++import datetime++import pytest++from posthog.temporal.data_imports.sources.common.sql.identifiers import (+ AnsiIdentifierQuoter,+ BacktickIdentifierQuoter,+ InvalidIdentifierError,+)+from posthog.temporal.data_imports.sources.common.sql.query_builder import ParamStyle, SelectQueryBuilder++from products.data_warehouse.backend.types import IncrementalFieldType+++class TestSelectAllFullRefresh:+ builder = SelectQueryBuilder(quoter=BacktickIdentifierQuoter())++ def test_builds_unqualified_select_with_backticks(self) -> None:+ result = self.builder.select_all(schema="mydb", table_name="messages")+ assert result.sql == "SELECT * FROM `mydb`.`messages`"+ assert result.params == {}++ def test_extra_hint_is_appended_verbatim(self) -> None:+ result = self.builder.select_all(+ schema="mydb",+ table_name="messages",+ extra_table_hint="FORCE INDEX (`idx_created_at`)",+ )+ assert "FORCE INDEX (`idx_created_at`)" in result.sql+ assert result.sql.startswith("SELECT * FROM `mydb`.`messages` FORCE INDEX")++ def test_injection_in_identifier_raises(self) -> None:+ with pytest.raises(InvalidIdentifierError):+ self.builder.select_all(schema="mydb", table_name="messages; DROP TABLE x")+++class TestSelectAllIncremental:+ builder = SelectQueryBuilder(quoter=BacktickIdentifierQuoter())++ def test_pyformat_named_placeholder_is_used_for_value(self) -> None:+ result = self.builder.select_all(+ schema="mydb",+ table_name="messages",+ incremental_field="created_at",+ incremental_field_type=IncrementalFieldType.DateTime,+ incremental_last_value=datetime.datetime(2025, 1, 1),+ )+ assert "%(incremental_value)s" in result.sql+ assert "WHERE `created_at` > %(incremental_value)s" in result.sql+ assert "ORDER BY `created_at` ASC" in result.sql+ assert result.params == {"incremental_value": datetime.datetime(2025, 1, 1)}++ def test_value_never_interpolated_into_sql(self) -> None:+ """SQL-injection guard: the value string must stay in params."""+ result = self.builder.select_all(+ schema="mydb",+ table_name="messages",+ incremental_field="created_at",+ incremental_field_type=IncrementalFieldType.DateTime,+ incremental_last_value="2025'; DROP TABLE x; --",+ )+ assert "DROP TABLE" not in result.sql+ assert result.params == {"incremental_value": "2025'; DROP TABLE x; --"}++ def test_initial_value_used_when_last_value_is_none(self) -> None:+ result = self.builder.select_all(+ schema="mydb",+ table_name="messages",+ incremental_field="created_at",+ incremental_field_type=IncrementalFieldType.Integer,+ incremental_last_value=None,+ )+ assert isinstance(result.params, dict)+ assert result.params["incremental_value"] == 0++ def test_incremental_field_type_required(self) -> None:+ with pytest.raises(ValueError, match="incremental_field_type is required"):+ self.builder.select_all(+ schema="mydb",+ table_name="messages",+ incremental_field="created_at",+ incremental_field_type=None,+ )++ def test_date_type_uses_inclusive_operator(self) -> None:+ result = self.builder.select_all(+ schema="mydb",+ table_name="messages",+ incremental_field="event_date",+ incremental_field_type=IncrementalFieldType.Date,+ incremental_last_value=datetime.date(2025, 1, 1),+ )+ assert "WHERE `event_date` >= %(incremental_value)s" in result.sql++ def test_order_by_can_be_suppressed(self) -> None:+ result = self.builder.select_all(+ schema="mydb",+ table_name="messages",+ incremental_field="created_at",+ incremental_field_type=IncrementalFieldType.DateTime,+ incremental_last_value=datetime.datetime(2025, 1, 1),+ order_by_incremental=False,+ )+ assert "ORDER BY" not in result.sql+++class TestParamStyles:+ def test_qmark_style_emits_question_mark(self) -> None:+ builder = SelectQueryBuilder(quoter=AnsiIdentifierQuoter(), param_style=ParamStyle.QMARK)+ result = builder.select_all(+ schema="public",+ table_name="users",+ incremental_field="id",+ incremental_field_type=IncrementalFieldType.Integer,+ incremental_last_value=42,+ )+ assert 'WHERE "id" > ?' in result.sql+ assert result.params == [42]++ def test_named_style_uses_colon_prefix(self) -> None:+ builder = SelectQueryBuilder(quoter=AnsiIdentifierQuoter(), param_style=ParamStyle.NAMED)+ result = builder.select_all(+ schema="public",+ table_name="users",+ incremental_field="id",+ incremental_field_type=IncrementalFieldType.Integer,+ incremental_last_value=42,+ )+ assert ":incremental_value" in result.sql+ assert result.params == {"incremental_value": 42}++ def test_numeric_style_uses_positional_number(self) -> None:+ builder = SelectQueryBuilder(quoter=AnsiIdentifierQuoter(), param_style=ParamStyle.NUMERIC)+ result = builder.select_all(+ schema="public",+ table_name="users",+ incremental_field="id",+ incremental_field_type=IncrementalFieldType.Integer,+ incremental_last_value=42,+ )+ assert ":1" in result.sql+ assert result.params == [42]++ def test_empty_params_match_style(self) -> None:+ qmark = SelectQueryBuilder(quoter=AnsiIdentifierQuoter(), param_style=ParamStyle.QMARK)+ named = SelectQueryBuilder(quoter=AnsiIdentifierQuoter(), param_style=ParamStyle.PYFORMAT_NAMED)+ assert qmark.select_all(schema="public", table_name="t").params == []+ assert named.select_all(schema="public", table_name="t").params == {}diff --git a/posthog/temporal/data_imports/sources/common/sql.py b/posthog/temporal/data_imports/sources/common/sql/types.pysimilarity index 89%rename from posthog/temporal/data_imports/sources/common/sql.pyrename to posthog/temporal/data_imports/sources/common/sql/types.pyindex c5a636ce454c..cd360ad6e54d 100644--- a/posthog/temporal/data_imports/sources/common/sql.py+++ b/posthog/temporal/data_imports/sources/common/sql/types.py@@ -109,14 +109,16 @@ class TableReference(TableBase):return cls(name=name, parents=parents)-ColumnType = typing.TypeVar("ColumnType", bound=Column)+ColumnType = typing.TypeVar("ColumnType", bound=Column, covariant=True)class Table(TableBase, typing.Generic[ColumnType]):"""A table obtained from a `SQLSource`.- A table may be better understood as a container of `Column`, so indexing,- iteration, length checks, and membership tests are supported.+ A table may be better understood as a read-only container of+ `Column` — once constructed, its columns are not mutated — so+ `ColumnType` is covariant and `Table[MySQLColumn]` is a valid+ subtype of `Table[Column]`."""def __init__(@@ -153,11 +155,14 @@ class Table(TableBase, typing.Generic[ColumnType]):raise TypeError(f"unsupported key type: '{type(key)}'")- def __contains__(self, column: ColumnType | str) -> bool:+ def __contains__(self, column: Column | str) -> bool:"""Check if this `Table` contains a column.- Accepts both an object that implements `Column` and a `str`. The latter- case being interpreted as the name of the column.+ Accepts both an object that implements `Column` (matched by+ equality against this table's columns) and a `str` (interpreted+ as the column name). Typed against `Column` rather than+ `ColumnType` because `ColumnType` is covariant — input positions+ must accept the wider `Column` type."""if not self.columns:return Falsediff --git a/posthog/temporal/data_imports/sources/mysql/mysql.py b/posthog/temporal/data_imports/sources/mysql/mysql.pyindex 30b86173dd5a..62b2043e9c91 100644--- a/posthog/temporal/data_imports/sources/mysql/mysql.py+++ b/posthog/temporal/data_imports/sources/mysql/mysql.py@@ -1,11 +1,25 @@+"""MySQL driver for PostHog's data-warehouse import pipeline.++Everything MySQL-specific — connection lifecycle (with SSH tunnel),+schema listing, per-cursor metadata for the streaming sync, the dlt+pipeline build, type conversions, the `FORCE INDEX` bad-plan fallback —+lives on `MySQLImplementation`. The source-class `MySQLSource` is a+thin PostHog-layer wrapper that just holds an instance and validates+credentials.++Module-level free helpers (`_build_query`, `_sanitize_identifier`,+`_safe_convert_date`, `_safe_convert_datetime`, `_is_bad_plan_timeout`)+are pure functions used by `MySQLImplementation` and exercised directly+by unit tests. They take no MySQL-driver state and are fine as+module-scope primitives.+"""+from __future__ import annotations-import re-import mathimport datetimeimport collections-from collections.abc import Callable, Iterator-from contextlib import _GeneratorContextManager+from collections.abc import Iterator+from contextlib import contextmanagerfrom typing import Anyfrom django.conf import settings@@ -20,22 +34,36 @@ from structlog.types import FilteringBoundLoggerfrom posthog.exceptions_capture import capture_exceptionfrom posthog.temporal.data_imports.naming_convention import NamingConvention-from posthog.temporal.data_imports.pipelines.helpers import (- incremental_type_to_initial_value,- incremental_type_to_operator,-)-from posthog.temporal.data_imports.pipelines.pipeline.consts import DEFAULT_CHUNK_SIZE, DEFAULT_TABLE_SIZE_BYTES-from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponsefrom posthog.temporal.data_imports.pipelines.pipeline.utils import (DEFAULT_NUMERIC_PRECISION,DEFAULT_NUMERIC_SCALE,- DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES,build_pyarrow_decimal_type,table_from_iterator,)-from posthog.temporal.data_imports.sources.common.sql import Column, Table+from posthog.temporal.data_imports.sources.common.mixins import open_ssh_tunnel+from posthog.temporal.data_imports.sources.common.sql import (+ BacktickIdentifierQuoter,+ Column,+ InvalidIdentifierError,+ SelectQueryBuilder,+ Table,+)+from posthog.temporal.data_imports.sources.common.sql.implementation import SQLSourceImplementation, TableStats+from posthog.temporal.data_imports.sources.common.sql.incremental import IncrementalFieldFilter+from posthog.temporal.data_imports.sources.generated_configs import MySQLSourceConfig++from products.data_warehouse.backend.types import IncrementalFieldType++__all__ = [+ "MySQLColumn",+ "MySQLImplementation",+ "STATEMENT_TIMEOUT_SECONDS",+ "filter_mysql_incremental_fields",+]-from products.data_warehouse.backend.types import IncrementalFieldType, PartitionSettings+_IDENTIFIER_QUOTER = BacktickIdentifierQuoter()+_QUERY_BUILDER = SelectQueryBuilder(quoter=_IDENTIFIER_QUOTER)# Applied to the row-streaming connection so large result preparation# (e.g. filesort on a multi-GB table) doesn't hit MySQL's default 60s@@ -44,6 +72,12 @@ from products.data_warehouse.backend.types import IncrementalFieldType, Partitio# net_write_timeout / net_read_timeout — PyMySQL and MySQL both take seconds.STATEMENT_TIMEOUT_SECONDS = 600 # 10 mins+# pymysql error code for "Lost connection to MySQL server during query" — the+# symptom we see when the optimizer picks a bad plan (full scan + filesort) and+# the filesort preparation exceeds a middlebox / server-side query timeout+# before any rows stream back.+_LOST_CONNECTION_DURING_QUERY_CODE = 2013+def _safe_convert_date(obj: Any) -> datetime.date | None:"""Convert MySQL date, returning None for invalid dates like '0000-00-00'."""@@ -102,72 +136,18 @@ def filter_mysql_incremental_fields(return results-def get_schemas(- host: str,- user: str,- password: str,- database: str,- schema: str,- port: int,- using_ssl: bool = True,- names: list[str] | None = None,-) -> dict[str, list[tuple[str, str, bool]]]:- """Get all tables from MySQL source schemas to sync."""-- ssl_ca: str | None = None-- if using_ssl:- ssl_ca = "/etc/ssl/cert.pem" if settings.DEBUG else "/etc/ssl/certs/ca-certificates.crt"-- connection = pymysql.connect(- host=host,- port=port,- database=database,- user=user,- password=password,- connect_timeout=10,- ssl_ca=ssl_ca,- )-- with connection.cursor() as cursor:- params: dict = {"schema": schema}- names_filter = ""- if names:- params["names"] = tuple(names)- names_filter = "AND table_name IN %(names)s"-- cursor.execute(- "SELECT table_name, column_name, data_type, is_nullable"- " FROM information_schema.columns"- f" WHERE table_schema = %(schema)s {names_filter}"- " ORDER BY table_name ASC",- params,- )- result = cursor.fetchall()-- schema_list: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)- for row in result:- schema_list[row[0]].append((row[1], row[2], row[3] == "YES"))-- connection.close()-- return schema_list--def _sanitize_identifier(identifier: str) -> str:- if not identifier.isidentifier():- # Allow identifiers of just numbers- if re.match("^\\d+$", identifier):- return f"`{identifier}`"-- if identifier.startswith("$") or (len(identifier) > 0 and identifier[0].isdigit()):- if not identifier[1:].replace(".", "").replace("_", "").replace("-", "").replace("@", "").isidentifier():- raise ValueError(f"Invalid SQL identifier: {identifier}")+ """Back-compat shim for callers that still expect a plain `ValueError`.- if not identifier.replace(".", "").replace("_", "").replace("-", "").replace("$", "").replace("@", "").isalnum():- raise ValueError(f"Invalid SQL identifier: {identifier}")-- return f"`{identifier}`"+ New code should use `BacktickIdentifierQuoter` directly — same allowlist,+ same quoting, exposed through the shared `IdentifierQuoter` interface.+ """+ try:+ return _IDENTIFIER_QUOTER.quote(identifier)+ except InvalidIdentifierError as e:+ # Preserve the old message shape so semgrep / log-matching rules that+ # key on the old text keep working.+ raise ValueError(f"Invalid SQL identifier: {identifier}") from edef _build_query(@@ -179,37 +159,33 @@ def _build_query(db_incremental_field_last_value: Any | None,force_index_name: str | None = None,) -> tuple[str, dict[str, Any]]:- table = f"{_sanitize_identifier(schema)}.{_sanitize_identifier(table_name)}"- hint = f" FORCE INDEX ({_sanitize_identifier(force_index_name)})" if force_index_name else ""-- query = f"SELECT * FROM {table}{hint}"+ hint: str | None = None+ if force_index_name is not None:+ # Sanitize before building the hint — bad names must fail fast.+ hint = f"FORCE INDEX ({_IDENTIFIER_QUOTER.quote(force_index_name)})"if not should_use_incremental_field:- return query, {}+ result = _QUERY_BUILDER.select_all(+ schema=schema,+ table_name=table_name,+ extra_table_hint=hint,+ )+ params = result.params if isinstance(result.params, dict) else {}+ return result.sql, paramsif incremental_field is None or incremental_field_type is None:raise ValueError("incremental_field and incremental_field_type can't be None")- if db_incremental_field_last_value is None:- db_incremental_field_last_value = incremental_type_to_initial_value(incremental_field_type)-- operator = incremental_type_to_operator(incremental_field_type)- query = (- f"SELECT * FROM {table}{hint}"- f" WHERE {_sanitize_identifier(incremental_field)} {operator} %(incremental_value)s"- f" ORDER BY {_sanitize_identifier(incremental_field)} ASC"+ result = _QUERY_BUILDER.select_all(+ schema=schema,+ table_name=table_name,+ incremental_field=incremental_field,+ incremental_field_type=incremental_field_type,+ incremental_last_value=db_incremental_field_last_value,+ extra_table_hint=hint,)-- return query, {- "incremental_value": db_incremental_field_last_value,- }---# pymysql error code for "Lost connection to MySQL server during query" — the-# symptom we see when the optimizer picks a bad plan (full scan + filesort) and-# the filesort preparation exceeds a middlebox / server-side query timeout-# before any rows stream back.-_LOST_CONNECTION_DURING_QUERY_CODE = 2013+ params = result.params if isinstance(result.params, dict) else {}+ return result.sql, paramsdef _is_bad_plan_timeout(e: pymysql.err.OperationalError) -> bool:@@ -222,313 +198,16 @@ def _is_bad_plan_timeout(e: pymysql.err.OperationalError) -> bool:return code == _LOST_CONNECTION_DURING_QUERY_CODE-def _find_index_for_cursor(- cursor: Cursor,- schema: str,- table_name: str,- cursor_field: str,- logger: FilteringBoundLogger,-) -> str | None:- """Return the name of an index whose leading column is `cursor_field`.-- Used to target a `FORCE INDEX` hint at the right index when the optimizer- picks a full table scan over the incremental field's index. Returns None- when no usable index exists — callers should fall through to the original- error in that case (same behavior as today, with a clearer log).- """- try:- query = f"SHOW INDEX FROM {_sanitize_identifier(schema)}.{_sanitize_identifier(table_name)}"- cursor.execute(query)- rows = cursor.fetchall()- column_names = [col[0] for col in cursor.description or []]- # SHOW INDEX column positions vary by MySQL version; look them up by name.- try:- key_name_idx = column_names.index("Key_name")- seq_idx = column_names.index("Seq_in_index")- column_idx = column_names.index("Column_name")- except ValueError:- logger.debug("SHOW INDEX returned unexpected columns: %s", column_names)- return None-- for row in rows:- if row[column_idx] == cursor_field and row[seq_idx] == 1:- return row[key_name_idx]- return None- except Exception as e:- logger.debug(f"_find_index_for_cursor failed: {e}", exc_info=e)- return None---def _explain_query(cursor: Cursor, query: str, query_args: dict[str, Any], logger: FilteringBoundLogger) -> None:- """Log the MySQL EXPLAIN output for `query` at debug level.-- Useful for diagnosing sync failures on large tables: reveals whether the- optimizer chose a full table scan + filesort (the failure mode where- nothing streams back before middlebox/query timeouts) vs. a range scan- on the incremental index.- """- try:- explain_query = f"EXPLAIN {query}"- logger.debug(f"Running EXPLAIN on: {query}")- cursor.execute(explain_query, query_args)- rows = cursor.fetchall()- column_names = [col[0] for col in cursor.description or []]- explain_lines = [str(dict(zip(column_names, row))) for row in rows]- logger.debug(f"EXPLAIN result: {' | '.join(explain_lines) if explain_lines else '(empty)'}")- except Exception as e:- logger.debug(f"EXPLAIN raised an exception: {e}", exc_info=e)- capture_exception(e)---def _get_rows_to_sync(- cursor: Cursor, inner_query: str, inner_query_args: dict[str, Any], logger: FilteringBoundLogger-) -> int:- try:- query = f"SELECT /*+ MAX_EXECUTION_TIME(60000) */ COUNT(*) FROM ({inner_query}) as t"-- cursor.execute(query, inner_query_args)- row = cursor.fetchone()-- if row is None:- logger.debug(f"_get_rows_to_sync: No results returned. Using 0 as rows to sync")- return 0-- rows_to_sync = row[0] or 0- rows_to_sync_int = int(rows_to_sync)-- logger.debug(f"_get_rows_to_sync: rows_to_sync_int={rows_to_sync_int}")-- return int(rows_to_sync)- 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 _get_partition_settings(- cursor: Cursor,- schema: str,- table_name: str,- logger: FilteringBoundLogger,- partition_size_bytes: int = DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES,-) -> PartitionSettings | None:- """Get partition settings for given MySQL table.-- To obtain partition settings, we look up `DATA_LENGTH` and `TABLE_ROWS`- from `INFORMATION_SCHEMA.TABLES`. Keep in mind that `DATA_LENGTH` only- includes size of values in clustered index. Notably, types like `TEXT` do- not store their values in the index, so the size will be underestimated- if fields like that are present. This could lead to larger than expected- partitions.-- `TABLE_ROWS` is an InnoDB estimate and can be imprecise, but it is- sufficient for partition sizing and avoids a potentially expensive- `COUNT(*)` full table scan that can cause connection timeouts on large- tables.- """- try:- query = """- SELECT- t.DATA_LENGTH AS table_size,- t.TABLE_ROWS AS row_count- FROM- information_schema.TABLES AS t- WHERE- t.TABLE_SCHEMA = %(schema)s- AND t.TABLE_NAME = %(table_name)s- """-- logger.debug(f"_get_partition_settings: running query {query}")-- cursor.execute(- query,- {- "schema": schema,- "table_name": table_name,- },- )- result = cursor.fetchone()- if result is None:- logger.debug("_get_partition_settings: no results returning None")- return None-- table_size, row_count = result-- if table_size is None or row_count is None or row_count == 0:- logger.debug(- "_get_partition_settings: table_size is None or row_count is None or row_count == 0. returning None"- )- return None-- avg_row_size = table_size / row_count- # Partition must have at least one row- partition_size = max(round(partition_size_bytes / avg_row_size), 1)- partition_count = math.floor(row_count / partition_size)-- if partition_count == 0:- logger.debug(f"_get_partition_settings: partition_count == 0, returning partition_size={partition_size}")- return PartitionSettings(partition_count=1, partition_size=partition_size)-- logger.debug(f"_get_partition_settings: partition_count={partition_count}, partition_size={partition_size}")- return PartitionSettings(partition_count=partition_count, partition_size=partition_size)- except Exception as e:- logger.debug(f"_get_partition_settings: Error: {e}. Returning None", exc_info=e)- capture_exception(e)- return None---def get_leading_index_columns_for_schemas(- host: str,- user: str,- password: str,- database: str,- schema: str,- port: int,- table_names: list[str],- using_ssl: bool = True,-) -> dict[str, set[str]] | None:- """Return the leading column of each index per table.-- `information_schema.STATISTICS` lists every index (including primary, unique,- secondary) row-per-column. `SEQ_IN_INDEX = 1` identifies the first column- of each index, which is what speeds up `WHERE col >= …` predicates.-- Returns None when discovery fails so the caller defaults to no warning.- Tables with no indexes still appear in the dict with an empty set so the- UI distinguishes them from "lookup failed".- """- if not table_names:- return {}-- result: dict[str, set[str]] = {table: set() for table in table_names}-- try:- ssl_ca: str | None = None- if using_ssl:- ssl_ca = "/etc/ssl/cert.pem" if settings.DEBUG else "/etc/ssl/certs/ca-certificates.crt"-- with pymysql.connect(- host=host,- port=port,- database=database,- user=user,- password=password,- connect_timeout=10,- ssl_ca=ssl_ca,- ) as connection:- with connection.cursor() as cursor:- cursor.execute(- """- SELECT TABLE_NAME, COLUMN_NAME- FROM information_schema.STATISTICS- WHERE TABLE_SCHEMA = %(schema)s- AND TABLE_NAME IN %(names)s- AND SEQ_IN_INDEX = 1- """,- {"schema": schema, "names": tuple(table_names)},- )- for table_name, column_name in cursor.fetchall():- result.setdefault(table_name, set()).add(column_name)- except Exception as e:- structlog.get_logger().warning("Failed to detect leading index columns for MySQL schemas", exc_info=e)- return None-- return result---def get_primary_keys_for_schemas(- host: str,- user: str,- password: str,- database: str,- schema: str,- port: int,- table_names: list[str],- using_ssl: bool = True,-) -> dict[str, list[str] | None]:- """Detect primary keys for all tables in a single query."""- result: dict[str, list[str] | None] = dict.fromkeys(table_names)-- try:- ssl_ca: str | None = None- if using_ssl:- ssl_ca = "/etc/ssl/cert.pem" if settings.DEBUG else "/etc/ssl/certs/ca-certificates.crt"-- with pymysql.connect(- host=host,- port=port,- database=database,- user=user,- password=password,- connect_timeout=10,- ssl_ca=ssl_ca,- ) as connection:- with connection.cursor() as cursor:- cursor.execute(- """- SELECT tc.TABLE_NAME, kcu.COLUMN_NAME- FROM information_schema.TABLE_CONSTRAINTS tc- JOIN information_schema.KEY_COLUMN_USAGE kcu- ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME- AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA- AND tc.TABLE_NAME = kcu.TABLE_NAME- WHERE tc.TABLE_SCHEMA = %(schema)s- AND tc.TABLE_NAME IN %(names)s- AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'- """,- {"schema": schema, "names": tuple(table_names)},- )- rows = cursor.fetchall()-- pks: dict[str, list[str]] = collections.defaultdict(list)- for table_name, column_name in rows:- pks[table_name].append(column_name)-- for table_name, pk_cols in pks.items():- result[table_name] = pk_cols- except Exception as e:- structlog.get_logger().warning("Failed to detect primary keys for MySQL schemas", exc_info=e)-- return result---def _get_primary_keys(cursor: Cursor, schema: str, table_name: str) -> list[str] | None:- query = """- SELECT COLUMN_NAME- FROM INFORMATION_SCHEMA.COLUMNS- WHERE TABLE_SCHEMA = %(schema)s- AND TABLE_NAME = %(table_name)s- AND COLUMN_KEY = 'PRI'"""-- cursor.execute(- query,- {- "schema": schema,- "table_name": table_name,- },- )- rows = cursor.fetchall()- if len(rows) > 0:- return [row[0] for row in rows]-- return None--class MySQLColumn(Column):- """Implementation of the `Column` protocol for a MySQL source.+ """`Column` for a MySQL source — carries enough type info to build a PyArrow field.Attributes:- name: The column's name.- data_type: The name of the column's data type as described in- https://www.postgresql.org/docs/current/datatype.html.- column_type:- nullable: Whether the column is nullable or not.- numeric_precision: The number of significant digits. Only used with- numeric `data_type`s, otherwise `None`.- numeric_scale: The number of significant digits to the right of- decimal point. Only used with numeric `data_type`s, otherwise- `None`.+ name: Column name.+ data_type: Base MySQL type (`int`, `varchar`, `decimal`, …).+ column_type: Full type string including modifiers (e.g. `int(10) unsigned`),+ used to detect `unsigned` which affects the PyArrow integer width.+ nullable: Whether the column is nullable in MySQL.+ numeric_precision / numeric_scale: Populated only for `decimal` / `numeric`."""def __init__(@@ -551,15 +230,13 @@ class MySQLColumn(Column):"""Return a `pyarrow.Field` that closely matches this column."""arrow_type: pa.DataType- # Note that deltalake doesn't support unsigned types, so we need to convert integer types to larger types- # For example an uint32 should support values up to 2^32, but deltalake will only support 2^31- # so in order to support unsigned types we need to convert to int64+ # deltalake doesn't support unsigned types, so unsigned ints are+ # widened to the next signed type that can hold their range.is_unsigned = "unsigned" in self.column_type- # Map MySQL type names to PyArrow typesmatch self.data_type.lower():case "bigint":- # There's no larger type than (u)int64+ # No larger type than (u)int64 — keep unsigned semantics.arrow_type = pa.uint64() if is_unsigned else pa.int64()case "int" | "integer" | "mediumint":arrow_type = pa.uint64() if is_unsigned else pa.int32()@@ -568,9 +245,8 @@ class MySQLColumn(Column):case "tinyint":arrow_type = pa.uint16() if is_unsigned else pa.int8()case "decimal" | "numeric":- if not self.numeric_precision or not self.numeric_scale:+ if self.numeric_precision is None or self.numeric_scale is None:raise TypeError("expected `numeric_precision` and `numeric_scale` to be `int`, got `NoneType`")-arrow_type = build_pyarrow_decimal_type(self.numeric_precision, self.numeric_scale)case "float":arrow_type = pa.float32()@@ -579,8 +255,8 @@ class MySQLColumn(Column):case "varchar" | "char" | "text" | "mediumtext" | "longtext":arrow_type = pa.string()case "date":- # MySQL allows zero dates ('0000-00-00') which become None,- # so date columns must always be nullable in the Arrow schema+ # MySQL allows zero dates ('0000-00-00') which we map to None,+ # so date columns must always be nullable in the Arrow schema.arrow_type = pa.date32()return pa.field(self.name, arrow_type, nullable=True)case "datetime" | "timestamp":@@ -596,7 +272,7 @@ class MySQLColumn(Column):arrow_type = pa.string()case "json":arrow_type = pa.string()- case _ if self.data_type.endswith("[]"): # Array types (though not native in MySQL)+ case _ if self.data_type.endswith("[]"): # Array types (not native in MySQL)arrow_type = pa.string()case _:arrow_type = pa.string()@@ -604,192 +280,450 @@ class MySQLColumn(Column):return pa.field(self.name, arrow_type, nullable=self.nullable)-def _get_table(cursor: Cursor, schema: str, table_name: str) -> Table[MySQLColumn]:- query = """- SELECT- column_name,- data_type,- column_type,- is_nullable,- numeric_precision,- numeric_scale- FROM- information_schema.columns- WHERE- table_schema = %(schema)s- AND table_name = %(table_name)s"""-- cursor.execute(- query,- {- "schema": schema,- "table_name": table_name,- },- )+class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Connection, Cursor]):+ """MySQL driver implementation paired with `MySQLSource`.++ One class owns everything MySQL-specific: the SSH tunnel + pymysql+ connection lifecycle, `information_schema`-style batch queries used+ during schema listing, per-cursor metadata used during the streaming+ sync (primary keys, column types, row counts, partition/chunk sizing,+ `FORCE INDEX` index lookup, `EXPLAIN` diagnostics), and the dlt+ pipeline factory (`build_pipeline`).+ """++ # ------------------------------------------------------------------+ # Connection lifecycle+ # ------------------------------------------------------------------++ @contextmanager+ def connect(+ self,+ config: MySQLSourceConfig,+ *,+ read_timeout: int | None = None,+ ) -> Iterator[pymysql.Connection]:+ """Open a pymysql connection for the duration of the context.++ Opens the SSH tunnel (if configured), then connects with the+ MySQL-wide conventions: safe date/datetime converters, and a+ PlanetScale workload hint injected automatically when the host+ resolves to a `*.psdb.cloud` address. Callers only vary one+ thing — the streaming path sets `read_timeout=STATEMENT_TIMEOUT_SECONDS`+ so multi-GB filesorts don't drop on middlebox timeouts before the+ first rows are ready.+ """+ ssl_ca: str | None = None+ if config.using_ssl:+ ssl_ca = "/etc/ssl/cert.pem" if settings.DEBUG else "/etc/ssl/certs/ca-certificates.crt"++ with open_ssh_tunnel(config) as (host, port):+ kwargs: dict[str, Any] = {+ "host": host,+ "port": port,+ "database": config.database,+ "user": config.user,+ "password": config.password,+ "connect_timeout": 10,+ "ssl_ca": ssl_ca,+ "conv": _MYSQL_SAFE_CONVERSIONS,+ "init_command": "SET workload = 'OLAP';" if host.endswith("psdb.cloud") else None,+ }+ if read_timeout is not None:+ kwargs["read_timeout"] = read_timeout+ with pymysql.connect(**kwargs) as conn:+ yield conn++ # ------------------------------------------------------------------+ # Listing — batch queries run once during `get_schemas`+ # ------------------------------------------------------------------++ def get_columns(+ self,+ conn: pymysql.Connection,+ config: MySQLSourceConfig,+ names: list[str] | None,+ ) -> dict[str, list[tuple[str, str, bool]]]:+ params: dict[str, Any] = {"schema": config.schema}+ names_filter = ""+ if names:+ params["names"] = tuple(names)+ names_filter = "AND table_name IN %(names)s"- numeric_data_types = {"numeric", "decimal"}- columns = []- for name, data_type, column_type, nullable, numeric_precision_candidate, numeric_scale_candidate in cursor:- if data_type in numeric_data_types:- numeric_precision = numeric_precision_candidate or DEFAULT_NUMERIC_PRECISION- numeric_scale = numeric_scale_candidate or DEFAULT_NUMERIC_SCALE- else:- numeric_precision = None- numeric_scale = None-- columns.append(- MySQLColumn(- name=name,- data_type=data_type,- column_type=column_type,- nullable=nullable,- numeric_precision=numeric_precision,- numeric_scale=numeric_scale,+ with conn.cursor() as cursor:+ cursor.execute(+ "SELECT table_name, column_name, data_type, is_nullable"+ " FROM information_schema.columns"+ f" WHERE table_schema = %(schema)s {names_filter}"+ " ORDER BY table_name ASC",+ params,)- )+ rows = cursor.fetchall()- return Table(- name=table_name,- parents=(schema,),- columns=columns,- )+ result: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)+ for table_name, column_name, data_type, is_nullable in rows:+ result[table_name].append((column_name, data_type, is_nullable == "YES"))+ return dict(result)+ def get_primary_keys(+ self,+ conn: pymysql.Connection,+ config: MySQLSourceConfig,+ tables: list[str],+ ) -> dict[str, list[str] | None]:+ """Detect primary keys for every table in a single query.++ Permission-sensitive — some MySQL deployments restrict access to+ `information_schema.TABLE_CONSTRAINTS`. Swallow and log any+ failure so schema discovery keeps working without PKs.+ """+ result: dict[str, list[str] | None] = dict.fromkeys(tables)+ if not tables:+ return result-def _get_table_average_row_size(- cursor: Cursor,- schema: str,- table_name: str,- should_use_incremental_field: bool,- incremental_field: str | None,- incremental_field_type: IncrementalFieldType | None,- db_incremental_field_last_value: Any | None,- logger: FilteringBoundLogger,-) -> int | None:- """Calculate average row size for a MySQL table by sampling the data.- Uses LENGTH() functions to calculate the actual size of each column's data- in a sample of rows, similar to how MSSQL uses DATALENGTH().- """- try:- # Build the query to sample from- inner_query, inner_query_args = _build_query(- schema,- table_name,- should_use_incremental_field,- incremental_field,- incremental_field_type,- db_incremental_field_last_value,- )+ try:+ with conn.cursor() as cursor:+ cursor.execute(+ """+ SELECT tc.TABLE_NAME, kcu.COLUMN_NAME+ FROM information_schema.TABLE_CONSTRAINTS tc+ JOIN information_schema.KEY_COLUMN_USAGE kcu+ ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME+ AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA+ AND tc.TABLE_NAME = kcu.TABLE_NAME+ WHERE tc.TABLE_SCHEMA = %(schema)s+ AND tc.TABLE_NAME IN %(names)s+ AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'+ """,+ {"schema": config.schema, "names": tuple(tables)},+ )+ rows = cursor.fetchall()+ except Exception as e:+ structlog.get_logger().warning("Failed to detect primary keys for MySQL schemas", exc_info=e)+ return result++ pks: dict[str, list[str]] = collections.defaultdict(list)+ for table_name, column_name in rows:+ pks[table_name].append(column_name)+ for table_name, pk_cols in pks.items():+ result[table_name] = pk_cols+ return result++ def get_incremental_filter(self) -> IncrementalFieldFilter:+ return filter_mysql_incremental_fields++ def get_leading_index_columns(+ self,+ conn: pymysql.Connection,+ config: MySQLSourceConfig,+ tables: list[str],+ ) -> dict[str, set[str]] | None:+ """Return the leading column of each index per table.++ `information_schema.STATISTICS` lists every index (primary, unique,+ secondary) one row per column. `SEQ_IN_INDEX = 1` identifies the+ first column of each index, which is what speeds up+ `WHERE col >= …` predicates. Returns `None` when discovery fails+ so the caller defaults to no warning; tables with no indexes still+ appear with an empty set so the UI can distinguish them from+ "lookup failed".+ """+ if not tables:+ return {}- # Get column names from the table+ result: dict[str, set[str]] = {table: set() for table in tables}+ try:+ with conn.cursor() as cursor:+ cursor.execute(+ """+ SELECT TABLE_NAME, COLUMN_NAME+ FROM information_schema.STATISTICS+ WHERE TABLE_SCHEMA = %(schema)s+ AND TABLE_NAME IN %(names)s+ AND SEQ_IN_INDEX = 1+ """,+ {"schema": config.schema, "names": tuple(tables)},+ )+ for table_name, column_name in cursor.fetchall():+ result.setdefault(table_name, set()).add(column_name)+ except Exception as e:+ structlog.get_logger().warning("Failed to detect leading index columns for MySQL schemas", exc_info=e)+ return None+ return result++ # ------------------------------------------------------------------+ # Per-cursor metadata — used during `build_pipeline`+ # ------------------------------------------------------------------++ def get_primary_keys_for_table(self, cursor: Cursor, schema: str, table_name: str) -> list[str] | None:+ """Return the primary-key column names for a single table, or None."""cursor.execute(- "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = %(schema)s AND TABLE_NAME = %(table_name)s ORDER BY ORDINAL_POSITION",+ """+ SELECT COLUMN_NAME+ FROM INFORMATION_SCHEMA.COLUMNS+ WHERE TABLE_SCHEMA = %(schema)s+ AND TABLE_NAME = %(table_name)s+ AND COLUMN_KEY = 'PRI'+ """,{"schema": schema, "table_name": table_name},)rows = cursor.fetchall()- if not rows:- logger.debug(f"_get_table_average_row_size: No columns found.")- return None+ if len(rows) > 0:+ return [row[0] for row in rows]+ return None- columns = [row[0] for row in rows]+ def get_table_metadata(self, cursor: Cursor, schema: str, table_name: str) -> Table[MySQLColumn]:+ """Return rich column metadata for building a PyArrow schema."""+ cursor.execute(+ """+ SELECT+ column_name,+ data_type,+ column_type,+ is_nullable,+ numeric_precision,+ numeric_scale+ FROM+ information_schema.columns+ WHERE+ table_schema = %(schema)s+ AND table_name = %(table_name)s+ """,+ {"schema": schema, "table_name": table_name},+ )- # Build the LENGTH sum for each column with proper sanitization- length_sum = " + ".join(f"LENGTH(COALESCE({_sanitize_identifier(col)}, ''))" for col in columns)+ numeric_data_types = {"numeric", "decimal"}+ columns = []+ for name, data_type, column_type, nullable, numeric_precision_candidate, numeric_scale_candidate in cursor:+ if data_type in numeric_data_types:+ numeric_precision = (+ numeric_precision_candidate+ if numeric_precision_candidate is not None+ else DEFAULT_NUMERIC_PRECISION+ )+ numeric_scale = (+ numeric_scale_candidate if numeric_scale_candidate is not None else DEFAULT_NUMERIC_SCALE+ )+ else:+ numeric_precision = None+ numeric_scale = None++ columns.append(+ MySQLColumn(+ name=name,+ data_type=data_type,+ column_type=column_type,+ nullable=nullable,+ numeric_precision=numeric_precision,+ numeric_scale=numeric_scale,+ )+ )- # NOTE: length_sum and inner_query are constructed with sanitized identifiers only.- # All column names are sanitized with _sanitize_identifier, and inner_query is built with same approach.- # No user-supplied values are directly interpolated here.- size_query = "SELECT AVG(" + length_sum + ") as avg_row_size FROM (" + inner_query + " LIMIT 1000) as t"+ return Table(name=table_name, parents=(schema,), columns=columns)- cursor.execute(size_query, inner_query_args)- row = cursor.fetchone()+ def get_rows_to_sync(+ self,+ cursor: Cursor,+ inner_query: str,+ inner_query_args: Any,+ logger: FilteringBoundLogger,+ ) -> int:+ """Count the rows the given `inner_query` will produce. Returns 0 on error."""+ try:+ # The MAX_EXECUTION_TIME optimizer hint bounds this probe at 60s —+ # we'd rather return 0 and let the sync proceed than block here.+ query = f"SELECT /*+ MAX_EXECUTION_TIME(60000) */ COUNT(*) FROM ({inner_query}) as t"- if row is None or row[0] is None:- logger.debug(f"_get_table_average_row_size: No results returned.")- return None+ cursor.execute(query, inner_query_args)+ row = cursor.fetchone()- row_size_bytes = max(row[0] or 0, 1)- return int(row_size_bytes)+ if row is None:+ logger.debug("get_rows_to_sync: No results returned. Using 0 as rows to sync")+ return 0- except Exception as e:- logger.debug(f"_get_table_average_row_size: Error: {e}.", exc_info=e)- capture_exception(e)- return None+ rows_to_sync = row[0] or 0+ rows_to_sync_int = int(rows_to_sync)+ 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 _get_table_chunk_size(- cursor: Cursor,- schema: str,- table_name: str,- should_use_incremental_field: bool,- incremental_field: str | None,- incremental_field_type: IncrementalFieldType | None,- db_incremental_field_last_value: Any | None,- logger: FilteringBoundLogger,-) -> int:- """Calculate optimal chunk size for MySQL table based on average row size."""- try:- row_size_bytes = _get_table_average_row_size(- cursor,- schema,- table_name,- should_use_incremental_field,- incremental_field,- incremental_field_type,- db_incremental_field_last_value,- logger,- )- if row_size_bytes is None:- logger.debug(- f"_get_table_chunk_size: Could not calculate row size. Using DEFAULT_CHUNK_SIZE={DEFAULT_CHUNK_SIZE}"+ def fetch_table_stats(+ self,+ cursor: Cursor,+ schema: str,+ table_name: str,+ logger: FilteringBoundLogger,+ ) -> TableStats | None:+ """Return DATA_LENGTH / TABLE_ROWS for `schema.table_name`.++ `DATA_LENGTH` only covers values in the clustered index — types+ like `TEXT` are stored off-page, so the figure can under-count.+ `TABLE_ROWS` is an InnoDB estimate. Both are close enough to+ size partitions, and cheap compared to a `COUNT(*)` full scan+ that can time out on large tables.+ """+ query = """+ SELECT+ t.DATA_LENGTH AS table_size,+ t.TABLE_ROWS AS row_count+ FROM+ information_schema.TABLES AS t+ WHERE+ t.TABLE_SCHEMA = %(schema)s+ AND t.TABLE_NAME = %(table_name)s+ """+ logger.debug(f"fetch_table_stats: running query {query}")+ cursor.execute(query, {"schema": schema, "table_name": table_name})+ result = cursor.fetchone()+ if result is None:+ logger.debug("fetch_table_stats: no results returning None")+ return None++ table_size, row_count = result+ if table_size is None or row_count is None:+ logger.debug("fetch_table_stats: missing table_size or row_count, returning None")+ return None++ return TableStats(table_size_bytes=int(table_size), row_count=int(row_count))++ def fetch_average_row_size(+ self,+ cursor: Cursor,+ schema: str,+ table_name: str,+ inner_query: str,+ inner_query_args: Any,+ logger: FilteringBoundLogger,+ ) -> int | None:+ """Sample `LENGTH(COALESCE(col, ''))` across columns on the first 1000 rows.++ Column names are pulled from `information_schema.COLUMNS`, then+ each name is passed through the identifier quoter before being+ interpolated into the `LENGTH(...)` sum. `inner_query` is the+ SELECT the sync is about to run — its identifiers were already+ quoted by the shared `SelectQueryBuilder`, and its arguments are+ rebound as parameters here. No untrusted value ever reaches raw+ SQL.+ """+ try:+ cursor.execute(+ """+ SELECT COLUMN_NAME+ FROM INFORMATION_SCHEMA.COLUMNS+ WHERE TABLE_SCHEMA = %(schema)s+ AND TABLE_NAME = %(table_name)s+ ORDER BY ORDINAL_POSITION+ """,+ {"schema": schema, "table_name": table_name},)- return DEFAULT_CHUNK_SIZE- except Exception as e:- logger.debug(f"_get_table_chunk_size: Error: {e}. Using DEFAULT_CHUNK_SIZE={DEFAULT_CHUNK_SIZE}", exc_info=e)- capture_exception(e)- return DEFAULT_CHUNK_SIZE-- chunk_size = int(DEFAULT_TABLE_SIZE_BYTES / row_size_bytes)- logger.debug(- f"_get_table_chunk_size: row_size_bytes={row_size_bytes}. DEFAULT_TABLE_SIZE_BYTES={DEFAULT_TABLE_SIZE_BYTES}. Using CHUNK_SIZE={chunk_size}"- )+ rows = cursor.fetchall()+ if not rows:+ logger.debug("fetch_average_row_size: No columns found.")+ return None++ columns = [row[0] for row in rows]+ length_sum = " + ".join(f"LENGTH(COALESCE({_IDENTIFIER_QUOTER.quote(col)}, ''))" for col in columns)+ # length_sum and inner_query are built from sanitized identifiers;+ # no user-supplied values are interpolated into the SQL itself.+ size_query = "SELECT AVG(" + length_sum + ") as avg_row_size FROM (" + inner_query + " LIMIT 1000) as t"++ cursor.execute(size_query, inner_query_args)+ row = cursor.fetchone()++ if row is None or row[0] is None:+ logger.debug("fetch_average_row_size: No results returned.")+ return None++ row_size_bytes = max(row[0] or 0, 1)+ return int(row_size_bytes)+ except Exception as e:+ logger.debug(f"fetch_average_row_size: Error: {e}.", exc_info=e)+ capture_exception(e)+ return None- return chunk_size+ def find_index_for_cursor(+ self,+ cursor: Cursor,+ schema: str,+ table_name: str,+ cursor_field: str,+ logger: FilteringBoundLogger,+ ) -> str | None:+ """Return an index whose leading column equals `cursor_field`.++ Used for the `FORCE INDEX (...)` retry when the optimizer picks+ a full table scan over the incremental field's index.+ Identifiers are quoted before being interpolated into+ `SHOW INDEX FROM ...`; `SHOW INDEX` has no parameterized form in+ MySQL.+ """+ try:+ query = f"SHOW INDEX FROM {_IDENTIFIER_QUOTER.quote(schema)}.{_IDENTIFIER_QUOTER.quote(table_name)}"+ cursor.execute(query)+ rows = cursor.fetchall()+ column_names = [col[0] for col in cursor.description or []]+ # SHOW INDEX column positions vary by MySQL version; look them up by name.+ try:+ key_name_idx = column_names.index("Key_name")+ seq_idx = column_names.index("Seq_in_index")+ column_idx = column_names.index("Column_name")+ except ValueError:+ logger.debug("SHOW INDEX returned unexpected columns: %s", column_names)+ return None++ for row in rows:+ if row[column_idx] == cursor_field and row[seq_idx] == 1:+ return row[key_name_idx]+ return None+ except Exception as e:+ logger.debug(f"find_index_for_cursor failed: {e}", exc_info=e)+ return None+ def explain_query(+ self,+ cursor: Cursor,+ query: str,+ query_args: Any,+ logger: FilteringBoundLogger,+ ) -> None:+ """Log MySQL `EXPLAIN` output for `query` at debug level.-def mysql_source(- tunnel: Callable[[], _GeneratorContextManager[tuple[str, int]]],- user: str,- password: str,- database: str,- using_ssl: bool,- schema: str,- table_names: list[str],- should_use_incremental_field: bool,- logger: FilteringBoundLogger,- db_incremental_field_last_value: Any | None,- incremental_field: str | None = None,- incremental_field_type: IncrementalFieldType | None = None,-) -> SourceResponse:- table_name = table_names[0]- if not table_name:- raise ValueError("Table name is missing")-- ssl_ca: str | None = None-- if using_ssl:- ssl_ca = "/etc/ssl/cert.pem" if settings.DEBUG else "/etc/ssl/certs/ca-certificates.crt"-- with tunnel() as (host, port):- with pymysql.connect(- host=host,- port=port,- database=database,- user=user,- password=password,- connect_timeout=10,- ssl_ca=ssl_ca,- conv=_MYSQL_SAFE_CONVERSIONS,- ) as connection:+ Used to diagnose sync failures on large tables — reveals whether+ the optimizer chose full-scan + filesort vs. a range scan on the+ incremental index.+ """+ try:+ explain_query = f"EXPLAIN {query}"+ logger.debug(f"Running EXPLAIN on: {query}")+ cursor.execute(explain_query, query_args)+ rows = cursor.fetchall()+ column_names = [col[0] for col in cursor.description or []]+ explain_lines = [str(dict(zip(column_names, row))) for row in rows]+ logger.debug(f"EXPLAIN result: {' | '.join(explain_lines) if explain_lines else '(empty)'}")+ except Exception as e:+ logger.debug(f"EXPLAIN raised an exception: {e}", exc_info=e)+ capture_exception(e)++ # ------------------------------------------------------------------+ # Pipeline build — the dlt `SourceResponse` for a single table+ # ------------------------------------------------------------------++ def build_pipeline(self, config: MySQLSourceConfig, inputs: SourceInputs) -> SourceResponse:+ table_name = inputs.schema_name+ if not table_name:+ raise ValueError("Table name is missing")++ schema = config.schema+ logger = inputs.logger+ should_use_incremental_field = inputs.should_use_incremental_field+ incremental_field = inputs.incremental_field+ incremental_field_type = inputs.incremental_field_type+ db_incremental_field_last_value = inputs.db_incremental_field_last_value++ with self.connect(config) as connection:with connection.cursor() as cursor:inner_query, inner_query_args = _build_query(schema,@@ -800,23 +734,14 @@ def mysql_source(db_incremental_field_last_value,)- primary_keys = _get_primary_keys(cursor, schema, table_name)- table = _get_table(cursor, schema, table_name)- logger.debug(f"Source schema: {table.to_arrow_schema()}")- rows_to_sync = _get_rows_to_sync(cursor, inner_query, inner_query_args, logger)- # define chunk_size- chunk_size = _get_table_chunk_size(- cursor,- schema,- table_name,- should_use_incremental_field,- incremental_field,- incremental_field_type,- db_incremental_field_last_value,- logger,- )+ primary_keys = self.get_primary_keys_for_table(cursor, schema, table_name)+ table = self.get_table_metadata(cursor, schema, table_name)+ arrow_schema = table.to_arrow_schema()+ logger.debug(f"Source schema: {arrow_schema}")+ rows_to_sync = self.get_rows_to_sync(cursor, inner_query, inner_query_args, logger)+ chunk_size = self.get_chunk_size(cursor, schema, table_name, inner_query, inner_query_args, logger)partition_settings = (- _get_partition_settings(cursor, schema, table_name, logger)+ self.get_partition_settings(cursor, schema, table_name, logger)if should_use_incremental_fieldelse None)@@ -825,44 +750,28 @@ def mysql_source(if primary_keys is None and "id" in table:primary_keys = ["id"]- arrow_schema = table.to_arrow_schema()+ def _stream_with_optional_force_index(force_index_name: str | None) -> Iterator[Any]:+ """Open a fresh connection and stream rows.- def _stream_with_optional_force_index(force_index_name: str | None) -> Iterator[Any]:- """Open a fresh connection and stream rows from `db_incremental_field_last_value`.-- The pipeline itself persists the per-batch cursor value (see- `update_incremental_field_values`), so a retry that restarts from the- original starting cursor is correct but occasionally replays a few- already-processed rows; the delta merge dedupes by primary key.- """- with tunnel() as (host, port):- # PlanetScale needs this to be set- init_command = "SET workload = 'OLAP';" if host.endswith("psdb.cloud") else None-- with pymysql.connect(- host=host,- port=port,- database=database,- user=user,- password=password,- connect_timeout=10,- read_timeout=STATEMENT_TIMEOUT_SECONDS,- ssl_ca=ssl_ca,- init_command=init_command,- conv=_MYSQL_SAFE_CONVERSIONS,- ) as connection:+ The pipeline itself persists the per-batch cursor value (see+ `update_incremental_field_values`), so a retry that restarts+ from the original starting cursor is correct but occasionally+ replays a few already-processed rows; the delta merge+ dedupes by primary key.+ """+ with self.connect(config, read_timeout=STATEMENT_TIMEOUT_SECONDS) as streaming_connection:# Bump server-side timeouts for large table scans. The# defaults (60s each) are too low for multi-GB unbuffered- # queries — the server drops the connection before the first- # rows are ready.+ # queries — the server drops the connection before the+ # first rows are ready.try:- with connection.cursor() as setup_cursor:+ with streaming_connection.cursor() as setup_cursor:setup_cursor.execute(f"SET SESSION net_write_timeout = {STATEMENT_TIMEOUT_SECONDS}, net_read_timeout = {STATEMENT_TIMEOUT_SECONDS}")except Exception as e:logger.warning(f"Failed to set session timeouts on MySQL sync connection: {e}")- with connection.cursor(SSCursor) as cursor:+ with streaming_connection.cursor(SSCursor) as ss_cursor:query, args = _build_query(schema,table_name,@@ -874,98 +783,86 @@ def mysql_source()logger.debug(f"MySQL query: {query.format(args)}")- # EXPLAIN before the streaming query to help diagnose- # failures where MySQL picks full scan + filesort over- # the incremental index. _explain_query consumes its- # rows via fetchall(), leaving the cursor in a clean+ # EXPLAIN before the streaming query to help+ # diagnose failures where MySQL picks full scan+ # + filesort over the incremental index.+ # `explain_query` consumes its rows via+ # fetchall(), leaving the cursor in a clean# state for the streaming execute() below.- _explain_query(cursor, query, args, logger)+ self.explain_query(ss_cursor, query, args, logger)- cursor.execute(query, args)+ ss_cursor.execute(query, args)- column_names = [column[0] for column in cursor.description or []]+ column_names = [column[0] for column in ss_cursor.description or []]while True:# use chunk_size to fetch rows instead of DEFAULT_CHUNK_SIZE- rows = cursor.fetchmany(chunk_size)- if not rows:+ batch = ss_cursor.fetchmany(chunk_size)+ if not batch:break- yield table_from_iterator((dict(zip(column_names, row)) for row in rows), arrow_schema)-- def get_rows() -> Iterator[Any]:- # Track whether any batch reached the pipeline. If one did, the retry- # path can't safely restart from the original cursor: the delta merge- # only dedupes rows for `incremental` writes into an existing table- # (see `delta_table_helper.write_to_deltalake`), so full-refresh and- # first-ever-sync scenarios would get silent duplicates on replay.- # The observed bad-plan failure fails before any rows stream, so this- # guard is defensive — it enforces the invariant the PR assumes.- yielded_any = False- try:- for chunk in _stream_with_optional_force_index(force_index_name=None):- yielded_any = True- yield chunk- return- except pymysql.err.OperationalError as e:- if not _is_bad_plan_timeout(e):- raise- if yielded_any:- logger.warning(- f"Streaming query died with bad-plan timeout (error {e.args[0] if e.args else '?'}) "- f"after already yielding rows — skipping FORCE INDEX fallback to avoid duplicates."- )- raise- logger.warning(- f"Streaming query died with bad-plan timeout (error {e.args[0] if e.args else '?'}). "- f"Attempting FORCE INDEX fallback."- )- if not should_use_incremental_field or not incremental_field:- # Without an incremental field there's no cursor to force an index on.+ yield table_from_iterator((dict(zip(column_names, row)) for row in batch), arrow_schema)++ def get_rows() -> Iterator[Any]:+ # Track whether any batch reached the pipeline. If one did,+ # the retry path can't safely restart from the original+ # cursor: the delta merge only dedupes rows for `incremental`+ # writes into an existing table (see+ # `delta_table_helper.write_to_deltalake`), so full-refresh+ # and first-ever-sync scenarios would get silent duplicates+ # on replay. The observed bad-plan failure fails before any+ # rows stream, so this guard is defensive — it enforces the+ # invariant the PR assumes.+ yielded_any = False+ try:+ for chunk in _stream_with_optional_force_index(force_index_name=None):+ yielded_any = True+ yield chunk+ return+ except pymysql.err.OperationalError as e:+ if not _is_bad_plan_timeout(e):+ raise+ if yielded_any:+ logger.warning(+ f"Streaming query died with bad-plan timeout (error {e.args[0] if e.args else '?'}) "+ f"after already yielding rows — skipping FORCE INDEX fallback to avoid duplicates."+ )+ raiselogger.warning(- "Bad-plan timeout hit, but sync has no incremental field — cannot apply FORCE INDEX fallback."+ f"Streaming query died with bad-plan timeout (error {e.args[0] if e.args else '?'}). "+ f"Attempting FORCE INDEX fallback.")- raise-- with tunnel() as (host, port):- # Match the streaming connection's PlanetScale workload hint so- # future proxy-side policy changes don't silently break the probe.- init_command = "SET workload = 'OLAP';" if host.endswith("psdb.cloud") else None-- with pymysql.connect(- host=host,- port=port,- database=database,- user=user,- password=password,- connect_timeout=10,- ssl_ca=ssl_ca,- init_command=init_command,- conv=_MYSQL_SAFE_CONVERSIONS,- ) as probe_connection:+ if not should_use_incremental_field or not incremental_field:+ # Without an incremental field there's no cursor to force an index on.+ logger.warning(+ "Bad-plan timeout hit, but sync has no incremental field — cannot apply FORCE INDEX fallback."+ )+ raise++ with self.connect(config) as probe_connection:with probe_connection.cursor() as probe_cursor:- force_index_name = _find_index_for_cursor(+ force_index_name = self.find_index_for_cursor(probe_cursor, schema, table_name, incremental_field, logger)- if not force_index_name:- logger.warning(- f"Bad-plan timeout hit and no usable index on "- f"{schema}.{table_name}.{incremental_field} — cannot apply FORCE INDEX fallback. "- f"Customer should add an index on the incremental field."- )- raise+ if not force_index_name:+ logger.warning(+ f"Bad-plan timeout hit and no usable index on "+ f"{schema}.{table_name}.{incremental_field} — cannot apply FORCE INDEX fallback. "+ f"Customer should add an index on the incremental field."+ )+ raise- logger.warning(f"Retrying streaming query with FORCE INDEX ({force_index_name}) after bad-plan timeout")- yield from _stream_with_optional_force_index(force_index_name)+ logger.warning(f"Retrying streaming query with FORCE INDEX ({force_index_name}) after bad-plan timeout")+ yield from _stream_with_optional_force_index(force_index_name)- name = NamingConvention.normalize_identifier(table_name)+ name = NamingConvention.normalize_identifier(table_name)- return SourceResponse(- name=name,- items=get_rows,- primary_keys=primary_keys,- partition_count=partition_settings.partition_count if partition_settings else None,- partition_size=partition_settings.partition_size if partition_settings else None,- rows_to_sync=rows_to_sync,- )+ return SourceResponse(+ name=name,+ items=get_rows,+ primary_keys=primary_keys,+ partition_count=partition_settings.partition_count if partition_settings else None,+ partition_size=partition_settings.partition_size if partition_settings else None,+ rows_to_sync=rows_to_sync,+ )diff --git a/posthog/temporal/data_imports/sources/mysql/source.py b/posthog/temporal/data_imports/sources/mysql/source.pyindex beed6bbfe3a1..d7d6a8000ca9 100644--- a/posthog/temporal/data_imports/sources/mysql/source.py+++ b/posthog/temporal/data_imports/sources/mysql/source.py@@ -1,6 +1,5 @@from typing import Optional, cast-import structlogfrom sshtunnel import BaseSSHTunnelForwarderErrorfrom posthog.schema import (@@ -15,26 +14,24 @@ from posthog.schema import ()from posthog.exceptions_capture import capture_exception-from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.sources.common.base import FieldTypefrom posthog.temporal.data_imports.sources.common.mixins import SSHTunnelMixin, ValidateDatabaseHostMixinfrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry-from posthog.temporal.data_imports.sources.common.schema import SourceSchema-from posthog.temporal.data_imports.sources.common.sql import resolve_detected_primary_keys+from posthog.temporal.data_imports.sources.common.sql.base import SQLSourcefrom posthog.temporal.data_imports.sources.generated_configs import MySQLSourceConfig-from posthog.temporal.data_imports.sources.mysql.mysql import (- filter_mysql_incremental_fields,- get_leading_index_columns_for_schemas as get_mysql_leading_index_columns_for_schemas,- get_primary_keys_for_schemas as get_mysql_primary_keys_for_schemas,- get_schemas as get_mysql_schemas,- mysql_source,-)+from posthog.temporal.data_imports.sources.mysql.mysql import MySQLImplementation++from products.data_warehouse.backend.types import ExternalDataSourceType-from products.data_warehouse.backend.types import ExternalDataSourceType, IncrementalField+_MYSQL_IMPLEMENTATION = MySQLImplementation()@SourceRegistry.register-class MySQLSource(SimpleSource[MySQLSourceConfig], SSHTunnelMixin, ValidateDatabaseHostMixin):+class MySQLSource(SQLSource[MySQLSourceConfig], SSHTunnelMixin, ValidateDatabaseHostMixin):+ @property+ def get_implementation(self) -> MySQLImplementation:+ return _MYSQL_IMPLEMENTATION+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.MYSQL@@ -49,14 +46,6 @@ class MySQLSource(SimpleSource[MySQLSourceConfig], SSHTunnelMixin, ValidateDatabfields=cast(list[FieldType],[- SourceFieldInputConfig(- name="connection_string",- label="Connection string (optional)",- type=SourceFieldInputConfigType.TEXT,- required=False,- placeholder="mysql://user:password@localhost:3306/database",- secret=True,- ),SourceFieldInputConfig(name="host",label="Host",@@ -143,81 +132,6 @@ class MySQLSource(SimpleSource[MySQLSourceConfig], SSHTunnelMixin, ValidateDatab"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.",}- def get_schemas(- self,- config: MySQLSourceConfig,- team_id: int,- with_counts: bool = False,- names: list[str] | None = None,- force_refresh: bool = False,- ) -> list[SourceSchema]:- schemas = []-- with self.with_ssh_tunnel(config) as (host, port):- db_schemas = get_mysql_schemas(- host=host,- port=port,- user=config.user,- password=config.password,- database=config.database,- using_ssl=config.using_ssl,- schema=config.schema,- names=names,- )- try:- detected_pks = get_mysql_primary_keys_for_schemas(- host=host,- port=port,- user=config.user,- password=config.password,- database=config.database,- schema=config.schema,- table_names=list(db_schemas.keys()),- using_ssl=config.using_ssl,- )- except Exception as e:- structlog.get_logger().warning("Failed to detect primary keys for MySQL schemas", exc_info=e)- detected_pks = {}-- indexed_columns_by_table = get_mysql_leading_index_columns_for_schemas(- host=host,- port=port,- user=config.user,- password=config.password,- database=config.database,- schema=config.schema,- table_names=list(db_schemas.keys()),- using_ssl=config.using_ssl,- )-- for table_name, columns in db_schemas.items():- incremental_field_tuples = filter_mysql_incremental_fields(columns)- indexed_cols = indexed_columns_by_table.get(table_name) if indexed_columns_by_table is not None else None- incremental_fields: list[IncrementalField] = [- {- "label": field_name,- "type": field_type,- "field": field_name,- "field_type": field_type,- "nullable": nullable,- "is_indexed": True if indexed_cols is None else field_name in indexed_cols,- }- for field_name, field_type, nullable in incremental_field_tuples- ]-- schemas.append(- SourceSchema(- name=table_name,- supports_incremental=len(incremental_fields) > 0,- supports_append=len(incremental_fields) > 0,- incremental_fields=incremental_fields,- columns=columns,- detected_primary_keys=resolve_detected_primary_keys(detected_pks.get(table_name), columns),- )- )-- return schemas-def validate_credentials(self, config: MySQLSourceConfig, team_id: int, schema_name: Optional[str] = None) -> tuple[bool, str | None]:@@ -237,28 +151,13 @@ class MySQLSource(SimpleSource[MySQLSourceConfig], SSHTunnelMixin, ValidateDatabreturn (False,e.value- or "Could not connect to MySQL via the SSH tunnel. Please check all connection details are valid.",+ or f"Could not connect to {self.get_source_config.name} via the SSH tunnel. Please check all connection details are valid.",)except Exception as e:capture_exception(e)- return False, "Could not connect to MySQL. Please check all connection details are valid."+ return (+ False,+ f"Could not connect to {self.get_source_config.name}. Please check all connection details are valid.",+ )return True, None-- def source_for_pipeline(self, config: MySQLSourceConfig, inputs: SourceInputs) -> SourceResponse:- ssh_tunnel = self.make_ssh_tunnel_func(config)-- return mysql_source(- tunnel=ssh_tunnel,- user=config.user,- password=config.password,- database=config.database,- using_ssl=config.using_ssl,- schema=config.schema,- table_names=[inputs.schema_name],- should_use_incremental_field=inputs.should_use_incremental_field,- logger=inputs.logger,- incremental_field=inputs.incremental_field,- incremental_field_type=inputs.incremental_field_type,- db_incremental_field_last_value=inputs.db_incremental_field_last_value,- )diff --git a/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py b/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.pyindex a63a6933590c..14bfcabecd66 100644--- a/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py+++ b/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py@@ -1,27 +1,76 @@import datetime-from contextlib import contextmanagerimport pytestfrom unittest.mock import MagicMockimport pymysql-from posthog.temporal.data_imports.sources.common.sql import Table+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from posthog.temporal.data_imports.sources.common.sql import Table, TableStats+from posthog.temporal.data_imports.sources.generated_configs import MySQLSourceConfigfrom posthog.temporal.data_imports.sources.mysql.mysql import (STATEMENT_TIMEOUT_SECONDS,MySQLColumn,+ MySQLImplementation,_build_query,- _find_index_for_cursor,_is_bad_plan_timeout,_safe_convert_date,_safe_convert_datetime,_sanitize_identifier,- mysql_source,)from posthog.temporal.data_imports.sources.mysql.source import MySQLSourcefrom products.data_warehouse.backend.types import IncrementalFieldType+# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_config(**overrides) -> MySQLSourceConfig:+ """Build a MySQLSourceConfig for tests that drive `build_pipeline`.++ pymysql.connect is mocked in every test that uses this, so the host/port+ never have to resolve. `ssh_tunnel` is left unset so the default `None`+ is preserved — the str-coercing `from_dict` turns explicit Nones into+ "None" strings otherwise.+ """+ defaults: dict = {+ "host": "localhost",+ "port": 3306,+ "database": "d",+ "user": "u",+ "password": "p",+ "schema": "mydb",+ "using_ssl": "false",+ }+ defaults.update(overrides)+ return MySQLSourceConfig.from_dict(defaults)+++def _make_inputs(schema_name: str = "messages", **overrides) -> SourceInputs:+ defaults: dict = {+ "schema_name": schema_name,+ "schema_id": "schema-id",+ "source_id": "source-id",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-id",+ "logger": MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++# ---------------------------------------------------------------------------+# Pure helper tests (unchanged — these are module-scope primitives)+# ---------------------------------------------------------------------------+@pytest.mark.parametrize("identifier,expected",@@ -130,111 +179,201 @@ class TestMySQLColumnDateNullability:assert field.nullable is False-@contextmanager-def _fake_tunnel():- yield "localhost", 3306+class TestMySQLColumnToArrowField:+ def test_decimal_requires_precision(self):+ col = MySQLColumn(name="x", data_type="decimal", column_type="decimal", nullable=True)+ with pytest.raises(TypeError, match="numeric_precision"):+ col.to_arrow_field()+ def test_unsigned_int_widens(self):+ col = MySQLColumn(name="x", data_type="int", column_type="int(10) unsigned", nullable=False)+ field = col.to_arrow_field()+ # Unsigned integers widen to the next signed type that can hold their range.+ assert "uint" in str(field.type)-def mysql_mocks(mocker):- """Patch pymysql.connect and metadata helpers so mysql_source can run end-to-end- without a real MySQL server. Returns (mock_connect, setup_cursor, ss_cursor).-- pymysql.connect is called twice: once for the metadata pass in mysql_source(),- and once inside get_rows() for the streaming connection we care about testing.- """- fake_table = Table(- name="messages",- parents=("mydb",),- columns=[MySQLColumn(name="id", data_type="int", column_type="int", nullable=False)],- )- mocker.patch("posthog.temporal.data_imports.sources.mysql.mysql._get_table", return_value=fake_table)- mocker.patch("posthog.temporal.data_imports.sources.mysql.mysql._get_primary_keys", return_value=["id"])- mocker.patch("posthog.temporal.data_imports.sources.mysql.mysql._get_rows_to_sync", return_value=0)- mocker.patch("posthog.temporal.data_imports.sources.mysql.mysql._get_table_chunk_size", return_value=1000)- mocker.patch("posthog.temporal.data_imports.sources.mysql.mysql._get_partition_settings", return_value=None)-- setup_cursor = MagicMock()- setup_cursor.__enter__.return_value = setup_cursor- ss_cursor = MagicMock()- ss_cursor.__enter__.return_value = ss_cursor- ss_cursor.description = [("id",)]- ss_cursor.fetchmany.return_value = []-- metadata_cursor = MagicMock()- metadata_cursor.__enter__.return_value = metadata_cursor-- # connection.cursor() is called 3 times total: once for metadata (no args),- # once for the SET SESSION setup on the streaming connection (no args),- # and once with SSCursor for the streaming query.- state = {"metadata_done": False}-- def cursor_factory(*args, **kwargs):- if args or kwargs:- return ss_cursor- if not state["metadata_done"]:- state["metadata_done"] = True- return metadata_cursor- return setup_cursor-- mock_connection = MagicMock()- mock_connection.__enter__.return_value = mock_connection- mock_connection.cursor.side_effect = cursor_factory+# ---------------------------------------------------------------------------+# Per-cursor metadata queries — test MySQLImplementation methods directly+# ---------------------------------------------------------------------------- mock_connect = mocker.patch(- "posthog.temporal.data_imports.sources.mysql.mysql.pymysql.connect",- return_value=mock_connection,- )- return mock_connect, setup_cursor, ss_cursor+def impl() -> MySQLImplementation:+ return MySQLImplementation()-def _drain_source():- source = mysql_source(- tunnel=_fake_tunnel,- user="u",- password="p",- database="d",- using_ssl=False,- schema="mydb",- table_names=["messages"],- should_use_incremental_field=False,- logger=MagicMock(),- db_incremental_field_last_value=None,- )- list(source.items()) # type: ignore[arg-type] # MySQL source is always sync+def logger() -> MagicMock:+ return MagicMock()-class TestStreamingConnectionTimeouts:- def test_read_timeout_is_passed_to_streaming_connection(self, mysql_mocks):- mock_connect, _, _ = mysql_mocks- _drain_source()- streaming_kwargs = mock_connect.call_args_list[1].kwargs- assert streaming_kwargs["read_timeout"] == STATEMENT_TIMEOUT_SECONDS- def test_set_session_timeouts_are_executed(self, mysql_mocks):- _, setup_cursor, _ = mysql_mocks- _drain_source()- executed = [c.args[0] for c in setup_cursor.execute.call_args_list if c.args]- set_session = next((sql for sql in executed if "SET SESSION" in sql), None)- assert set_session is not None- assert f"net_write_timeout = {STATEMENT_TIMEOUT_SECONDS}" in set_session- assert f"net_read_timeout = {STATEMENT_TIMEOUT_SECONDS}" in set_session+def cursor() -> MagicMock:+ c = MagicMock()+ c.fetchall.return_value = []+ c.fetchone.return_value = None+ c.description = None+ return c+++class TestGetPrimaryKeysForTable:+ def test_returns_none_when_no_rows(self, impl, cursor):+ cursor.fetchall.return_value = []+ assert impl.get_primary_keys_for_table(cursor, "db", "t") is None++ def test_returns_pk_column_names(self, impl, cursor):+ cursor.fetchall.return_value = [("id",), ("email",)]+ assert impl.get_primary_keys_for_table(cursor, "db", "t") == ["id", "email"]++ def test_uses_parameterized_query(self, impl, cursor):+ impl.get_primary_keys_for_table(cursor, "mydb", "mytable")+ # Must pass params as a dict, not inline the schema/table name.+ sql, params = cursor.execute.call_args.args+ assert "%(schema)s" in sql+ assert "%(table_name)s" in sql+ assert params == {"schema": "mydb", "table_name": "mytable"}+ assert "mydb" not in sql+ assert "mytable" not in sql+++class TestGetTableMetadata:+ def test_builds_table_with_non_numeric_columns(self, impl, cursor):+ cursor.__iter__.return_value = iter(+ [+ ("id", "int", "int", True, None, None),+ ("email", "varchar", "varchar(255)", False, None, None),+ ]+ )+ table = impl.get_table_metadata(cursor, "mydb", "users")+ assert isinstance(table, Table)+ assert table.name == "users"+ assert table.parents == ("mydb",)+ assert len(table.columns) == 2+ assert all(isinstance(c, MySQLColumn) for c in table.columns)+ assert table.columns[0].numeric_precision is None++ def test_populates_numeric_precision_and_scale_for_decimals(self, impl, cursor):+ cursor.__iter__.return_value = iter(+ [+ ("amount", "decimal", "decimal(10,2)", False, 10, 2),+ ]+ )+ table = impl.get_table_metadata(cursor, "mydb", "orders")+ assert table.columns[0].numeric_precision == 10+ assert table.columns[0].numeric_scale == 2++ def test_falls_back_to_defaults_when_decimal_missing_precision(self, impl, cursor):+ cursor.__iter__.return_value = iter(+ [+ ("amount", "decimal", "decimal", False, None, None),+ ]+ )+ table = impl.get_table_metadata(cursor, "mydb", "orders")+ assert isinstance(table.columns[0].numeric_precision, int)+ assert isinstance(table.columns[0].numeric_scale, int)+++class TestGetRowsToSync:+ def test_returns_count_from_row(self, impl, cursor, logger):+ cursor.fetchone.return_value = (123,)+ result = impl.get_rows_to_sync(cursor, "SELECT * FROM t", {}, logger)+ assert result == 123++ def test_returns_zero_on_none_row(self, impl, cursor, logger):+ cursor.fetchone.return_value = None+ assert impl.get_rows_to_sync(cursor, "SELECT * FROM t", {}, logger) == 0++ def test_returns_zero_on_exception(self, impl, cursor, logger):+ cursor.execute.side_effect = RuntimeError("boom")+ # Swallows the error rather than propagating — matches pre-refactor behavior.+ assert impl.get_rows_to_sync(cursor, "SELECT * FROM t", {}, logger) == 0++ def test_wraps_inner_query_as_subselect(self, impl, cursor, logger):+ cursor.fetchone.return_value = (5,)+ impl.get_rows_to_sync(cursor, "SELECT x FROM y WHERE a = %(a)s", {"a": 1}, logger)+ sql, params = cursor.execute.call_args.args+ assert "SELECT x FROM y WHERE a = %(a)s" in sql+ assert "COUNT(*)" in sql+ assert params == {"a": 1}+++class TestFetchTableStats:+ def test_returns_none_when_no_row(self, impl, cursor, logger):+ cursor.fetchone.return_value = None+ assert impl.fetch_table_stats(cursor, "db", "t", logger) is None++ def test_returns_none_when_either_value_is_none(self, impl, cursor, logger):+ cursor.fetchone.return_value = (None, 100)+ assert impl.fetch_table_stats(cursor, "db", "t", logger) is None+ cursor.fetchone.return_value = (100, None)+ assert impl.fetch_table_stats(cursor, "db", "t", logger) is None++ def test_returns_table_stats_dataclass(self, impl, cursor, logger):+ cursor.fetchone.return_value = (1024, 42)+ stats = impl.fetch_table_stats(cursor, "db", "t", logger)+ assert stats == TableStats(table_size_bytes=1024, row_count=42)++ def test_uses_parameterized_query(self, impl, cursor, logger):+ cursor.fetchone.return_value = (1, 1)+ impl.fetch_table_stats(cursor, "mydb", "mytable", logger)+ sql, params = cursor.execute.call_args.args+ assert params == {"schema": "mydb", "table_name": "mytable"}+ assert "mydb" not in sql+ assert "mytable" not in sql+++class TestFetchAverageRowSize:+ def test_returns_none_when_no_columns(self, impl, cursor, logger):+ cursor.fetchall.return_value = []+ result = impl.fetch_average_row_size(cursor, "db", "t", "SELECT 1", {}, logger)+ assert result is None- def test_sync_continues_when_set_session_raises(self, mysql_mocks):- _, setup_cursor, ss_cursor = mysql_mocks- setup_cursor.execute.side_effect = Exception("SET SESSION denied")+ def test_returns_none_when_sample_empty(self, impl, cursor, logger):+ cursor.fetchall.return_value = [("id",), ("email",)]+ cursor.fetchone.return_value = None+ result = impl.fetch_average_row_size(cursor, "db", "t", "SELECT 1", {}, logger)+ assert result is None- _drain_source()+ def test_returns_row_size_bytes(self, impl, cursor, logger):+ cursor.fetchall.return_value = [("id",), ("email",)]+ cursor.fetchone.return_value = (256.4,)+ result = impl.fetch_average_row_size(cursor, "db", "t", "SELECT 1", {}, logger)+ assert result == 256++ def test_clamps_to_at_least_one(self, impl, cursor, logger):+ cursor.fetchall.return_value = [("id",)]+ cursor.fetchone.return_value = (0,)+ result = impl.fetch_average_row_size(cursor, "db", "t", "SELECT 1", {}, logger)+ assert result == 1++ def test_quotes_column_names_in_length_sum(self, impl, cursor, logger):+ cursor.fetchall.return_value = [("id",), ("email",)]+ cursor.fetchone.return_value = (100,)+ impl.fetch_average_row_size(cursor, "db", "t", "SELECT * FROM x", {}, logger)+ # The second execute call is the size query — inspect it.+ second_call = cursor.execute.call_args_list[1]+ sql = second_call.args[0]+ assert "`id`" in sql+ assert "`email`" in sql+ assert "LENGTH(COALESCE(`id`" in sql++ def test_rejects_malformed_column_names(self, impl, cursor, logger):+ # If INFORMATION_SCHEMA somehow returns a weird column name, we must+ # reject it rather than splice it into SQL. The quoter raises; the+ # method catches and returns None.+ cursor.fetchall.return_value = [("bad;col",)]+ cursor.fetchone.return_value = (1,)+ result = impl.fetch_average_row_size(cursor, "db", "t", "SELECT 1", {}, logger)+ assert result is None- assert ss_cursor.execute.called+ def test_returns_none_on_exception(self, impl, cursor, logger):+ cursor.execute.side_effect = RuntimeError("boom")+ result = impl.fetch_average_row_size(cursor, "db", "t", "SELECT 1", {}, logger)+ assert result is Nonedef _show_index_rows(*triples: tuple[str, str, int]) -> list[tuple]:- """Build fake SHOW INDEX rows from (key_name, column_name, seq_in_index) triples.-- Column order must match the cursor.description returned by the mock.- """+ """Build fake SHOW INDEX rows from (key_name, column_name, seq_in_index) triples."""return [("message", # Table@@ -278,47 +417,171 @@ _SHOW_INDEX_COLUMNS = [class TestFindIndexForCursor:def _make_cursor(self, rows):- cursor = MagicMock()- cursor.description = _SHOW_INDEX_COLUMNS- cursor.fetchall.return_value = rows- return cursor+ c = MagicMock()+ c.description = _SHOW_INDEX_COLUMNS+ c.fetchall.return_value = rows+ return c- def test_returns_index_name_when_cursor_is_leading_column(self):- cursor = self._make_cursor(_show_index_rows(("idx_created_at", "created_at", 1)))- result = _find_index_for_cursor(cursor, "mydb", "message", "created_at", MagicMock())- assert result == "idx_created_at"+ def test_returns_index_name_when_cursor_is_leading_column(self, impl, logger):+ c = self._make_cursor(_show_index_rows(("idx_created_at", "created_at", 1)))+ assert impl.find_index_for_cursor(c, "mydb", "message", "created_at", logger) == "idx_created_at"- def test_returns_none_when_cursor_is_not_leading_column(self):+ def test_returns_none_when_cursor_is_not_leading_column(self, impl, logger):# Composite index (user_id, created_at) — can't use for WHERE on created_at alone- cursor = self._make_cursor(+ c = self._make_cursor(_show_index_rows(("idx_composite", "user_id", 1),("idx_composite", "created_at", 2),))- result = _find_index_for_cursor(cursor, "mydb", "message", "created_at", MagicMock())- assert result is None+ assert impl.find_index_for_cursor(c, "mydb", "message", "created_at", logger) is None- def test_returns_none_when_no_index_mentions_cursor(self):- cursor = self._make_cursor(_show_index_rows(("PRIMARY", "id", 1)))- result = _find_index_for_cursor(cursor, "mydb", "message", "created_at", MagicMock())- assert result is None+ def test_returns_none_when_no_index_mentions_cursor(self, impl, logger):+ c = self._make_cursor(_show_index_rows(("PRIMARY", "id", 1)))+ assert impl.find_index_for_cursor(c, "mydb", "message", "created_at", logger) is None- def test_returns_first_matching_index_among_several(self):- cursor = self._make_cursor(+ def test_returns_first_matching_index_among_several(self, impl, logger):+ c = self._make_cursor(_show_index_rows(("idx_a", "created_at", 1),("idx_b", "created_at", 1),))- result = _find_index_for_cursor(cursor, "mydb", "message", "created_at", MagicMock())- assert result == "idx_a"+ assert impl.find_index_for_cursor(c, "mydb", "message", "created_at", logger) == "idx_a"- def test_returns_none_on_query_failure(self):- cursor = MagicMock()- cursor.execute.side_effect = Exception("SHOW INDEX failed")- result = _find_index_for_cursor(cursor, "mydb", "message", "created_at", MagicMock())- assert result is None+ def test_returns_none_on_query_failure(self, impl, logger):+ c = MagicMock()+ c.execute.side_effect = Exception("SHOW INDEX failed")+ assert impl.find_index_for_cursor(c, "mydb", "message", "created_at", logger) is None++ def test_returns_none_on_unexpected_columns(self, impl, cursor, logger):+ cursor.description = [("foo",), ("bar",)]+ cursor.fetchall.return_value = []+ assert impl.find_index_for_cursor(cursor, "db", "t", "x", logger) is None++ def test_rejects_malformed_schema_or_table(self, impl, cursor, logger):+ # `SHOW INDEX FROM ...` has no parameterized form, so we MUST reject+ # malformed names before building the query.+ assert impl.find_index_for_cursor(cursor, "bad;schema", "t", "x", logger) is None+++class TestExplainQuery:+ def test_prefixes_with_explain(self, impl, cursor, logger):+ cursor.fetchall.return_value = []+ cursor.description = []+ impl.explain_query(cursor, "SELECT 1", {}, logger)+ sql, _ = cursor.execute.call_args.args+ assert sql.startswith("EXPLAIN ")++ def test_swallows_exceptions(self, impl, cursor, logger):+ cursor.execute.side_effect = RuntimeError("boom")+ # Must not raise — diagnostic-only.+ impl.explain_query(cursor, "SELECT 1", {}, logger)+++class TestSafetyContract:+ """Verifies that driver-specific metadata queries never splice untrusted identifiers into SQL."""++ def test_quoter_rejects_bad_identifiers(self):+ # _sanitize_identifier wraps InvalidIdentifierError → ValueError for+ # back-compat with semgrep rules keyed on the legacy message shape.+ with pytest.raises(ValueError, match="Invalid SQL identifier"):+ _sanitize_identifier("bad;id")++ @pytest.mark.parametrize("ident", ["users", "my_table", "$col", "851", "db@prod"])+ def test_quoter_accepts_common_identifier_shapes(self, ident):+ assert _sanitize_identifier(ident).startswith("`")+++# ---------------------------------------------------------------------------+# End-to-end build_pipeline — wired through MySQLImplementation+# ---------------------------------------------------------------------------+++def build_pipeline_mocks(mocker):+ """Patch pymysql.connect + per-cursor metadata methods on MySQLImplementation+ so `build_pipeline` can run end-to-end without a real MySQL server.++ pymysql.connect is called twice: once for the metadata pass inside+ `build_pipeline`, and once inside `get_rows()` for the streaming+ connection we care about testing.+ """+ fake_table = Table(+ name="messages",+ parents=("mydb",),+ columns=[MySQLColumn(name="id", data_type="int", column_type="int", nullable=False)],+ )+ mocker.patch.object(MySQLImplementation, "get_table_metadata", return_value=fake_table)+ mocker.patch.object(MySQLImplementation, "get_primary_keys_for_table", return_value=["id"])+ mocker.patch.object(MySQLImplementation, "get_rows_to_sync", return_value=0)+ mocker.patch.object(MySQLImplementation, "get_chunk_size", return_value=1000)+ mocker.patch.object(MySQLImplementation, "get_partition_settings", return_value=None)+ mocker.patch.object(MySQLImplementation, "explain_query")++ setup_cursor = MagicMock()+ setup_cursor.__enter__.return_value = setup_cursor++ ss_cursor = MagicMock()+ ss_cursor.__enter__.return_value = ss_cursor+ ss_cursor.description = [("id",)]+ ss_cursor.fetchmany.return_value = []++ metadata_cursor = MagicMock()+ metadata_cursor.__enter__.return_value = metadata_cursor++ # connection.cursor() is called 3 times total: once for metadata (no args),+ # once for the SET SESSION setup on the streaming connection (no args),+ # and once with SSCursor for the streaming query.+ state = {"metadata_done": False}++ def cursor_factory(*args, **kwargs):+ if args or kwargs:+ return ss_cursor+ if not state["metadata_done"]:+ state["metadata_done"] = True+ return metadata_cursor+ return setup_cursor++ mock_connection = MagicMock()+ mock_connection.__enter__.return_value = mock_connection+ mock_connection.cursor.side_effect = cursor_factory++ mock_connect = mocker.patch(+ "posthog.temporal.data_imports.sources.mysql.mysql.pymysql.connect",+ return_value=mock_connection,+ )+ return mock_connect, setup_cursor, ss_cursor+++def _drain_source():+ source = MySQLImplementation().build_pipeline(_make_config(), _make_inputs())+ list(source.items()) # type: ignore[arg-type] # MySQL source is always sync+++class TestStreamingConnectionTimeouts:+ def test_read_timeout_is_passed_to_streaming_connection(self, build_pipeline_mocks):+ mock_connect, _, _ = build_pipeline_mocks+ _drain_source()+ streaming_kwargs = mock_connect.call_args_list[1].kwargs+ assert streaming_kwargs["read_timeout"] == STATEMENT_TIMEOUT_SECONDS++ def test_set_session_timeouts_are_executed(self, build_pipeline_mocks):+ _, setup_cursor, _ = build_pipeline_mocks+ _drain_source()+ executed = [c.args[0] for c in setup_cursor.execute.call_args_list if c.args]+ set_session = next((sql for sql in executed if "SET SESSION" in sql), None)+ assert set_session is not None+ assert f"net_write_timeout = {STATEMENT_TIMEOUT_SECONDS}" in set_session+ assert f"net_read_timeout = {STATEMENT_TIMEOUT_SECONDS}" in set_session++ def test_sync_continues_when_set_session_raises(self, build_pipeline_mocks):+ _, setup_cursor, ss_cursor = build_pipeline_mocks+ setup_cursor.execute.side_effect = Exception("SET SESSION denied")++ _drain_source()++ assert ss_cursor.execute.calledclass TestIsBadPlanTimeout:diff --git a/posthog/temporal/tests/data_imports/conftest.py b/posthog/temporal/tests/data_imports/conftest.pyindex c31d47c1249b..c2388b585832 100644--- a/posthog/temporal/tests/data_imports/conftest.py+++ b/posthog/temporal/tests/data_imports/conftest.py@@ -9,12 +9,14 @@ from unittest import mockfrom django.conf import settingsfrom django.test import override_settings+import pymysqlimport aioboto3import pytest_asynciofrom asgiref.sync import sync_to_asyncfrom temporalio.common import RetryPolicyfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker+from testcontainers.mysql import MySqlContainerfrom posthog.schema import HogQLQueryResponse@@ -105,6 +107,52 @@ def _clean_sourcebatch_tables(_ensure_sourcebatch_tables):cur.execute(f"TRUNCATE {STATUS_TABLE}, {BATCH_TABLE} RESTART IDENTITY CASCADE")[email protected](scope="session")+def mysql_container():+ """Spin up a MySQL container once for the entire test session.++ Shared across all data-imports tests so we don't pay container+ startup more than once. Requires a reachable Docker daemon — CI has+ one (it's what brings up the `docker-compose.dev.yml` stack), and+ local flox envs have Docker too. If Docker is unreachable the+ fixture errors loudly so the breakage isn't silently hidden.+ """+ container = MySqlContainer("mysql:9.2")+ container.start()+ try:+ yield container+ finally:+ container.stop()+++def mysql_config(mysql_container):+ return {+ "host": mysql_container.get_container_host_ip(),+ "port": int(mysql_container.get_exposed_port(3306)),+ "user": mysql_container.username,+ "password": mysql_container.password,+ "database": mysql_container.dbname,+ # MySQLSourceConfig names the logical database "schema" and keeps+ # the two in lockstep — mirror that here.+ "schema": mysql_container.dbname,+ "using_ssl": False,+ }+++def mysql_connection(mysql_config):+ with pymysql.connect(+ host=mysql_config["host"],+ port=mysql_config["port"],+ database=mysql_config["database"],+ user=mysql_config["user"],+ password=mysql_config["password"],+ connect_timeout=5,+ ) as connection:+ yield connection++@pytest_asyncio.fixtureasync def minio_client():"""Manage an S3 client to interact with a MinIO bucket.diff --git a/posthog/temporal/tests/data_imports/test_end_to_end.py b/posthog/temporal/tests/data_imports/test_end_to_end.pyindex 864a3d69675f..5020460378e0 100644--- a/posthog/temporal/tests/data_imports/test_end_to_end.py+++ b/posthog/temporal/tests/data_imports/test_end_to_end.py@@ -231,6 +231,31 @@ async def postgres_connection(postgres_config, setup_postgres_test_db):await connection.close()+# `mysql_container`, `mysql_config`, and `mysql_connection` live in+# conftest.py so the container starts once per test session and is shared+# across every test file in this package.+++def _mysql_job_inputs(mysql_config: dict) -> dict[str, str | dict[str, str]]:+ """Serialize `mysql_config` into the flat string-keyed dict the+ ExternalDataSource.job_inputs pipeline expects (same shape the UI+ produces).++ Return type matches `_run`'s `job_inputs` param — dicts are invariant+ so the wider `str | dict[str, str]` value type is required even+ though every value this helper produces is a plain `str`.+ """+ return {+ "host": mysql_config["host"],+ "port": str(mysql_config["port"]),+ "database": mysql_config["database"],+ "user": mysql_config["user"],+ "password": mysql_config["password"],+ "schema": mysql_config["schema"],+ "using_ssl": "false",+ }++@pytest.fixturedef mock_paddle_client():response_data: dict[str, Any] = {"items": []}@@ -3882,3 +3907,237 @@ async def test_stripe_webhook_consumer_e2e(team, stripe_charge, mock_stripe_clie# 9. Verify webhook parquet file was cleaned up after consumptionfiles = await minio_client.list_objects_v2(Bucket=BUCKET_NAME, Prefix=webhook_prefix)assert files.get("Contents") is None or len(files.get("Contents", [])) == 0+++async def _mysql_setup(mysql_connection, statements: list[tuple[str, tuple | None]]) -> None:+ """Run a list of `(sql, args)` statements against MySQL in one shot.++ `mysql_connection` is a sync pymysql connection; wrap the batch in+ `sync_to_async` so the surrounding async test body doesn't block the+ event loop.+ """++ def _run() -> None:+ with mysql_connection.cursor() as cursor:+ for sql_stmt, args in statements:+ cursor.execute(sql_stmt, args) if args is not None else cursor.execute(sql_stmt)+ mysql_connection.commit()++ await sync_to_async(_run)()++[email protected]_db(transaction=True)+async def test_mysql_full_refresh(team, mysql_config, mysql_connection):+ """Full-refresh sync of a simple table with a mix of common MySQL types."""+ await _mysql_setup(+ mysql_connection,+ [+ ("DROP TABLE IF EXISTS users_full_refresh", None),+ (+ """+ CREATE TABLE users_full_refresh (+ id INT PRIMARY KEY,+ email VARCHAR(255) NOT NULL,+ age SMALLINT,+ created_at DATETIME+ )+ """,+ None,+ ),+ (+ "INSERT INTO users_full_refresh (id, email, age, created_at) VALUES (%s, %s, %s, %s)",+ (1, "[email protected]", 30, datetime(2025, 1, 1, 12, 0, 0)),+ ),+ ],+ )++ await _run(+ team=team,+ schema_name="users_full_refresh",+ table_name="mysql_users_full_refresh",+ source_type="MySQL",+ job_inputs=_mysql_job_inputs(mysql_config),+ mock_data_response=[],+ )++ res = await sync_to_async(execute_hogql_query)("SELECT id, email, age FROM mysql_users_full_refresh", team)+ assert res.results is not None+ row = res.results[0]+ assert row[0] == 1+ assert row[1] == "[email protected]"+ assert row[2] == 30++[email protected]_db(transaction=True)+async def test_mysql_incremental_integer_cursor(team, mysql_config, mysql_connection):+ """Incremental sync with an INT cursor field — second run should pick up only new rows."""+ await _mysql_setup(+ mysql_connection,+ [+ ("DROP TABLE IF EXISTS events_int_incremental", None),+ (+ "CREATE TABLE events_int_incremental (id INT PRIMARY KEY, payload VARCHAR(64))",+ None,+ ),+ ("INSERT INTO events_int_incremental VALUES (1, 'first')", None),+ ],+ )++ _workflow_id, inputs = await _run(+ team=team,+ schema_name="events_int_incremental",+ table_name="mysql_events_int_incremental",+ source_type="MySQL",+ job_inputs=_mysql_job_inputs(mysql_config),+ mock_data_response=[],+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},+ )++ res = await sync_to_async(execute_hogql_query)("SELECT id FROM mysql_events_int_incremental ORDER BY id", team)+ assert [row[0] for row in res.results] == [1]++ # Insert more rows and re-run — the incremental cursor should pick them up.+ await _mysql_setup(+ mysql_connection,+ [+ ("INSERT INTO events_int_incremental VALUES (2, 'second')", None),+ ("INSERT INTO events_int_incremental VALUES (3, 'third')", None),+ ],+ )++ await _execute_run(str(uuid.uuid4()), inputs, [])+ await _replay_v3_consumer(team_id=team.pk, schema_id=inputs.external_data_schema_id)++ res = await sync_to_async(execute_hogql_query)("SELECT id FROM mysql_events_int_incremental ORDER BY id", team)+ assert [row[0] for row in res.results] == [1, 2, 3]++[email protected]_db(transaction=True)+async def test_mysql_full_refresh_with_zero_date(team, mysql_config, mysql_connection):+ """Full-refresh sync of a table containing MySQL's notorious+ '0000-00-00 00:00:00' zero-date. `_safe_convert_datetime` should map+ it to None so the sync survives pymysql's default type coercion."""+ await _mysql_setup(+ mysql_connection,+ [+ ("DROP TABLE IF EXISTS events_zero_date", None),+ ("CREATE TABLE events_zero_date (id INT PRIMARY KEY, updated_at DATETIME)", None),+ # Bypass strict mode to allow the zero datetime.+ ("SET SESSION sql_mode = ''", None),+ ("INSERT INTO events_zero_date VALUES (1, '0000-00-00 00:00:00')", None),+ ],+ )++ await _run(+ team=team,+ schema_name="events_zero_date",+ table_name="mysql_events_zero_date",+ source_type="MySQL",+ job_inputs=_mysql_job_inputs(mysql_config),+ mock_data_response=[],+ )++ res = await sync_to_async(execute_hogql_query)(+ "SELECT id, updated_at FROM mysql_events_zero_date",+ team,+ )+ assert len(res.results) == 1+ assert res.results[0][0] == 1+ # The zero date should have been converted to NULL/None.+ assert res.results[0][1] is None++[email protected]_db(transaction=True)+async def test_mysql_schema_evolution(team, mysql_config, mysql_connection):+ """Add a column between syncs — the second run should pick up the new column."""+ await _mysql_setup(+ mysql_connection,+ [+ ("DROP TABLE IF EXISTS orders_evolution", None),+ ("CREATE TABLE orders_evolution (id INT PRIMARY KEY)", None),+ ("INSERT INTO orders_evolution (id) VALUES (1)", None),+ ],+ )++ _workflow_id, inputs = await _run(+ team=team,+ schema_name="orders_evolution",+ table_name="mysql_orders_evolution",+ source_type="MySQL",+ job_inputs=_mysql_job_inputs(mysql_config),+ mock_data_response=[],+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},+ )++ res = await sync_to_async(execute_hogql_query)("SELECT * FROM mysql_orders_evolution", team)+ assert any(col == "id" for col in res.columns or [])++ await _mysql_setup(+ mysql_connection,+ [+ ("ALTER TABLE orders_evolution ADD COLUMN total_cents INT", None),+ ("INSERT INTO orders_evolution (id, total_cents) VALUES (2, 999)", None),+ ],+ )++ await _execute_run(str(uuid.uuid4()), inputs, [])+ await _replay_v3_consumer(team_id=team.pk, schema_id=inputs.external_data_schema_id)++ res = await sync_to_async(execute_hogql_query)("SELECT * FROM mysql_orders_evolution", team)+ columns = res.columns or []+ assert any(col == "id" for col in columns)+ assert any(col == "total_cents" for col in columns)++[email protected]_db(transaction=True)+async def test_mysql_decimal_and_unsigned_types(team, mysql_config, mysql_connection):+ """DECIMAL(p,s) keeps precision; UNSIGNED BIGINT widens so the full+ u64 range (beyond signed int64) survives the round-trip."""+ await _mysql_setup(+ mysql_connection,+ [+ ("DROP TABLE IF EXISTS ledger_types", None),+ (+ """+ CREATE TABLE ledger_types (+ id INT PRIMARY KEY,+ amount DECIMAL(10, 2),+ big_count BIGINT UNSIGNED+ )+ """,+ None,+ ),+ (+ "INSERT INTO ledger_types (id, amount, big_count) VALUES (%s, %s, %s)",+ (1, "123.45", 9_000_000_000_000_000_000),+ ),+ ],+ )++ await _run(+ team=team,+ schema_name="ledger_types",+ table_name="mysql_ledger_types",+ source_type="MySQL",+ job_inputs=_mysql_job_inputs(mysql_config),+ mock_data_response=[],+ )++ res = await sync_to_async(execute_hogql_query)(+ "SELECT id, amount, big_count FROM mysql_ledger_types",+ team,+ )+ rows = res.results+ assert rows is not None and len(rows) == 1+ assert rows[0][0] == 1+ # Decimal round-trip — compare as string to avoid float drift.+ assert str(rows[0][1]) == "123.45"+ # Unsigned BIGINT > signed-int64 max — must come back intact.+ assert int(rows[0][2]) == 9_000_000_000_000_000_000diff --git a/posthog/temporal/tests/data_imports/test_mysql_source.py b/posthog/temporal/tests/data_imports/test_mysql_source.pyindex 1e6d9457ea9c..52251441664a 100644--- a/posthog/temporal/tests/data_imports/test_mysql_source.py+++ b/posthog/temporal/tests/data_imports/test_mysql_source.py@@ -1,28 +1,14 @@"""Tests for the MySQL source.-NOTE: These tests require a MySQL server to be running locally (or somewhere else).-Therefore these tests will only run if the required environment variables are set.--You can run a local MySQL server using Docker:--```-docker run -d --name mysql-test -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=test -p 3306:3306 mysql:9.2-```--Then you can run these tests using:--```-OBJECT_STORAGE_ENDPOINT=http://localhost:19000 \- MYSQL_HOST=localhost \- MYSQL_USER=root \- MYSQL_PASSWORD=root \- MYSQL_DATABASE=test \- pytest posthog/temporal/tests/data_imports/test_mysql_source.py-```-+These tests reuse the session-scoped `mysql_container` fixture from+`conftest.py`, which spins up a single MySQL container shared across+every test file in this package. Requires a reachable Docker daemon —+CI's existing runner already has one (it's what brings up the+`docker-compose.dev.yml` stack), and local `flox` envs have Docker too.+If Docker is unreachable the fixture errors loudly instead of silently+skipping."""-import osimport mathimport uuidimport random@@ -31,33 +17,21 @@ import operatorimport pytest-import pymysqlimport structlogfrom asgiref.sync import sync_to_asyncfrom posthog.temporal.data_imports.pipelines.pipeline.consts import DEFAULT_CHUNK_SIZE, DEFAULT_TABLE_SIZE_BYTESfrom posthog.temporal.data_imports.sources.generated_configs import MySQLSourceConfig-from posthog.temporal.data_imports.sources.mysql.mysql import (- _build_query,- _get_partition_settings,- _get_rows_to_sync,- _get_table_average_row_size,- _get_table_chunk_size,-)+from posthog.temporal.data_imports.sources.mysql.mysql import MySQLImplementation, _build_queryfrom posthog.temporal.tests.data_imports.conftest import run_external_data_job_workflowfrom products.data_warehouse.backend.types import IncrementalFieldTypefrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource-pytestmark = pytest.mark.usefixtures("minio_client")+_IMPL = MySQLImplementation()-REQUIRED_ENV_VARS = (- "MYSQL_HOST",- "MYSQL_USER",- "MYSQL_PASSWORD",- "MYSQL_DATABASE",-)+pytestmark = pytest.mark.usefixtures("minio_client")MYSQL_TABLE_NAME = "test_table"@@ -68,45 +42,6 @@ TEST_DATA = []-def mysql_env_vars_are_set():- if not all(env_var in os.environ for env_var in REQUIRED_ENV_VARS):- return False- return True---SKIP_IF_MISSING_MYSQL_CREDENTIALS = pytest.mark.skipif(- not mysql_env_vars_are_set(),- reason="MySQL required env vars are not set",-)---def mysql_config():- return {- "host": os.environ["MYSQL_HOST"],- "port": os.environ.get("MYSQL_PORT", 3306),- "user": os.environ["MYSQL_USER"],- "password": os.environ["MYSQL_PASSWORD"],- "database": os.environ["MYSQL_DATABASE"],- # TODO: I don't think this is needed- "schema": os.environ["MYSQL_DATABASE"],- "using_ssl": False,- }---def mysql_connection(mysql_config):- with pymysql.connect(- host=mysql_config["host"],- port=mysql_config["port"],- database=mysql_config["database"],- user=mysql_config["user"],- password=mysql_config["password"],- connect_timeout=5,- ) as connection:- yield connection--@pytest.fixturedef mysql_source_table(mysql_connection):"""Create a MySQL table with test data and clean it up after the test."""@@ -165,7 +100,6 @@ def external_data_schema_full_refresh(external_data_source, team):@pytest.mark.django_db(transaction=True)@pytest.mark.asyncio-@SKIP_IF_MISSING_MYSQL_CREDENTIALSasync def test_mysql_source_full_refresh(team, mysql_source_table, external_data_source, external_data_schema_full_refresh):@@ -234,26 +168,26 @@ def mysql_partition_table(mysql_connection, partition_table_name, partition_tablconn.commit()-@SKIP_IF_MISSING_MYSQL_CREDENTIALS@pytest.mark.parametrize("partition_table_rows", [0], indirect=True)-def test_get_partition_settings_with_empty_table(mysql_partition_table, mysql_connection):+def test_get_partition_settings_with_empty_table(mysql_partition_table, mysql_connection, mysql_config):logger = structlog.get_logger()with mysql_connection.cursor() as cursor:- partition_settings = _get_partition_settings(- cursor, os.environ["MYSQL_DATABASE"], mysql_partition_table, logger+ partition_settings = _IMPL.get_partition_settings(+ cursor, mysql_config["database"], mysql_partition_table, logger)assert partition_settings is None-@SKIP_IF_MISSING_MYSQL_CREDENTIALS-def test_get_partition_settings_with_one_size_partition(mysql_partition_table, mysql_connection, partition_table_rows):+def test_get_partition_settings_with_one_size_partition(+ mysql_partition_table, mysql_connection, mysql_config, partition_table_rows+):logger = structlog.get_logger()with mysql_connection.cursor() as cursor:- partition_settings = _get_partition_settings(- cursor, os.environ["MYSQL_DATABASE"], mysql_partition_table, partition_size_bytes=1, logger=logger+ partition_settings = _IMPL.get_partition_settings(+ cursor, mysql_config["database"], mysql_partition_table, logger, partition_size_bytes=1)assert partition_settings is not None@@ -279,7 +213,6 @@ def external_data_schema_incremental(external_data_source, team):@pytest.mark.django_db(transaction=True)@pytest.mark.asyncio-@SKIP_IF_MISSING_MYSQL_CREDENTIALSasync def test_mysql_source_incremental(team, mysql_source_table, external_data_source, external_data_schema_incremental, mysql_connection):@@ -317,8 +250,8 @@ async def test_mysql_source_incremental(external_data_source=external_data_source,external_data_schema=external_data_schema_incremental,table_name=table_name,- # We use a GTE, so the last id will be re-synced.- expected_rows_synced=expected_num_rows + 1,+ # Integer cursors use `>` (only Date uses `>=`), so only the newly inserted rows are synced.+ expected_rows_synced=len(NEW_TEST_DATA),expected_total_rows=expected_total_num_rows,expected_columns=["id", "name", "email", "created_at", "unsigned_int"],)@@ -628,7 +561,6 @@ def mysql_very_big_table(mysql_connection):conn.commit()-@SKIP_IF_MISSING_MYSQL_CREDENTIALSdef test_mysql_narrow_table_chunking(mysql_narrow_table, mysql_config):"""Test that narrow tables use the full chunk size (20,000 rows)."""@@ -636,21 +568,23 @@ def test_mysql_narrow_table_chunking(mysql_narrow_table, mysql_config):logger = structlog.get_logger()# Test average row size calculation- avg_row_size = _get_table_average_row_size(- cursor, mysql_config["database"], table_name, False, None, None, None, logger+ inner_query, inner_query_args = _build_query(mysql_config["database"], table_name, False, None, None, None)+ avg_row_size = _IMPL.fetch_average_row_size(+ cursor, mysql_config["database"], table_name, inner_query, inner_query_args, logger)assert avg_row_size is not Noneassert avg_row_size < 200# Test chunk size calculation- chunk_size = _get_table_chunk_size(cursor, mysql_config["database"], table_name, False, None, None, None, logger)+ chunk_size = _IMPL.get_chunk_size(+ cursor, mysql_config["database"], table_name, inner_query, inner_query_args, logger+ )# For narrow tables, should use full DEFAULT_CHUNK_SIZEassert chunk_size == DEFAULT_CHUNK_SIZE-@SKIP_IF_MISSING_MYSQL_CREDENTIALSdef test_mysql_wide_table_chunking(mysql_wide_table, mysql_config):"""Test that wide tables use reduced chunk size via dynamic chunking."""@@ -658,15 +592,18 @@ def test_mysql_wide_table_chunking(mysql_wide_table, mysql_config):logger = structlog.get_logger()# Test average row size calculation- avg_row_size = _get_table_average_row_size(- cursor, mysql_config["database"], table_name, False, None, None, None, logger+ inner_query, inner_query_args = _build_query(mysql_config["database"], table_name, False, None, None, None)+ avg_row_size = _IMPL.fetch_average_row_size(+ cursor, mysql_config["database"], table_name, inner_query, inner_query_args, logger)assert avg_row_size is not Noneassert avg_row_size > 20000# Test chunk size calculation- chunk_size = _get_table_chunk_size(cursor, mysql_config["database"], table_name, False, None, None, None, logger)+ chunk_size = _IMPL.get_chunk_size(+ cursor, mysql_config["database"], table_name, inner_query, inner_query_args, logger+ )# For wide tables, should use reduced chunk size, which is less than DEFAULT_CHUNK_SIZEexpected_chunk_size = min(int(DEFAULT_TABLE_SIZE_BYTES / avg_row_size), DEFAULT_CHUNK_SIZE)@@ -674,7 +611,6 @@ def test_mysql_wide_table_chunking(mysql_wide_table, mysql_config):assert chunk_size < DEFAULT_CHUNK_SIZE-@SKIP_IF_MISSING_MYSQL_CREDENTIALSdef test_mysql_medium_table_chunking(mysql_medium_table, mysql_config):"""Test that medium tables use moderately reduced chunk size."""@@ -682,8 +618,9 @@ def test_mysql_medium_table_chunking(mysql_medium_table, mysql_config):logger = structlog.get_logger()# Test average row size calculation- avg_row_size = _get_table_average_row_size(- cursor, mysql_config["database"], table_name, False, None, None, None, logger+ inner_query, inner_query_args = _build_query(mysql_config["database"], table_name, False, None, None, None)+ avg_row_size = _IMPL.fetch_average_row_size(+ cursor, mysql_config["database"], table_name, inner_query, inner_query_args, logger)assert avg_row_size is not None@@ -692,7 +629,9 @@ def test_mysql_medium_table_chunking(mysql_medium_table, mysql_config):) # little bit more complicated here, but make sure the avg row size is between 10000 and 20000 because the data is generated randomly# Test chunk size calculation- chunk_size = _get_table_chunk_size(cursor, mysql_config["database"], table_name, False, None, None, None, logger)+ chunk_size = _IMPL.get_chunk_size(+ cursor, mysql_config["database"], table_name, inner_query, inner_query_args, logger+ )# For medium tables, should use moderately reduced chunk sizeexpected_chunk_size = min(int(DEFAULT_TABLE_SIZE_BYTES / avg_row_size), DEFAULT_CHUNK_SIZE)@@ -701,7 +640,6 @@ def test_mysql_medium_table_chunking(mysql_medium_table, mysql_config):assert chunk_size > 5000 # make sure its not _too_ small-@SKIP_IF_MISSING_MYSQL_CREDENTIALSdef test_mysql_very_big_table_chunking(mysql_very_big_table, mysql_config):"""Test that very big tables with many rows use dynamic chunking and process multiple chunks."""@@ -709,15 +647,18 @@ def test_mysql_very_big_table_chunking(mysql_very_big_table, mysql_config):logger = structlog.get_logger()# Test average row size calculation- avg_row_size = _get_table_average_row_size(- cursor, mysql_config["database"], table_name, False, None, None, None, logger+ inner_query, inner_query_args = _build_query(mysql_config["database"], table_name, False, None, None, None)+ avg_row_size = _IMPL.fetch_average_row_size(+ cursor, mysql_config["database"], table_name, inner_query, inner_query_args, logger)assert avg_row_size is not Noneassert avg_row_size > 25000 # want them big# Test chunk size calculation- chunk_size = _get_table_chunk_size(cursor, mysql_config["database"], table_name, False, None, None, None, logger)+ chunk_size = _IMPL.get_chunk_size(+ cursor, mysql_config["database"], table_name, inner_query, inner_query_args, logger+ )# Should use significantly reduced chunk size, which is less than DEFAULT_CHUNK_SIZEexpected_chunk_size = min(int(DEFAULT_TABLE_SIZE_BYTES / avg_row_size), DEFAULT_CHUNK_SIZE)@@ -725,8 +666,7 @@ def test_mysql_very_big_table_chunking(mysql_very_big_table, mysql_config):assert chunk_size < 6000 # make sure its smaller# Test that we'd process multiple chunks- inner_query, inner_query_args = _build_query(mysql_config["database"], table_name, False, None, None, None)- rows_to_sync = _get_rows_to_sync(cursor, inner_query, inner_query_args, logger)+ rows_to_sync = _IMPL.get_rows_to_sync(cursor, inner_query, inner_query_args, logger)assert rows_to_sync == 12000 # make sure we inserted 12,000 rowsexpected_chunks = math.ceil(rows_to_sync / chunk_size)@@ -741,7 +681,6 @@ def test_mysql_very_big_table_chunking(mysql_very_big_table, mysql_config):@pytest.mark.django_db(transaction=True)@pytest.mark.asyncio-@SKIP_IF_MISSING_MYSQL_CREDENTIALSasync def test_mysql_chunking_end_to_end_wide_table(team, mysql_wide_table, mysql_config):"""End-to-end test that wide tables are processed with correct chunking."""cursor, table_name = mysql_wide_tablediff --git a/pyproject.toml b/pyproject.tomlindex 394ad4e0de33..d8467ef630fa 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -268,6 +268,7 @@ dev = ["types-tzlocal~=5.1.0.1","pywatchman~=3.0","watchdog==5.0.3",+ "testcontainers[mysql]~=4.14",# Developer CLI"hogli",]diff --git a/uv.lock b/uv.lockindex 61c2e38c531a..1572ad903f3c 100644--- a/uv.lock+++ b/uv.lock@@ -5456,6 +5456,7 @@ dev = [{ name = "stpyv8", marker = "(platform_machine != 'aarch64' and platform_machine != 'arm64') or sys_platform != 'linux'" },{ name = "syrupy" },{ name = "tach" },+ { name = "testcontainers", extra = ["mysql"] },{ name = "ty" },{ name = "types-aioboto3", extra = ["s3"] },{ name = "types-aiobotocore" },@@ -5721,6 +5722,7 @@ dev = [{ name = "stpyv8", marker = "(platform_machine != 'aarch64' and platform_machine != 'arm64') or sys_platform != 'linux'", specifier = "==13.1.201.22" },{ name = "syrupy", specifier = "~=4.9.1" },{ name = "tach", specifier = "~=0.34" },+ { name = "testcontainers", extras = ["mysql"], specifier = "~=4.14" },{ name = "ty", specifier = "==0.0.29" },{ name = "types-aioboto3", extras = ["s3"], specifier = "~=14.3.0" },{ name = "types-aiobotocore", specifier = "~=2.22.0" },@@ -6222,6 +6224,11 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/0c/94/e4181a1f6286f545507528c78016e00065ea913276888db2262507693ce5/PyMySQL-1.1.1-py3-none-any.whl", hash = "sha256:4de15da4c61dc132f4fb9ab763063e693d521a80fd0e87943b9a453dd4c19d6c", size = 44972, upload-time = "2024-05-21T11:03:41.216Z" },]+[package.optional-dependencies]+rsa = [+ { name = "cryptography" },+]+[[package]]name = "pynacl"version = "1.5.0"@@ -7628,6 +7635,28 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/67/e1/434566ffce04448192369c1a282931cf4ae593e91907558eaecd2e9f2801/termcolor-2.3.0-py3-none-any.whl", hash = "sha256:3afb05607b89aed0ffe25202399ee0867ad4d3cb4180d98aaf8eefa6a5f7d475", size = 6872, upload-time = "2023-04-23T19:45:22.671Z" },]+[[package]]+name = "testcontainers"+version = "4.14.2"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "docker" },+ { name = "python-dotenv" },+ { name = "typing-extensions" },+ { name = "urllib3" },+ { name = "wrapt" },+]+sdist = { url = "https://files.pythonhosted.org/packages/ca/ac/a597c3a0e02b26cbed6dd07df68be1e57684766fd1c381dee9b170a99690/testcontainers-4.14.2.tar.gz", hash = "sha256:1340ccf16fe3acd9389a6c9e1d9ab21d9fe99a8afdf8165f89c3e69c1967d239", size = 166841, upload-time = "2026-03-18T05:19:16.696Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/13/2d/26b8b30067d94339afee62c3edc9b803a6eb9332f521ba77d8aaab5de873/testcontainers-4.14.2-py3-none-any.whl", hash = "sha256:0d0522c3cd8f8d9627cda41f7a6b51b639fa57bdc492923c045117933c668d68", size = 125712, upload-time = "2026-03-18T05:19:15.29Z" },+]++[package.optional-dependencies]+mysql = [+ { name = "pymysql", extra = ["rsa"] },+ { name = "sqlalchemy" },+]+[[package]]name = "text-unidecode"version = "1.3"