Skip to content

: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.

refactor(data-warehouse): migrate mssql to SQLSourceImplementation (#59699)

Daniel RC643834d555ea
diff --git a/posthog/temporal/data_imports/sources/common/sql/__init__.py b/posthog/temporal/data_imports/sources/common/sql/__init__.py
index a60d56a38497..fa02ff25b9a9 100644
--- a/posthog/temporal/data_imports/sources/common/sql/__init__.py
+++ b/posthog/temporal/data_imports/sources/common/sql/__init__.py
@@ -14,6 +14,7 @@ imports keep working. New callers should import from the submodules directly.
from posthog.temporal.data_imports.sources.common.sql.identifiers import (
AnsiIdentifierQuoter,
BacktickIdentifierQuoter,
+ BracketIdentifierQuoter,
IdentifierQuoter,
InvalidIdentifierError,
)
@@ -37,6 +38,7 @@ from posthog.temporal.data_imports.sources.common.sql.types import (
__all__ = [
"AnsiIdentifierQuoter",
"BacktickIdentifierQuoter",
+ "BracketIdentifierQuoter",
"Column",
"ColumnType",
"IdentifierQuoter",
diff --git a/posthog/temporal/data_imports/sources/common/sql/identifiers.py b/posthog/temporal/data_imports/sources/common/sql/identifiers.py
index ad6af29fba6c..49d25f8e64cd 100644
--- a/posthog/temporal/data_imports/sources/common/sql/identifiers.py
+++ b/posthog/temporal/data_imports/sources/common/sql/identifiers.py
@@ -102,3 +102,16 @@ class AnsiIdentifierQuoter(_BaseQuoter):
_open = '"'
_close = '"'
+
+
+class BracketIdentifierQuoter(_BaseQuoter):
+ """T-SQL quoting with square brackets (MSSQL, Azure SQL Server).
+
+ The allowlist already rejects identifiers containing `]`, so no
+ additional escaping is required — but the parent class still calls
+ `_validate_identifier` before quoting, which is the actual safety
+ boundary.
+ """
+
+ _open = "["
+ _close = "]"
diff --git a/posthog/temporal/data_imports/sources/common/sql/tests/test_identifiers.py b/posthog/temporal/data_imports/sources/common/sql/tests/test_identifiers.py
index 27b7fa2cb624..d34ea7d50165 100644
--- a/posthog/temporal/data_imports/sources/common/sql/tests/test_identifiers.py
+++ b/posthog/temporal/data_imports/sources/common/sql/tests/test_identifiers.py
@@ -5,6 +5,7 @@ import pytest
from posthog.temporal.data_imports.sources.common.sql.identifiers import (
AnsiIdentifierQuoter,
BacktickIdentifierQuoter,
+ BracketIdentifierQuoter,
InvalidIdentifierError,
)
@@ -77,3 +78,46 @@ class TestAnsiIdentifierQuoter:
"""Back-compat: code catching plain ValueError still works."""
with pytest.raises(ValueError):
self.quoter.quote("bad;id")
+
+
+class TestBracketIdentifierQuoter:
+ quoter = BracketIdentifierQuoter()
+
+ @pytest.mark.parametrize(
+ "identifier,expected",
+ [
+ ("dbo", "[dbo]"),
+ ("users", "[users]"),
+ ("851", "[851]"),
+ ("$col", "[$col]"),
+ ("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[b",
+ "a\nb",
+ "a b",
+ "x]; DROP TABLE foo; --",
+ "",
+ ],
+ )
+ 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("dbo", "users") == "[dbo].[users]"
+
+ def test_quote_qualified_rejects_any_unsafe_part(self) -> None:
+ with pytest.raises(InvalidIdentifierError):
+ self.quoter.quote_qualified("dbo", "bad;table")
diff --git a/posthog/temporal/data_imports/sources/mssql/mssql.py b/posthog/temporal/data_imports/sources/mssql/mssql.py
index bf11df0c3ac2..3fea30f2f316 100644
--- a/posthog/temporal/data_imports/sources/mssql/mssql.py
+++ b/posthog/temporal/data_imports/sources/mssql/mssql.py
@@ -1,13 +1,21 @@
+"""MSSQL driver for PostHog's data-warehouse import pipeline.
+
+Everything MSSQL-specific — connection lifecycle (with SSH tunnel),
+schema listing, per-cursor metadata for the streaming sync, the dlt
+pipeline build, type conversions — lives on `MSSQLImplementation`.
+The source-class `MSSQLSource` is a thin PostHog-layer wrapper that
+just holds an instance and validates credentials.
+"""
+
from __future__ import annotations
-import math
-import typing
import collections
-from collections.abc import Callable, Iterator
-from contextlib import _GeneratorContextManager
+from collections.abc import Iterator
+from contextlib import contextmanager
from typing import Any
import pyarrow as pa
+import pymssql
import structlog
from structlog.types import FilteringBoundLogger
@@ -17,21 +25,28 @@ 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, SourceResponse
from 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 BracketIdentifierQuoter, Column, 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 MSSQLSourceConfig
+
+from products.data_warehouse.backend.types import IncrementalFieldType
-from products.data_warehouse.backend.types import IncrementalFieldType, PartitionSettings
+__all__ = [
+ "MSSQLColumn",
+ "MSSQLImplementation",
+ "filter_mssql_incremental_fields",
+]
-if typing.TYPE_CHECKING:
- from pymssql import Cursor
+_IDENTIFIER_QUOTER = BracketIdentifierQuoter()
def filter_mssql_incremental_fields(
@@ -50,48 +65,6 @@ def filter_mssql_incremental_fields(
return results
-def get_schemas(
- host: str, user: str, password: str, database: str, schema: str, port: int, names: list[str] | None = None
-) -> dict[str, list[tuple[str, str, bool]]]:
- # Importing pymssql requires mssql drivers to be installed locally - see posthog/warehouse/README.md
- import pymssql
-
- connection = pymssql.connect(
- server=host,
- # pymssql requires port to be str
- port=str(port),
- database=database,
- user=user,
- password=password,
- login_timeout=5,
- )
-
- with connection.cursor(as_dict=False) 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,
- )
-
- schema_list: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)
-
- for row in cursor:
- if row:
- schema_list[row[0]].append((row[1], row[2], row[3] == "YES"))
-
- connection.close()
-
- return schema_list
-
-
def _build_query(
schema: str,
table_name: str,
@@ -101,11 +74,15 @@ def _build_query(
db_incremental_field_last_value: Any | None,
add_limit: bool = False,
) -> tuple[str, dict[str, Any]]:
- base_query = "SELECT {top} * FROM [{schema}].[{table_name}]"
+ # Every identifier interpolated below is validated by the bracket
+ # quoter — bad input (`;`, `]`, whitespace, etc.) raises before any
+ # SQL is built. Parameter values still flow through pymssql binding.
+ qualified_table = _IDENTIFIER_QUOTER.quote_qualified(schema, table_name)
+ top = "TOP 100 " if add_limit else ""
+ base_query = f"SELECT {top}* FROM {qualified_table}"
if not should_use_incremental_field:
- query = base_query.format(top="TOP 100" if add_limit else "", schema=schema, table_name=table_name)
- return query, {}
+ return base_query, {}
if incremental_field is None or incremental_field_type is None:
raise ValueError("incremental_field and incremental_field_type can't be None")
@@ -114,166 +91,18 @@ def _build_query(
db_incremental_field_last_value = incremental_type_to_initial_value(incremental_field_type)
operator = incremental_type_to_operator(incremental_field_type)
- query = base_query.format(top="TOP 100" if add_limit else "", schema=schema, table_name=table_name)
- query = f"{query} WHERE [{incremental_field}] {operator} %(incremental_value)s"
+ quoted_incremental = _IDENTIFIER_QUOTER.quote(incremental_field)
+ query = f"{base_query} WHERE {quoted_incremental} {operator} %(incremental_value)s"
# it is only safe to have this order by nested in a CTE if TOP is also specified
# ordering for incremental sync purposes where TOP is not specified is handled in get_rows()
if add_limit:
- query = f"{query} ORDER BY [{incremental_field}] ASC"
+ query = f"{query} ORDER BY {quoted_incremental} ASC"
return query, {
"incremental_value": db_incremental_field_last_value,
}
-def get_leading_index_columns_for_schemas(
- host: str,
- user: str,
- password: str,
- database: str,
- schema: str,
- port: int,
- table_names: list[str],
-) -> dict[str, set[str]] | None:
- """Return the leading column of each index per table.
-
- `sys.index_columns.key_ordinal = 1` identifies the first key column of an
- index. `is_included_column = 0` excludes columns that are only payload of
- a covering index — those don't accelerate `WHERE col >= …` predicates.
- `i.has_filter = 0` excludes filtered indexes for the same reason Postgres
- excludes partial indexes: a filtered index only accelerates queries whose
- predicate the planner can prove implies the index filter, which the
- incremental sync's `WHERE col >= last_max` generally won't satisfy. Crediting
- the leading column would suppress a warning the user genuinely needs.
- `i.is_disabled = 0` excludes disabled indexes (the planner won't use them).
- Heap tables (no clustered index) and tables with no indexes return an empty
- set so the UI warning fires for them.
-
- Returns None when discovery fails.
- """
- import pymssql
-
- if not table_names:
- return {}
-
- result: dict[str, set[str]] = {table: set() for table in table_names}
-
- try:
- with pymssql.connect(
- server=host,
- port=str(port),
- database=database,
- user=user,
- password=password,
- login_timeout=5,
- ) as connection:
- with connection.cursor(as_dict=False) as cursor:
- cursor.execute(
- """
- SELECT t.name AS table_name, c.name AS column_name
- FROM sys.indexes i
- JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
- JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
- JOIN sys.tables t ON i.object_id = t.object_id
- JOIN sys.schemas s ON t.schema_id = s.schema_id
- WHERE ic.key_ordinal = 1
- AND ic.is_included_column = 0
- AND i.has_filter = 0
- AND i.is_disabled = 0
- AND s.name = %(schema)s
- AND t.name IN %(names)s
- """,
- {"schema": schema, "names": tuple(table_names)},
- )
- for table_name, column_name in cursor.fetchall() or []:
- result.setdefault(table_name, set()).add(column_name)
- except Exception as e:
- structlog.get_logger().warning("Failed to detect leading index columns for MSSQL 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],
-) -> dict[str, list[str] | None]:
- """Detect primary keys for all tables in a single query."""
- import pymssql
-
- result: dict[str, list[str] | None] = dict.fromkeys(table_names)
-
- try:
- with pymssql.connect(
- server=host,
- port=str(port),
- database=database,
- user=user,
- password=password,
- login_timeout=5,
- ) as connection:
- with connection.cursor(as_dict=False) as cursor:
- cursor.execute(
- """
- SELECT t.name AS table_name, c.name AS column_name
- FROM sys.indexes i
- JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
- JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
- JOIN sys.tables t ON i.object_id = t.object_id
- JOIN sys.schemas s ON t.schema_id = s.schema_id
- WHERE i.is_primary_key = 1
- AND s.name = %(schema)s
- AND t.name IN %(names)s
- ORDER BY t.name, ic.key_ordinal
- """,
- {"schema": schema, "names": tuple(table_names)},
- )
- rows = cursor.fetchall()
-
- pks: dict[str, list[str]] = collections.defaultdict(list)
- for table_name, column_name in rows or []:
- 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 MSSQL schemas", exc_info=e)
-
- return result
-
-
-def _get_primary_keys(cursor: Cursor, schema: str, table_name: str) -> list[str] | None:
- query = """
- SELECT c.name AS column_name
- FROM sys.indexes i
- JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
- JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
- JOIN sys.tables t ON i.object_id = t.object_id
- JOIN sys.schemas s ON t.schema_id = s.schema_id
- WHERE i.is_primary_key = 1
- AND s.name = %(schema)s
- AND t.name = %(table_name)s
- ORDER BY ic.key_ordinal"""
-
- cursor.execute(
- query,
- {
- "schema": schema,
- "table_name": table_name,
- },
- )
- rows = cursor.fetchall()
- if not rows:
- return None
-
- return [row[0] for row in rows]
-
-
class MSSQLColumn(Column):
"""Implementation of the `Column` protocol for a MSSQL source.
@@ -343,274 +172,397 @@ class MSSQLColumn(Column):
return pa.field(self.name, arrow_type, nullable=self.nullable)
-def _get_table(cursor: Cursor, schema: str, table_name: str) -> Table[MSSQLColumn]:
- query = """
- SELECT
- COLUMN_NAME,
- DATA_TYPE,
- CASE IS_NULLABLE WHEN 'YES' THEN 1 ELSE 0 END as IS_NULLABLE,
- NUMERIC_PRECISION,
- NUMERIC_SCALE
- FROM INFORMATION_SCHEMA.COLUMNS
- WHERE TABLE_SCHEMA = %(schema)s
- AND TABLE_NAME = %(table_name)s
- ORDER BY ORDINAL_POSITION"""
-
- cursor.execute(
- query,
- {
- "schema": schema,
- "table_name": table_name,
- },
- )
-
- numeric_data_types = {"numeric", "decimal", "money"}
- columns = []
- for row in cursor:
- if row is None:
- break
-
- name, data_type, nullable, numeric_precision_candidate, numeric_scale_candidate = row
- 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(
- MSSQLColumn(
- name=name,
- data_type=data_type,
- nullable=nullable,
- numeric_precision=numeric_precision,
- numeric_scale=numeric_scale,
- )
- )
-
- if not columns:
- raise ValueError(f"Table {table_name} not found")
-
- return Table(
- name=table_name,
- parents=(schema,),
- columns=columns,
- )
-
-
-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:
- query, args = _build_query(
- schema,
- table_name,
- should_use_incremental_field,
- incremental_field,
- incremental_field_type,
- db_incremental_field_last_value,
- add_limit=True,
- )
-
- # Get column names from the table
- cursor.execute(
- f"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = %(schema)s AND TABLE_NAME = %(table)s ORDER BY ORDINAL_POSITION",
- {"schema": schema, "table": table_name},
- )
- rows = cursor.fetchall()
- if not rows:
- logger.debug(f"_get_table_average_row_size: No columns found.")
- return None
-
- columns = [row[0] for row in rows]
-
- # Build the DATALENGTH sum for each column
- datalength_sum = " + ".join(f"DATALENGTH([{col}])" for col in columns)
-
- size_query = f"""
- SELECT AVG({datalength_sum}) as avg_row_size
- FROM ({query}) as t
- """
-
- cursor.execute(size_query, args)
- row = cursor.fetchone()
-
- if row is None or row[0] is None:
- logger.debug(f"_get_table_average_row_size: No results returned.")
- return None
-
- row_size_bytes = max(row[0] or 0, 1)
- return row_size_bytes
-
-
-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:
- 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}"
- )
- 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}"
- )
- return chunk_size
-
+class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Connection, pymssql.Cursor]): # ty: ignore[invalid-type-arguments]
+ """MSSQL driver implementation paired with `MSSQLSource`.
-def _get_table_stats(cursor: Cursor, schema: str, table_name: str) -> tuple[int, float]:
- """Calculate the number of rows and size of a table.
-
- Uses sp_spaceused stored procedure which is the official way to get accurate table size and row count.
- Falls back to simpler version for SQL Server versions before 2012.
+ One class owns everything MSSQL-specific: the SSH tunnel + pymssql
+ connection lifecycle, `information_schema` / `sys.*` batch queries
+ used during schema listing, per-cursor metadata used during the
+ streaming sync (primary keys, column types, row counts,
+ partition/chunk sizing), and the dlt pipeline factory
+ (`build_pipeline`).
"""
- # Try modern version first (SQL Server 2012+)
- query = "EXEC sp_spaceused %(full_table_name)s, @updateusage = 'TRUE'"
-
- try:
- cursor.execute(query, {"full_table_name": f"[{schema}].[{table_name}]"})
- except Exception:
- # If @updateusage parameter fails, try the older version
- query = "EXEC sp_spaceused %(full_table_name)s"
- cursor.execute(query, {"full_table_name": f"[{schema}].[{table_name}]"})
-
- result = cursor.fetchone()
- if result is None:
- raise ValueError("_get_partition_settings: sp_spaceused returned no results")
-
- # sp_spaceused returns: name, rows, reserved, data, index_size, unused
- _, total_rows, _, data_size, _, _ = result
-
- # Convert string values to numbers
- total_rows = int(total_rows)
-
- # Parse size with unit (e.g. "1024.45 MB" -> 1024.45, "MB")
- size_parts = data_size.strip().split(" ")
- if len(size_parts) != 2:
- raise ValueError(
- f"_get_partition_settings: Invalid sp_spaceused result: expected 2 parts, got {len(size_parts)}"
- )
- size_value = float(size_parts[0])
- unit = size_parts[1].upper()
+ # ------------------------------------------------------------------
+ # Connection lifecycle
+ # ------------------------------------------------------------------
- # Convert to bytes based on unit
- multiplier = {"KB": 1024, "MB": 1024 * 1024, "GB": 1024 * 1024 * 1024, "TB": 1024 * 1024 * 1024 * 1024}.get(unit)
- if multiplier is None:
- raise ValueError(f"_get_partition_settings: Unexpected unit '{unit}' in sp_spaceused result")
+ @contextmanager
+ def connect(self, config: MSSQLSourceConfig) -> Iterator[pymssql.Connection]:
+ """Open a pymssql connection for the duration of the context.
- total_bytes = size_value * multiplier
- return total_rows, total_bytes
+ Opens the SSH tunnel (if configured) once, then connects with the
+ MSSQL-wide conventions: 5s login timeout.
+ """
+ with open_ssh_tunnel(config) as (host, port):
+ with pymssql.connect(
+ server=host,
+ # pymssql requires port to be str
+ port=str(port),
+ database=config.database,
+ user=config.user,
+ password=config.password,
+ login_timeout=5,
+ ) as conn:
+ yield conn
+ # ------------------------------------------------------------------
+ # Listing — batch queries run once during `get_schemas`
+ # ------------------------------------------------------------------
-def _get_rows_to_sync(
- cursor: Cursor, inner_query: str, inner_query_args: dict[str, Any], logger: FilteringBoundLogger
-) -> int:
- try:
- query = f"SELECT COUNT(*) FROM ({inner_query}) as t"
+ def get_columns(
+ self,
+ conn: pymssql.Connection,
+ config: MSSQLSourceConfig,
+ 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"
- cursor.execute(query, inner_query_args)
- row = cursor.fetchone()
+ with conn.cursor(as_dict=False) 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,
+ )
- if row is None:
- logger.debug(f"_get_rows_to_sync: No results returned. Using 0 as rows to sync")
- return 0
+ schema_list: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)
- rows_to_sync = row[0] or 0
- rows_to_sync_int = int(rows_to_sync)
+ for row in cursor:
+ if row:
+ schema_list[row[0]].append((row[1], row[2], row[3] == "YES"))
- logger.debug(f"_get_rows_to_sync: rows_to_sync_int={rows_to_sync_int}")
+ return dict(schema_list)
- 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)
+ def get_primary_keys(
+ self,
+ conn: pymssql.Connection,
+ config: MSSQLSourceConfig,
+ tables: list[str],
+ ) -> dict[str, list[str] | None]:
+ """Detect primary keys for all tables in a single query.
+
+ Permission-sensitive — some MSSQL deployments restrict access to
+ `sys.indexes` / `sys.tables`. 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
+
+ try:
+ with conn.cursor(as_dict=False) as cursor:
+ cursor.execute(
+ """
+ SELECT t.name AS table_name, c.name AS column_name
+ FROM sys.indexes i
+ JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
+ JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
+ JOIN sys.tables t ON i.object_id = t.object_id
+ JOIN sys.schemas s ON t.schema_id = s.schema_id
+ WHERE i.is_primary_key = 1
+ AND s.name = %(schema)s
+ AND t.name IN %(names)s
+ ORDER BY t.name, ic.key_ordinal
+ """,
+ {"schema": config.schema, "names": tuple(tables)},
+ )
+ rows = cursor.fetchall()
+ except Exception as e:
+ structlog.get_logger().warning("Failed to detect primary keys for MSSQL schemas", exc_info=e)
+ return result
- return 0
+ pks: dict[str, list[str]] = collections.defaultdict(list)
+ for table_name, column_name in rows or []:
+ 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_mssql_incremental_fields
-def _get_partition_settings(
- cursor: Cursor, schema: str, table_name: str, logger: FilteringBoundLogger
-) -> PartitionSettings | None:
- """Calculate the partition size and count for a table."""
+ def get_leading_index_columns(
+ self,
+ conn: pymssql.Connection,
+ config: MSSQLSourceConfig,
+ tables: list[str],
+ ) -> dict[str, set[str]] | None:
+ """Return the leading column of each index per table.
+
+ `sys.index_columns.key_ordinal = 1` identifies the first key column of an
+ index. `is_included_column = 0` excludes columns that are only payload of
+ a covering index — those don't accelerate `WHERE col >= …` predicates.
+ `i.has_filter = 0` excludes filtered indexes for the same reason Postgres
+ excludes partial indexes: a filtered index only accelerates queries whose
+ predicate the planner can prove implies the index filter, which the
+ incremental sync's `WHERE col >= last_max` generally won't satisfy. Crediting
+ the leading column would suppress a warning the user genuinely needs.
+ `i.is_disabled = 0` excludes disabled indexes (the planner won't use them).
+ Heap tables (no clustered index) and tables with no indexes return an empty
+ set so the UI warning fires for them.
+
+ Returns None when discovery fails.
+ """
+ if not tables:
+ return {}
+
+ result: dict[str, set[str]] = {table: set() for table in tables}
+
+ try:
+ with conn.cursor(as_dict=False) as cursor:
+ cursor.execute(
+ """
+ SELECT t.name AS table_name, c.name AS column_name
+ FROM sys.indexes i
+ JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
+ JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
+ JOIN sys.tables t ON i.object_id = t.object_id
+ JOIN sys.schemas s ON t.schema_id = s.schema_id
+ WHERE ic.key_ordinal = 1
+ AND ic.is_included_column = 0
+ AND i.has_filter = 0
+ AND i.is_disabled = 0
+ AND s.name = %(schema)s
+ AND t.name IN %(names)s
+ """,
+ {"schema": config.schema, "names": tuple(tables)},
+ )
+ for table_name, column_name in cursor.fetchall() or []:
+ result.setdefault(table_name, set()).add(column_name)
+ except Exception as e:
+ structlog.get_logger().warning("Failed to detect leading index columns for MSSQL schemas", exc_info=e)
+ return None
+
+ return result
+
+ # ------------------------------------------------------------------
+ # Per-cursor metadata — used during `build_pipeline`
+ # ------------------------------------------------------------------
+
+ def get_primary_keys_for_table(self, cursor: pymssql.Cursor, schema: str, table_name: str) -> list[str] | None:
+ """Return the primary-key column names for a single table, or None."""
+ query = """
+ SELECT c.name AS column_name
+ FROM sys.indexes i
+ JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
+ JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
+ JOIN sys.tables t ON i.object_id = t.object_id
+ JOIN sys.schemas s ON t.schema_id = s.schema_id
+ WHERE i.is_primary_key = 1
+ AND s.name = %(schema)s
+ AND t.name = %(table_name)s
+ ORDER BY ic.key_ordinal"""
- total_rows, total_bytes = _get_table_stats(cursor, schema, table_name)
- if total_bytes == 0 or total_rows == 0:
- return None
+ cursor.execute(
+ query,
+ {
+ "schema": schema,
+ "table_name": table_name,
+ },
+ )
+ rows = cursor.fetchall()
+ if not rows:
+ return None
+
+ return [row[0] for row in rows]
+
+ def get_table_metadata(self, cursor: pymssql.Cursor, schema: str, table_name: str) -> Table[MSSQLColumn]:
+ """Return rich column metadata for building a PyArrow schema."""
+ query = """
+ SELECT
+ COLUMN_NAME,
+ DATA_TYPE,
+ CASE IS_NULLABLE WHEN 'YES' THEN 1 ELSE 0 END as IS_NULLABLE,
+ NUMERIC_PRECISION,
+ NUMERIC_SCALE
+ FROM INFORMATION_SCHEMA.COLUMNS
+ WHERE TABLE_SCHEMA = %(schema)s
+ AND TABLE_NAME = %(table_name)s
+ ORDER BY ORDINAL_POSITION"""
- # Calculate partition size based on target bytes per partition
- bytes_per_row = total_bytes / total_rows
- partition_size = int(round(DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES / bytes_per_row))
- partition_count = math.floor(total_rows / partition_size)
- logger.debug(
- f"_get_partition_settings: {total_rows=}, {total_bytes=}, {bytes_per_row=}, "
- f"{partition_size=}, {partition_count=}"
- )
+ cursor.execute(
+ query,
+ {
+ "schema": schema,
+ "table_name": table_name,
+ },
+ )
- if partition_count == 0:
- return PartitionSettings(partition_count=1, partition_size=partition_size)
+ numeric_data_types = {"numeric", "decimal", "money"}
+ columns = []
+ for row in cursor:
+ if row is None:
+ break
+
+ name, data_type, nullable, numeric_precision_candidate, numeric_scale_candidate = row
+ 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(
+ MSSQLColumn(
+ name=name,
+ data_type=data_type,
+ nullable=nullable,
+ numeric_precision=numeric_precision,
+ numeric_scale=numeric_scale,
+ )
+ )
- return PartitionSettings(partition_count=partition_count, partition_size=partition_size)
+ if not columns:
+ raise ValueError(f"Table {table_name} not found")
+ return Table(
+ name=table_name,
+ parents=(schema,),
+ columns=columns,
+ )
-def mssql_source(
- tunnel: Callable[[], _GeneratorContextManager[tuple[str, int]]],
- user: str,
- password: str,
- database: str,
- 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:
- import pymssql
-
- table_name = table_names[0]
- if not table_name:
- raise ValueError("Table name is missing")
-
- with tunnel() as (host, port):
- with pymssql.connect(
- server=host,
- port=str(port),
- database=database,
- user=user,
- password=password,
- login_timeout=5,
- ) as connection:
+ def fetch_table_stats(
+ self,
+ cursor: pymssql.Cursor,
+ schema: str,
+ table_name: str,
+ logger: FilteringBoundLogger,
+ ) -> TableStats | None:
+ """Return table size + row count from `sp_spaceused`.
+
+ Uses sp_spaceused which is the official way to get accurate table size and row count.
+ Falls back to the older single-arg form for SQL Server versions before 2012.
+ Returns `None` on any failure so the base class falls back to safe defaults.
+ """
+ # `sp_spaceused` receives the qualified name as a *parameter* (not
+ # interpolated), but validate it through the quoter anyway so an
+ # injection attempt in `schema` / `table_name` is rejected at the
+ # boundary rather than leaning on driver parameter binding.
+ full_table_name = _IDENTIFIER_QUOTER.quote_qualified(schema, table_name)
+ try:
+ try:
+ cursor.execute(
+ "EXEC sp_spaceused %(full_table_name)s, @updateusage = 'TRUE'", {"full_table_name": full_table_name}
+ )
+ except Exception:
+ # If @updateusage parameter fails, try the older version
+ cursor.execute("EXEC sp_spaceused %(full_table_name)s", {"full_table_name": full_table_name})
+
+ result = cursor.fetchone()
+ if result is None:
+ logger.debug("fetch_table_stats: sp_spaceused returned no results")
+ return None
+
+ # sp_spaceused returns: name, rows, reserved, data, index_size, unused
+ _, total_rows, _, data_size, _, _ = result
+
+ total_rows = int(total_rows)
+
+ # Parse size with unit (e.g. "1024.45 MB" -> 1024.45, "MB")
+ size_parts = data_size.strip().split(" ")
+ if len(size_parts) != 2:
+ logger.debug(f"fetch_table_stats: Invalid sp_spaceused result: expected 2 parts, got {len(size_parts)}")
+ return None
+
+ size_value = float(size_parts[0])
+ unit = size_parts[1].upper()
+
+ multiplier = {
+ "KB": 1024,
+ "MB": 1024 * 1024,
+ "GB": 1024 * 1024 * 1024,
+ "TB": 1024 * 1024 * 1024 * 1024,
+ }.get(unit)
+ if multiplier is None:
+ logger.debug(f"fetch_table_stats: Unexpected unit '{unit}' in sp_spaceused result")
+ return None
+
+ total_bytes = int(size_value * multiplier)
+ return TableStats(table_size_bytes=total_bytes, row_count=total_rows)
+ except Exception as e:
+ logger.debug(f"fetch_table_stats: Error: {e}. Returning None", exc_info=e)
+ capture_exception(e)
+ return None
+
+ def fetch_average_row_size(
+ self,
+ cursor: pymssql.Cursor,
+ schema: str,
+ table_name: str,
+ inner_query: str,
+ inner_query_args: Any,
+ logger: FilteringBoundLogger,
+ ) -> int | None:
+ """Sample `DATALENGTH(col)` across columns on a `SELECT TOP 100` query.
+
+ Unlike other drivers, MSSQL uses an unconditional `SELECT TOP 100 *`
+ rather than the live `inner_query`. MSSQL has no `LIMIT N` keyword,
+ and wrapping the incremental query in a sub-select for size sampling
+ adds complexity without meaningfully improving the estimate (row sizes
+ don't vary much across time windows). `inner_query` and
+ `inner_query_args` are accepted for API parity with the base class but
+ are intentionally ignored.
+ """
+ try:
+ # `inner_query` / `inner_query_args` accepted for API parity only.
+ del inner_query, inner_query_args
+
+ # Get column names from the table
+ cursor.execute(
+ "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = %(schema)s AND TABLE_NAME = %(table)s ORDER BY ORDINAL_POSITION",
+ {"schema": schema, "table": table_name},
+ )
+ rows = cursor.fetchall()
+ if not rows:
+ logger.debug("fetch_average_row_size: No columns found.")
+ return None
+
+ columns = [row[0] for row in rows]
+ # Column names come from INFORMATION_SCHEMA but must still be
+ # validated before SQL interpolation — `DATALENGTH(...)` has no
+ # parameterized form.
+ datalength_sum = " + ".join(f"DATALENGTH({_IDENTIFIER_QUOTER.quote(col)})" for col in columns)
+
+ sample_query = f"SELECT TOP 100 * FROM {_IDENTIFIER_QUOTER.quote_qualified(schema, table_name)}"
+ size_query = f"SELECT AVG({datalength_sum}) as avg_row_size FROM ({sample_query}) as t"
+
+ cursor.execute(size_query)
+ 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
+
+ # ------------------------------------------------------------------
+ # Pipeline build — the dlt `SourceResponse` for a single table
+ # ------------------------------------------------------------------
+
+ def build_pipeline(self, config: MSSQLSourceConfig, 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,
@@ -621,48 +573,25 @@ def mssql_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)
- 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 = (
+ self.get_partition_settings(cursor, schema, table_name, logger)
+ if should_use_incremental_field
+ else None
)
- try:
- partition_settings = (
- _get_partition_settings(cursor, schema, table_name, logger)
- if should_use_incremental_field
- else None
- )
- except Exception as e:
- logger.debug(f"_get_partition_settings: Error: {e}. Skipping partitioning.")
- capture_exception(e)
- partition_settings = None
# Fallback on checking for an `id` field on the table
if primary_keys is None and "id" in table:
primary_keys = ["id"]
- def get_rows() -> Iterator[Any]:
- arrow_schema = table.to_arrow_schema()
-
- with tunnel() as (host, port):
- with pymssql.connect(
- server=host,
- port=str(port),
- database=database,
- user=user,
- password=password,
- login_timeout=5,
- ) as connection:
- with connection.cursor() as cursor:
+ def get_rows() -> Iterator[Any]:
+ with self.connect(config) as streaming_connection:
+ with streaming_connection.cursor() as cursor:
query, args = _build_query(
schema,
table_name,
@@ -672,9 +601,9 @@ def mssql_source(
db_incremental_field_last_value,
)
if incremental_field:
- query = f"{query} ORDER BY [{incremental_field}] ASC"
+ query = f"{query} ORDER BY {_IDENTIFIER_QUOTER.quote(incremental_field)} ASC"
- logger.debug(f"MS SQL query: {query.format(args)}")
+ logger.debug(f"MS SQL query: {query} with args: {args}")
cursor.execute(query, args)
@@ -687,13 +616,13 @@ def mssql_source(
yield table_from_iterator((dict(zip(column_names, row)) for row in rows), arrow_schema)
- 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/mssql/source.py b/posthog/temporal/data_imports/sources/mssql/source.py
index 4580ab5bde7f..c5b8b95ae15c 100644
--- a/posthog/temporal/data_imports/sources/mssql/source.py
+++ b/posthog/temporal/data_imports/sources/mssql/source.py
@@ -1,6 +1,5 @@
from typing import Optional, cast
-import structlog
from sshtunnel import BaseSSHTunnelForwarderError
from posthog.schema import (
@@ -12,22 +11,14 @@ 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 FieldType
from posthog.temporal.data_imports.sources.common.mixins import SSHTunnelMixin, ValidateDatabaseHostMixin
from 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 SQLSource
from posthog.temporal.data_imports.sources.generated_configs import MSSQLSourceConfig
-from posthog.temporal.data_imports.sources.mssql.mssql import (
- filter_mssql_incremental_fields,
- get_leading_index_columns_for_schemas as get_mssql_leading_index_columns_for_schemas,
- get_primary_keys_for_schemas as get_mssql_primary_keys_for_schemas,
- get_schemas as get_mssql_schemas,
- mssql_source,
-)
+from posthog.temporal.data_imports.sources.mssql.mssql import MSSQLImplementation
-from products.data_warehouse.backend.types import ExternalDataSourceType, IncrementalField
+from products.data_warehouse.backend.types import ExternalDataSourceType
MSSQLErrors = {
"Login failed for user": "Login failed for database",
@@ -35,9 +26,15 @@ MSSQLErrors = {
"connection timed out": "Could not connect to SQL server - check server firewall settings",
}
+_MSSQL_IMPLEMENTATION = MSSQLImplementation()
+
@SourceRegistry.register
-class MSSQLSource(SimpleSource[MSSQLSourceConfig], SSHTunnelMixin, ValidateDatabaseHostMixin):
+class MSSQLSource(SQLSource[MSSQLSourceConfig], SSHTunnelMixin, ValidateDatabaseHostMixin):
+ @property
+ def get_implementation(self) -> MSSQLImplementation:
+ return _MSSQL_IMPLEMENTATION
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.MSSQL
@@ -132,78 +129,6 @@ class MSSQLSource(SimpleSource[MSSQLSourceConfig], SSHTunnelMixin, ValidateDatab
),
)
- def get_schemas(
- self,
- config: MSSQLSourceConfig,
- 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_mssql_schemas(
- host=host,
- port=port,
- user=config.user,
- password=config.password,
- database=config.database,
- schema=config.schema,
- names=names,
- )
- try:
- detected_pks = get_mssql_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()),
- )
- except Exception as e:
- structlog.get_logger().warning("Failed to detect primary keys for MSSQL schemas", exc_info=e)
- detected_pks = {}
-
- indexed_columns_by_table = get_mssql_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()),
- )
-
- for table_name, columns in db_schemas.items():
- incremental_field_tuples = filter_mssql_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: MSSQLSourceConfig, team_id: int, schema_name: Optional[str] = None
) -> tuple[bool, str | None]:
@@ -240,20 +165,3 @@ class MSSQLSource(SimpleSource[MSSQLSourceConfig], SSHTunnelMixin, ValidateDatab
return False, "Could not connect to MS SQL. Please check all connection details are valid."
return True, None
-
- def source_for_pipeline(self, config: MSSQLSourceConfig, inputs: SourceInputs) -> SourceResponse:
- ssh_tunnel = self.make_ssh_tunnel_func(config)
-
- return mssql_source(
- tunnel=ssh_tunnel,
- user=config.user,
- password=config.password,
- database=config.database,
- 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/mssql/test_mssql.py b/posthog/temporal/data_imports/sources/mssql/test_mssql.py
deleted file mode 100644
index df9e51ad32c7..000000000000
--- a/posthog/temporal/data_imports/sources/mssql/test_mssql.py
+++ /dev/null
@@ -1,33 +0,0 @@
-import pytest
-
-from posthog.temporal.data_imports.sources.mssql.source import MSSQLSource
-
-
-class TestMSSQLSourceNonRetryableErrors:
- @pytest.fixture
- def source(self):
- return MSSQLSource()
-
- @pytest.mark.parametrize(
- "error_msg",
- [
- "Cannot build decimal array from values",
- "ValueError: Cannot build decimal array from values",
- ],
- )
- def test_unrepresentable_decimal_values_are_non_retryable(self, source, error_msg):
- non_retryable = source.get_non_retryable_errors()
- is_non_retryable = any(pattern in error_msg for pattern in non_retryable.keys())
- assert is_non_retryable, f"Unrepresentable decimal error should be non-retryable: {error_msg}"
-
- @pytest.mark.parametrize(
- "error_msg",
- [
- "Source column type changed",
- "SchemaColumnTypeChangedException: Source column type changed: 'id' has values that no longer fit",
- ],
- )
- def test_widened_integer_column_errors_are_non_retryable(self, source, error_msg):
- non_retryable = source.get_non_retryable_errors()
- is_non_retryable = any(pattern in error_msg for pattern in non_retryable.keys())
- assert is_non_retryable, f"Widened integer column error should be non-retryable: {error_msg}"
diff --git a/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py
new file mode 100644
index 000000000000..f68322bd1df1
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py
@@ -0,0 +1,395 @@
+import pytest
+from unittest.mock import MagicMock
+
+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 MSSQLSourceConfig
+from posthog.temporal.data_imports.sources.mssql.mssql import (
+ MSSQLColumn,
+ MSSQLImplementation,
+ _build_query,
+ filter_mssql_incremental_fields,
+)
+from posthog.temporal.data_imports.sources.mssql.source import MSSQLSource
+
+from products.data_warehouse.backend.types import IncrementalFieldType
+
+
+def _make_config(**overrides) -> MSSQLSourceConfig:
+ defaults: dict = {
+ "host": "localhost",
+ "port": 1433,
+ "database": "d",
+ "user": "u",
+ "password": "p",
+ "schema": "dbo",
+ }
+ defaults.update(overrides)
+ return MSSQLSourceConfig.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
+# ---------------------------------------------------------------------------
+
+
+class TestFilterMSSQLIncrementalFields:
+ @pytest.mark.parametrize(
+ "col_type,expected",
+ [
+ ("date", IncrementalFieldType.Date),
+ ("datetime", IncrementalFieldType.DateTime),
+ ("datetime2", IncrementalFieldType.DateTime),
+ ("smalldatetime", IncrementalFieldType.DateTime),
+ ("tinyint", IncrementalFieldType.Integer),
+ ("smallint", IncrementalFieldType.Integer),
+ ("int", IncrementalFieldType.Integer),
+ ("bigint", IncrementalFieldType.Integer),
+ ],
+ )
+ def test_recognized_types(self, col_type, expected):
+ result = filter_mssql_incremental_fields([("col", col_type, True)])
+ assert result == [("col", expected, True)]
+
+ def test_drops_unsupported(self):
+ result = filter_mssql_incremental_fields([("col", "varchar", False)])
+ assert result == []
+
+
+class TestMSSQLColumnToArrowField:
+ def test_decimal_requires_precision(self):
+ col = MSSQLColumn(name="x", data_type="decimal", nullable=True)
+ with pytest.raises(TypeError, match="numeric_precision"):
+ col.to_arrow_field()
+
+
+class TestBuildQuery:
+ def test_full_refresh_no_incremental(self):
+ query, args = _build_query(
+ schema="dbo",
+ table_name="users",
+ should_use_incremental_field=False,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ )
+ assert "SELECT" in query
+ assert "[dbo].[users]" in query
+ assert "TOP" not in query
+ assert args == {}
+
+ def test_incremental_adds_where(self):
+ query, args = _build_query(
+ schema="dbo",
+ table_name="users",
+ should_use_incremental_field=True,
+ incremental_field="created_at",
+ incremental_field_type=IncrementalFieldType.DateTime,
+ db_incremental_field_last_value="2025-01-01",
+ )
+ assert "WHERE [created_at]" in query
+ assert "%(incremental_value)s" in query
+ assert args == {"incremental_value": "2025-01-01"}
+
+ def test_add_limit_uses_top_100(self):
+ query, _ = _build_query(
+ schema="dbo",
+ table_name="users",
+ should_use_incremental_field=False,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ add_limit=True,
+ )
+ assert "TOP 100" in query
+
+ def test_incremental_requires_field(self):
+ with pytest.raises(ValueError, match="incremental_field"):
+ _build_query(
+ schema="dbo",
+ table_name="users",
+ should_use_incremental_field=True,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ )
+
+ @pytest.mark.parametrize(
+ "schema,table_name",
+ [
+ ("dbo]; DROP TABLE foo; --", "users"),
+ ("dbo", "users]; DROP TABLE foo; --"),
+ ("dbo with space", "users"),
+ ("dbo", "users'name"),
+ ],
+ )
+ def test_rejects_unsafe_schema_or_table(self, schema, table_name):
+ with pytest.raises(ValueError, match="Invalid SQL identifier"):
+ _build_query(
+ schema=schema,
+ table_name=table_name,
+ should_use_incremental_field=False,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ )
+
+ def test_rejects_unsafe_incremental_field(self):
+ with pytest.raises(ValueError, match="Invalid SQL identifier"):
+ _build_query(
+ schema="dbo",
+ table_name="users",
+ should_use_incremental_field=True,
+ incremental_field="created_at]; DROP TABLE foo; --",
+ incremental_field_type=IncrementalFieldType.DateTime,
+ db_incremental_field_last_value="2025-01-01",
+ )
+
+
+# ---------------------------------------------------------------------------
+# Per-cursor metadata queries
+# ---------------------------------------------------------------------------
+
+
+def impl() -> MSSQLImplementation:
+ return MSSQLImplementation()
+
+
+def logger() -> MagicMock:
+ return MagicMock()
+
+
+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, "dbo", "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, "dbo", "t") == ["id", "email"]
+
+ def test_uses_parameterized_query(self, impl, cursor):
+ impl.get_primary_keys_for_table(cursor, "dbo", "mytable")
+ sql, params = cursor.execute.call_args.args
+ assert "%(schema)s" in sql
+ assert "%(table_name)s" in sql
+ assert params == {"schema": "dbo", "table_name": "mytable"}
+
+
+class TestGetTableMetadata:
+ def test_builds_table_with_non_numeric_columns(self, impl, cursor):
+ cursor.__iter__.return_value = iter(
+ [
+ ("id", "int", True, None, None),
+ ("email", "varchar", False, None, None),
+ ]
+ )
+ table = impl.get_table_metadata(cursor, "dbo", "users")
+ assert isinstance(table, Table)
+ assert table.name == "users"
+ assert table.parents == ("dbo",)
+ assert len(table.columns) == 2
+ assert all(isinstance(c, MSSQLColumn) 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", False, 10, 2),
+ ]
+ )
+ table = impl.get_table_metadata(cursor, "dbo", "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", False, None, None),
+ ]
+ )
+ table = impl.get_table_metadata(cursor, "dbo", "orders")
+ assert isinstance(table.columns[0].numeric_precision, int)
+ assert isinstance(table.columns[0].numeric_scale, int)
+
+ def test_raises_when_no_columns(self, impl, cursor):
+ cursor.__iter__.return_value = iter([])
+ with pytest.raises(ValueError, match="not found"):
+ impl.get_table_metadata(cursor, "dbo", "missing")
+
+
+class TestFetchTableStats:
+ def test_returns_none_when_no_row(self, impl, cursor, logger):
+ cursor.fetchone.return_value = None
+ assert impl.fetch_table_stats(cursor, "dbo", "t", logger) is None
+
+ def test_returns_table_stats_dataclass(self, impl, cursor, logger):
+ # sp_spaceused result shape: name, rows, reserved, data, index_size, unused
+ cursor.fetchone.return_value = ("t", "1000", "40 KB", "32 KB", "8 KB", "0 KB")
+ stats = impl.fetch_table_stats(cursor, "dbo", "t", logger)
+ assert stats == TableStats(table_size_bytes=32 * 1024, row_count=1000)
+
+ def test_returns_none_on_unknown_unit(self, impl, cursor, logger):
+ cursor.fetchone.return_value = ("t", "1000", "40 ZB", "32 ZB", "8 ZB", "0 ZB")
+ assert impl.fetch_table_stats(cursor, "dbo", "t", logger) is None
+
+ def test_returns_none_on_exception(self, impl, cursor, logger):
+ cursor.execute.side_effect = RuntimeError("boom")
+ assert impl.fetch_table_stats(cursor, "dbo", "t", logger) is None
+
+
+class TestFetchAverageRowSize:
+ """MSSQL's `fetch_average_row_size` samples a separate `TOP 100` query
+ rather than the live inner_query, so the `inner_query` / `inner_query_args`
+ arguments are accepted for API parity but unused."""
+
+ def test_returns_none_when_no_columns(self, impl, cursor, logger):
+ cursor.fetchall.return_value = []
+ result = impl.fetch_average_row_size(cursor, "dbo", "t", "SELECT 1", {}, logger)
+ assert result is None
+
+ 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, "dbo", "t", "SELECT 1", {}, logger)
+ assert result is None
+
+ 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, "dbo", "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, "dbo", "t", "SELECT 1", {}, logger)
+ assert result == 1
+
+ def test_uses_separate_top_100_sample(self, impl, cursor, logger):
+ cursor.fetchall.return_value = [("id",)]
+ cursor.fetchone.return_value = (10,)
+ impl.fetch_average_row_size(cursor, "dbo", "t", "SELECT 1", {}, logger)
+ size_query = cursor.execute.call_args_list[1].args[0]
+ assert "TOP 100" in size_query
+ assert "DATALENGTH([id])" in size_query
+
+ def test_rejects_malformed_column_names(self, impl, cursor, logger):
+ # If INFORMATION_SCHEMA returns a weird column name, the quoter
+ # must reject it rather than splice it into SQL. Method catches
+ # and returns None.
+ cursor.fetchall.return_value = [("bad;col",)]
+ cursor.fetchone.return_value = (1,)
+ result = impl.fetch_average_row_size(cursor, "dbo", "t", "SELECT 1", {}, logger)
+ assert result is None
+
+ def test_returns_none_on_exception(self, impl, cursor, logger):
+ cursor.execute.side_effect = RuntimeError("boom")
+ result = impl.fetch_average_row_size(cursor, "dbo", "t", "SELECT 1", {}, logger)
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# End-to-end build_pipeline — wired through MSSQLImplementation
+# ---------------------------------------------------------------------------
+
+
+def build_pipeline_mocks(mocker):
+ """Patch pymssql.connect + per-cursor metadata methods on MSSQLImplementation
+ so `build_pipeline` can run end-to-end without a real MSSQL server."""
+ fake_table = Table(
+ name="messages",
+ parents=("dbo",),
+ columns=[MSSQLColumn(name="id", data_type="int", nullable=False)],
+ )
+ mocker.patch.object(MSSQLImplementation, "get_table_metadata", return_value=fake_table)
+ mocker.patch.object(MSSQLImplementation, "get_primary_keys_for_table", return_value=["id"])
+ mocker.patch.object(MSSQLImplementation, "get_rows_to_sync", return_value=0)
+ mocker.patch.object(MSSQLImplementation, "get_chunk_size", return_value=1000)
+ mocker.patch.object(MSSQLImplementation, "get_partition_settings", return_value=None)
+
+ streaming_cursor = MagicMock()
+ streaming_cursor.__enter__.return_value = streaming_cursor
+ streaming_cursor.description = [("id",)]
+ streaming_cursor.fetchmany.return_value = []
+
+ metadata_cursor = MagicMock()
+ metadata_cursor.__enter__.return_value = metadata_cursor
+
+ state = {"metadata_done": False}
+
+ def cursor_factory(*args, **kwargs):
+ if not state["metadata_done"]:
+ state["metadata_done"] = True
+ return metadata_cursor
+ return streaming_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.mssql.mssql.pymssql.connect",
+ return_value=mock_connection,
+ )
+ return mock_connect, streaming_cursor
+
+
+def _drain_source():
+ source = MSSQLImplementation().build_pipeline(_make_config(), _make_inputs())
+ list(source.items()) # type: ignore[arg-type]
+
+
+class TestBuildPipeline:
+ def test_streams_through_separate_connection(self, build_pipeline_mocks):
+ mock_connect, streaming_cursor = build_pipeline_mocks
+ _drain_source()
+ # Two connect calls: one for metadata, one for streaming.
+ assert mock_connect.call_count == 2
+ assert streaming_cursor.execute.called
+
+
+class TestMSSQLSourceNonRetryableErrors:
+ @pytest.mark.parametrize(
+ "error_msg",
+ [
+ "Cannot build decimal array from values",
+ "ValueError: Cannot build decimal array from values",
+ "Source column type changed",
+ "SchemaColumnTypeChangedException: Source column type changed: 'id' no longer fits",
+ ],
+ )
+ def test_data_shape_errors_are_non_retryable(self, error_msg):
+ non_retryable = MSSQLSource().get_non_retryable_errors()
+ assert any(pattern in error_msg for pattern in non_retryable.keys()), error_msg
diff --git a/posthog/temporal/tests/data_imports/test_mssql_source.py b/posthog/temporal/tests/data_imports/test_mssql_source.py
index a62c13e3ebe3..018f0711860a 100644
--- a/posthog/temporal/tests/data_imports/test_mssql_source.py
+++ b/posthog/temporal/tests/data_imports/test_mssql_source.py
@@ -32,10 +32,9 @@ import pytz
import pymssql
import structlog
-from posthog.temporal.data_imports.sources.mssql.mssql import _get_table_average_row_size, _get_table_stats
+from posthog.temporal.data_imports.sources.mssql.mssql import MSSQLImplementation
from posthog.temporal.tests.data_imports.conftest import run_external_data_job_workflow
-from products.data_warehouse.backend.types import IncrementalFieldType
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -457,14 +456,12 @@ class TestGetTableAverageRowSize:
We don't assert the average row size here as it's hard to determine and is likely to be flaky. We do this instead
in another test below.
"""
- average_row_size = _get_table_average_row_size(
+ average_row_size = MSSQLImplementation().fetch_average_row_size(
cursor=mssql_source_table,
schema=mssql_config["schema"],
table_name=MSSQL_TABLE_NAME,
- should_use_incremental_field=False,
- incremental_field=None,
- incremental_field_type=None,
- db_incremental_field_last_value=None,
+ inner_query="",
+ inner_query_args={},
logger=structlog.get_logger(),
)
@@ -486,14 +483,12 @@ class TestGetTableAverageRowSize:
We don't assert the average row size here as it's hard to determine and is likely to be flaky. We do this instead
in another test below.
"""
- average_row_size = _get_table_average_row_size(
+ average_row_size = MSSQLImplementation().fetch_average_row_size(
cursor=mssql_source_table,
schema=mssql_config["schema"],
table_name=MSSQL_TABLE_NAME,
- should_use_incremental_field=True,
- incremental_field="created_at",
- incremental_field_type=IncrementalFieldType.DateTime,
- db_incremental_field_last_value=None,
+ inner_query="",
+ inner_query_args={},
logger=structlog.get_logger(),
)
@@ -560,14 +555,12 @@ class TestGetTableAverageRowSize:
To do this, we test using a table with a known row size so we can assert the average row size is correct.
"""
- average_row_size = _get_table_average_row_size(
+ average_row_size = MSSQLImplementation().fetch_average_row_size(
cursor=mssql_source_table_known_row_size,
schema=mssql_config["schema"],
table_name=MSSQL_TABLE_NAME,
- should_use_incremental_field=False,
- incremental_field=None,
- incremental_field_type=None,
- db_incremental_field_last_value=None,
+ inner_query="",
+ inner_query_args={},
logger=structlog.get_logger(),
)
@@ -676,16 +669,18 @@ class TestGetTableStats:
We test using a table with exactly 1000 rows of small integers,
so we can make some assertions about the size and row count.
"""
- total_rows, total_bytes = _get_table_stats(
+ stats = MSSQLImplementation().fetch_table_stats(
cursor=mssql_small_table,
schema=mssql_config["schema"],
table_name="test_small",
+ logger=structlog.get_logger(),
)
- assert total_rows == 1000 # We inserted exactly 1000 rows
+ assert stats is not None
+ assert stats.row_count == 1000 # We inserted exactly 1000 rows
# Size should be around 32KB
- assert total_bytes > 30 * 1024
- assert total_bytes < 34 * 1024
+ assert stats.table_size_bytes > 30 * 1024
+ assert stats.table_size_bytes < 34 * 1024
async def test_get_table_stats_empty_table(
self,
@@ -696,11 +691,13 @@ class TestGetTableStats:
An empty table should return 0 rows and 0 bytes.
"""
- total_rows, total_bytes = _get_table_stats(
+ stats = MSSQLImplementation().fetch_table_stats(
cursor=mssql_empty_table,
schema=mssql_config["schema"],
table_name="test_empty",
+ logger=structlog.get_logger(),
)
- assert total_rows == 0
- assert total_bytes == 0
+ # Empty table has 0 rows; size may be 0 (fetch_table_stats returns None)
+ # or non-zero bytes (returns TableStats with row_count == 0).
+ assert stats is None or stats.row_count == 0