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.

fix(warehouse-sources): project discovered columns instead of SELECT * (#95161)

posthog[bot]a5a130a8a5b3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/__init__.py
index 8d779eda1e0d..78c91e956eae 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/__init__.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/__init__.py
@@ -41,12 +41,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
validate_and_coerce_row_filters,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.projection import (
+ TableProjection,
compute_projected_columns,
filter_columns_by_enabled_columns,
filter_dwh_columns_by_enabled_columns,
format_projected_select_clause,
project_arrow_columns,
prune_enabled_columns,
+ resolve_table_projection,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.query_builder import (
ParamStyle,
@@ -80,6 +82,7 @@ __all__ = [
"SelectQueryBuilder",
"Table",
"TableBase",
+ "TableProjection",
"TableReference",
"TableSchemas",
"TableStats",
@@ -99,6 +102,7 @@ __all__ = [
"render_named_conditions",
"render_positional_conditions",
"resolve_detected_primary_keys",
+ "resolve_table_projection",
"sql_schema_metadata",
"validate_and_coerce_row_filters",
]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/projection.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/projection.py
index 2ffdfdd14048..80f369864a82 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/projection.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/projection.py
@@ -1,7 +1,8 @@
"""Column-projection helpers shared by every SQL source.
Semantics:
-- `enabled_columns is None` → `SELECT *`.
+- `enabled_columns is None` → `SELECT *`, unless the caller first resolves it against the
+ source catalog with `resolve_table_projection`.
- `enabled_columns == []` → primary keys + incremental field only.
- PKs + active incremental field are always retained: merges break without PKs,
incremental can't advance without its cursor field.
@@ -11,7 +12,7 @@ Semantics:
from __future__ import annotations
-from typing import TypeVar
+from typing import Generic, TypeVar
import structlog
@@ -171,6 +172,45 @@ def project_arrow_columns(
return Table(name=table.name, columns=projected, parents=table.parents, alias=table.alias, type=table.type)
+@frozen
+class TableProjection(Generic[_ColumnT]):
+ """The columns a read projects, and the discovered table narrowed to them."""
+
+ enabled_columns: list[str] | None
+ table: Table[_ColumnT]
+
+
+def resolve_table_projection(
+ full_table: Table[_ColumnT],
+ *,
+ enabled_columns: list[str] | None,
+ primary_keys: list[str] | None = None,
+ incremental_field: str | None = None,
+ available_columns: list[str] | None = None,
+) -> TableProjection[_ColumnT]:
+ """Name the columns a read projects, and narrow `full_table` to them.
+
+ `enabled_columns is None` means the user kept every column. Rendered as `SELECT *`, that
+ fails for a source role which holds column grants instead of table grants, because the star
+ expands to columns the role may not read. Every catalog a source discovers from already
+ hides those columns, so naming them reads what the role holds, and returns the same rows for
+ a role that can read the whole table.
+
+ Resolve again on the connection that runs the read. The projection a source resolves while it
+ probes row counts and partitions can be minutes old. Naming a column the source dropped inside
+ that window fails the read with an error we classify as permanent, which disables the schema,
+ where `SELECT *` only returned fewer columns.
+
+ Pass `available_columns` for a source that must keep some discovered columns out of the
+ read. An empty catalog keeps the `SELECT *` fallback.
+ """
+ if enabled_columns is None:
+ names = available_columns if available_columns is not None else [column.name for column in full_table.columns]
+ enabled_columns = list(names) or None
+ projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)
+ return TableProjection(enabled_columns=enabled_columns, table=project_arrow_columns(full_table, projected))
+
+
@frozen
class PrunedColumns:
kept: list[str] | None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_projection.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_projection.py
index b80bbd66b4e5..6f689512f15c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_projection.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_projection.py
@@ -22,6 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
format_projected_select_clause,
project_arrow_columns,
prune_enabled_columns,
+ resolve_table_projection,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.types import Column, Table
@@ -81,6 +82,34 @@ class TestComputeProjectedColumns:
assert compute_projected_columns(enabled_columns, primary_keys, incremental_field) == expected
+class TestResolveTableProjection:
+ @parameterized.expand(
+ [
+ ("sync_all_names_the_catalog", None, None, ["id", "email", "secret"], ["id", "email", "secret"]),
+ ("sync_all_without_a_catalog_keeps_star", None, [], None, ["id", "email", "secret"]),
+ ("explicit_selection_is_not_widened", ["email"], None, ["email"], ["id", "email"]),
+ ("empty_selection_keeps_the_primary_key", [], None, [], ["id"]),
+ ("available_columns_replace_the_catalog", None, ["id", "email"], ["id", "email"], ["id", "email"]),
+ ]
+ )
+ def test_resolve_table_projection(
+ self,
+ _name: str,
+ enabled_columns: list[str] | None,
+ available_columns: list[str] | None,
+ expected_enabled: list[str] | None,
+ expected_table: list[str],
+ ) -> None:
+ projection = resolve_table_projection(
+ _table_with("id", "email", "secret"),
+ enabled_columns=enabled_columns,
+ primary_keys=["id"],
+ available_columns=available_columns,
+ )
+ assert projection.enabled_columns == expected_enabled
+ assert [column.name for column in projection.table.columns] == expected_table
+
+
class TestFormatProjectedSelectClause:
def test_none_renders_as_star(self) -> None:
assert format_projected_select_clause(None, BacktickIdentifierQuoter()) == "*"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py
index e326021a36a2..0bd9820c67ef 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py
@@ -27,6 +27,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
DEFAULT_NUMERIC_SCALE,
BinaryColumnReporter,
build_pyarrow_decimal_type,
+ restrict_schema_to_columns,
table_from_iterator,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import (
@@ -38,11 +39,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
BracketIdentifierQuoter,
Column,
Table,
+ TableProjection,
ValidatedRowFilter,
compute_projected_columns,
format_projected_select_clause,
- project_arrow_columns,
render_named_conditions,
+ resolve_table_projection,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.batching import fetch_row_batches
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.implementation import (
@@ -905,6 +907,16 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
enabled_columns = inputs.enabled_columns
row_filters = inputs.row_filters
+ def _resolve_projection(
+ full_table: Table[MSSQLColumn], primary_keys: list[str] | None
+ ) -> TableProjection[MSSQLColumn]:
+ return resolve_table_projection(
+ full_table,
+ enabled_columns=enabled_columns,
+ primary_keys=primary_keys,
+ incremental_field=incremental_field,
+ )
+
with self.connect(config, team_id=inputs.team_id) as connection:
with connection.cursor() as cursor:
primary_keys = self.get_primary_keys_for_table(cursor, schema, table_name)
@@ -914,10 +926,8 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
if primary_keys is None and "id" in full_table:
primary_keys = ["id"]
- projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)
- table = project_arrow_columns(full_table, projected)
- arrow_schema = table.to_arrow_schema()
- logger.debug(f"Source schema: {arrow_schema}")
+ setup_projection = _resolve_projection(full_table, primary_keys)
+ logger.debug(f"Source schema: {setup_projection.table.to_arrow_schema()}")
inner_query, inner_query_args = _build_query(
schema,
@@ -926,7 +936,7 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
incremental_field,
incremental_field_type,
db_incremental_field_last_value,
- enabled_columns=enabled_columns,
+ enabled_columns=setup_projection.enabled_columns,
primary_keys=primary_keys,
row_filters=row_filters,
)
@@ -939,9 +949,25 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
else None
)
+ def _refreshed_projection(connection: pymssql.Connection) -> TableProjection[MSSQLColumn]:
+ """Re-read the catalog on the streaming connection, right before the read query.
+
+ A probe that fails keeps the setup projection, which is where this read would have
+ started anyway. See `resolve_table_projection` for why the read resolves again.
+ """
+ try:
+ with connection.cursor() as cursor:
+ fresh_table = self.get_table_metadata(cursor, schema, table_name)
+ except Exception as e:
+ logger.debug(f"Could not re-read the catalog before streaming: {e}", exc_info=e)
+ return setup_projection
+ return _resolve_projection(fresh_table, primary_keys)
+
def get_rows() -> Iterator[Any]:
binary_reporter = BinaryColumnReporter(logger)
with self.connect(config, team_id=inputs.team_id) as streaming_connection:
+ projection = _refreshed_projection(streaming_connection)
+ arrow_schema = projection.table.to_arrow_schema()
with streaming_connection.cursor() as cursor:
query, args = _build_query(
schema,
@@ -950,7 +976,7 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
incremental_field,
incremental_field_type,
db_incremental_field_last_value,
- enabled_columns=enabled_columns,
+ enabled_columns=projection.enabled_columns,
primary_keys=primary_keys,
row_filters=row_filters,
)
@@ -963,12 +989,16 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
column_names = [column[0] for column in cursor.description or []]
+ # The read can still return fewer columns than the catalog listed, so restrict
+ # the schema to what came back instead of failing the Arrow build.
+ read_schema = restrict_schema_to_columns(arrow_schema, column_names)
+
for rows in fetch_row_batches(
cursor.fetchmany, max_rows=chunk_size, byte_bounded=inputs.byte_bounded_extraction
):
yield table_from_iterator(
(dict(zip(column_names, row)) for row in rows),
- arrow_schema,
+ read_schema,
primary_keys=primary_keys,
binary_reporter=binary_reporter,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql.py
index 4777078e80bf..c755a3ee843f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql.py
@@ -314,6 +314,31 @@ def cursor() -> MagicMock:
return c
+class TestBuildPipelineProjection:
+ def test_sync_all_projects_discovered_columns(self, impl, mocker):
+ mocker.patch.object(impl, "connect", return_value=MagicMock())
+ mocker.patch.object(impl, "get_primary_keys_for_table", return_value=["id"])
+ mocker.patch.object(
+ impl,
+ "get_table_metadata",
+ return_value=Table(
+ name="users",
+ parents=("dbo",),
+ columns=[
+ MSSQLColumn(name="id", data_type="int", nullable=False),
+ MSSQLColumn(name="email", data_type="varchar", nullable=True),
+ ],
+ ),
+ )
+ rows_to_sync = mocker.patch.object(impl, "get_rows_to_sync", return_value=0)
+ mocker.patch.object(impl, "get_chunk_size", return_value=1000)
+
+ impl.build_pipeline(_make_config(), _make_inputs(schema_name="users"))
+
+ query = rows_to_sync.call_args.args[1]
+ assert query.startswith("SELECT [id], [email] FROM")
+
+
class TestGetPrimaryKeysForTable:
def test_returns_none_when_no_rows(self, impl, cursor):
cursor.fetchall.return_value = []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py
index 4ee46df59e6a..e24d9ce835c1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py
@@ -38,6 +38,7 @@ from structlog.types import FilteringBoundLogger
# Module-level error-capture seam. This module's best-effort probes (get_rows_to_sync,
# explain_query, fetch_average_row_size) deliberately do NOT report handled failures here;
# their guard tests patch `mysql.capture_exception` to enforce that.
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception # noqa: F401
from posthog.psycopg_helpers import (
is_resolvable_hostname,
@@ -67,9 +68,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
InvalidIdentifierError,
SelectQueryBuilder,
Table,
+ TableProjection,
ValidatedRowFilter,
- compute_projected_columns,
- project_arrow_columns,
+ resolve_table_projection,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.batching import fetch_row_batches
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.implementation import (
@@ -892,6 +893,47 @@ def get_connection_metadata(conn: pymysql.Connection, *, database: str) -> dict[
}
+# MySQL 8.0.23+ can mark a column `INVISIBLE`: `information_schema.columns` still lists it, but
+# `SELECT *` never returns it. `EXTRA` holds space-separated attributes, so a generated invisible
+# primary key reads `auto_increment INVISIBLE`.
+_INVISIBLE_COLUMN_EXTRA_TOKEN = "INVISIBLE"
+
+
+def _is_invisible_column(extra: str | None) -> bool:
+ """Return whether an `information_schema.columns` row describes an invisible column."""
+ return _INVISIBLE_COLUMN_EXTRA_TOKEN in (extra or "").upper().split()
+
+
+@frozen
+class MySQLTableSetup:
+ """Everything `build_pipeline` learns about a table before it can stream rows."""
+
+ primary_keys: list[str] | None
+ projection: TableProjection[MySQLColumn]
+ chunk_size: int
+ rows_to_sync: int
+ partition_settings: PartitionSettings | None
+
+
+def _syncable_column_names(table: Table[MySQLColumn], logger: FilteringBoundLogger) -> list[str]:
+ """Return the column names a sync-all read can name, or nothing to keep `SELECT *`.
+
+ Invisible columns stay out, because `SELECT *` never returned them either. Catalog column
+ names also legitimately carry characters the backtick allowlist rejects, such as a space or
+ the `:` in `Ach:CompanyId`. Naming one raises before the first row is read, so hand back an
+ empty list and let the caller keep the `SELECT *` that such a table always synced with.
+ Skipping only the offending column is not an option, because that drops it from the read.
+ """
+ names = [column.name for column in table.columns if not column.invisible]
+ for name in names:
+ try:
+ _IDENTIFIER_QUOTER.quote(name)
+ except InvalidIdentifierError:
+ logger.warning(f"Can't quote the column name {name!r}, so this sync reads the whole table with SELECT *")
+ return []
+ return names
+
+
class MySQLColumn(Column):
"""`Column` for a MySQL source — carries enough type info to build a PyArrow field.
@@ -902,6 +944,7 @@ class MySQLColumn(Column):
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`.
+ invisible: Whether MySQL hides the column from `SELECT *`.
"""
def __init__(
@@ -912,6 +955,7 @@ class MySQLColumn(Column):
nullable: bool,
numeric_precision: int | None = None,
numeric_scale: int | None = None,
+ invisible: bool = False,
) -> None:
self.name = name
self.data_type = data_type
@@ -919,6 +963,7 @@ class MySQLColumn(Column):
self.nullable = nullable
self.numeric_precision = numeric_precision
self.numeric_scale = numeric_scale
+ self.invisible = invisible
def to_arrow_field(self) -> pa.Field[pa.DataType]:
"""Return a `pyarrow.Field` that closely matches this column."""
@@ -1253,7 +1298,8 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
column_type,
is_nullable,
numeric_precision,
- numeric_scale
+ numeric_scale,
+ extra
FROM
information_schema.columns
WHERE
@@ -1265,7 +1311,15 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
numeric_data_types = {"numeric", "decimal"}
columns = []
- for name, data_type, column_type, nullable, numeric_precision_candidate, numeric_scale_candidate in cursor:
+ for (
+ name,
+ data_type,
+ column_type,
+ nullable,
+ numeric_precision_candidate,
+ numeric_scale_candidate,
+ extra,
+ ) in cursor:
if data_type in numeric_data_types:
numeric_precision = (
numeric_precision_candidate
@@ -1287,6 +1341,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
nullable=nullable,
numeric_precision=numeric_precision,
numeric_scale=numeric_scale,
+ invisible=_is_invisible_column(extra),
)
)
@@ -1543,7 +1598,21 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
enabled_columns = inputs.enabled_columns
row_filters = inputs.row_filters
- def _discover_metadata() -> tuple[list[str] | None, pa.Schema, int, PartitionSettings | None, int]:
+ def _resolve_projection(
+ full_table: Table[MySQLColumn], primary_keys: list[str] | None
+ ) -> TableProjection[MySQLColumn]:
+ # An invisible primary key is kept out of the catalog names but comes back through
+ # `compute_projected_columns`, which a merge needs.
+ available_columns = _syncable_column_names(full_table, logger) if enabled_columns is None else None
+ return resolve_table_projection(
+ full_table,
+ enabled_columns=enabled_columns,
+ primary_keys=primary_keys,
+ incremental_field=incremental_field,
+ available_columns=available_columns,
+ )
+
+ def _discover_metadata() -> MySQLTableSetup:
with self.connect(config, team_id=inputs.team_id) as connection:
with connection.cursor() as cursor:
primary_keys = self.get_primary_keys_for_table(cursor, schema, table_name)
@@ -1553,10 +1622,8 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
if primary_keys is None and "id" in full_table:
primary_keys = ["id"]
- projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)
- table = project_arrow_columns(full_table, projected)
- arrow_schema = table.to_arrow_schema()
- logger.debug(f"Source schema: {arrow_schema}")
+ projection = _resolve_projection(full_table, primary_keys)
+ logger.debug(f"Source schema: {projection.table.to_arrow_schema()}")
inner_query, inner_query_args = _build_query(
schema,
@@ -1565,7 +1632,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
incremental_field,
incremental_field_type,
db_incremental_field_last_value,
- enabled_columns=enabled_columns,
+ enabled_columns=projection.enabled_columns,
primary_keys=primary_keys,
row_filters=row_filters,
)
@@ -1577,17 +1644,40 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
if should_use_incremental_field
else None
)
- return primary_keys, arrow_schema, chunk_size, partition_settings, rows_to_sync
+ return MySQLTableSetup(
+ primary_keys=primary_keys,
+ projection=projection,
+ chunk_size=chunk_size,
+ rows_to_sync=rows_to_sync,
+ partition_settings=partition_settings,
+ )
# A PlanetScale/Vitess tablet can be momentarily unavailable even once the vtgate
# handshake succeeds, so retry the whole metadata-discovery block (reopening the
# connection) on a transient `code = Unavailable` rather than failing setup on the
# first blip — see `_retry_on_transient_tablet_unavailable`.
- primary_keys, arrow_schema, chunk_size, partition_settings, rows_to_sync = (
- _retry_on_transient_tablet_unavailable(_discover_metadata, logger)
- )
+ setup = _retry_on_transient_tablet_unavailable(_discover_metadata, logger)
+ primary_keys = setup.primary_keys
+ setup_projection = setup.projection
+ chunk_size = setup.chunk_size
+ rows_to_sync = setup.rows_to_sync
+ partition_settings = setup.partition_settings
binary_reporter = BinaryColumnReporter(logger)
+ def _refreshed_projection(connection: pymysql.Connection) -> TableProjection[MySQLColumn]:
+ """Re-read the catalog on the streaming connection, right before the read query.
+
+ A probe that fails keeps the setup projection, which is where this read would have
+ started anyway. See `resolve_table_projection` for why the read resolves again.
+ """
+ try:
+ with connection.cursor() as cursor:
+ fresh_table = self.get_table_metadata(cursor, schema, table_name)
+ except Exception as e:
+ logger.debug(f"Could not re-read the catalog before streaming: {e}", exc_info=e)
+ return setup_projection
+ return _resolve_projection(fresh_table, primary_keys)
+
def _stream_with_optional_force_index(force_index_name: str | None) -> Iterator[Any]:
"""Open a fresh connection and stream rows.
@@ -1611,6 +1701,10 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
)
except Exception as e:
logger.warning(f"Failed to set session timeouts on MySQL sync connection: {e}")
+
+ projection = _refreshed_projection(streaming_connection)
+ arrow_schema = projection.table.to_arrow_schema()
+
ss_cursor = streaming_connection.cursor(SSCursor)
try:
query, args = _build_query(
@@ -1621,7 +1715,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
incremental_field_type,
db_incremental_field_last_value,
force_index_name=force_index_name,
- enabled_columns=enabled_columns,
+ enabled_columns=projection.enabled_columns,
primary_keys=primary_keys,
row_filters=row_filters,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py
index 286657c5d173..3a1cbf22d8d4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py
@@ -367,8 +367,8 @@ 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),
+ ("id", "int", "int", True, None, None, ""),
+ ("email", "varchar", "varchar(255)", False, None, None, ""),
]
)
table = impl.get_table_metadata(cursor, "mydb", "users")
@@ -382,7 +382,7 @@ class TestGetTableMetadata:
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),
+ ("amount", "decimal", "decimal(10,2)", False, 10, 2, ""),
]
)
table = impl.get_table_metadata(cursor, "mydb", "orders")
@@ -392,13 +392,87 @@ class TestGetTableMetadata:
def test_falls_back_to_defaults_when_decimal_missing_precision(self, impl, cursor):
cursor.__iter__.return_value = iter(
[
- ("amount", "decimal", "decimal", False, None, None),
+ ("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)
+ def test_flags_invisible_columns(self, impl, cursor):
+ cursor.__iter__.return_value = iter(
+ [
+ ("my_row_id", "bigint", "bigint unsigned", False, None, None, "auto_increment INVISIBLE"),
+ ("email", "varchar", "varchar(255)", True, None, None, ""),
+ ]
+ )
+ table = impl.get_table_metadata(cursor, "mydb", "users")
+ assert [column.invisible for column in table.columns] == [True, False]
+
+
+class TestBuildPipelineProjection:
+ def _sync_all_query(self, impl, mocker, columns, primary_keys):
+ mocker.patch.object(impl, "connect", return_value=MagicMock())
+ mocker.patch.object(impl, "get_primary_keys_for_table", return_value=primary_keys)
+ mocker.patch.object(
+ impl,
+ "get_table_metadata",
+ return_value=Table(name="messages", parents=("mydb",), columns=columns),
+ )
+ rows_to_sync = mocker.patch.object(impl, "get_rows_to_sync", return_value=0)
+ mocker.patch.object(impl, "get_chunk_size", return_value=1000)
+
+ impl.build_pipeline(_make_config(), _make_inputs())
+
+ return rows_to_sync.call_args.args[1]
+
+ def test_sync_all_skips_invisible_columns(self, impl, mocker):
+ query = self._sync_all_query(
+ impl,
+ mocker,
+ [
+ MySQLColumn(name="id", data_type="int", column_type="int", nullable=False),
+ MySQLColumn(name="email", data_type="varchar", column_type="varchar(255)", nullable=True),
+ MySQLColumn(
+ name="notes", data_type="varchar", column_type="varchar(255)", nullable=True, invisible=True
+ ),
+ ],
+ ["id"],
+ )
+ assert query.startswith("SELECT `id`, `email` FROM")
+
+ def test_sync_all_falls_back_to_star_for_unquotable_column_names(self, impl, mocker):
+ # A catalog name the backtick allowlist rejects, e.g. the `:` in `Ach:CompanyId`. Naming it
+ # would raise at setup, so the table keeps reading the way it always has.
+ query = self._sync_all_query(
+ impl,
+ mocker,
+ [
+ MySQLColumn(name="id", data_type="int", column_type="int", nullable=False),
+ MySQLColumn(name="Ach:CompanyId", data_type="varchar", column_type="varchar(50)", nullable=True),
+ ],
+ ["id"],
+ )
+ assert query.startswith("SELECT * FROM")
+
+ def test_sync_all_keeps_invisible_primary_key(self, impl, mocker):
+ query = self._sync_all_query(
+ impl,
+ mocker,
+ [
+ MySQLColumn(
+ name="my_row_id",
+ data_type="bigint",
+ column_type="bigint unsigned",
+ nullable=False,
+ invisible=True,
+ ),
+ MySQLColumn(name="email", data_type="varchar", column_type="varchar(255)", nullable=True),
+ ],
+ ["my_row_id"],
+ )
+ assert query.startswith("SELECT `email`, `my_row_id` FROM")
+
class TestGetRowsToSync:
def test_returns_count_from_row(self, impl, cursor, logger):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
index 235e92c634d4..52f9c7c253b3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
@@ -65,8 +65,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mix
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (
Column,
Table,
+ TableProjection,
ValidatedRowFilter,
compute_projected_columns,
+ resolve_table_projection,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.batching import (
EXTRACT_BATCH_MAX_BYTES,
@@ -3277,22 +3279,6 @@ def _get_table(
return Table(name=table_name, parents=(schema,), columns=columns, type=table_type)
-def _project_table_columns(
- table: Table[PostgreSQLColumn],
- retained: list[str] | None,
-) -> Table[PostgreSQLColumn]:
- """Return a new `Table` whose columns are filtered to `retained` (in source order).
-
- `None` retained returns the table unchanged. Columns missing from `retained` are dropped from
- the Arrow schema so projected SELECT output zips correctly into the schema."""
- if retained is None:
- return table
-
- retained_set = set(retained)
- filtered = [column for column in table.columns if column.name in retained_set]
- return Table(name=table.name, parents=table.parents, columns=filtered, type=table.type, alias=table.alias)
-
-
# paramiko raises a bare, message-less EOFError from `start_client` when the SSH gateway accepts
# the TCP connection but closes it during the SSH handshake — a non-SSH service on the port, a
# bastion refusing PostHog's IPs, or a proxy that resets the stream. sshtunnel doesn't wrap it (it
@@ -3351,6 +3337,16 @@ def postgres_source(
effective_sslmode = _get_sslmode(require_ssl)
+ def _resolve_projection(
+ full_table: Table[PostgreSQLColumn], primary_keys: list[str] | None
+ ) -> TableProjection[PostgreSQLColumn]:
+ return resolve_table_projection(
+ full_table,
+ enabled_columns=enabled_columns,
+ primary_keys=primary_keys,
+ incremental_field=incremental_field,
+ )
+
with _tunnel_with_handshake_translation(tunnel) as (host, port):
def _open_setup_connection() -> psycopg.Connection:
@@ -3487,28 +3483,14 @@ def postgres_source(
# Project both the Arrow schema and the SELECT clause so the cursor's row shape
# matches what downstream consumers expect.
- retained_columns: list[str] | None = None
- if enabled_columns is not None:
- retained_set: set[str] = set(enabled_columns)
- for pk in primary_keys or []:
- retained_set.add(pk)
- if incremental_field:
- retained_set.add(incremental_field)
- retained_columns = [
- column.name for column in full_table.columns if column.name in retained_set
- ]
- # Mirror `compute_projected_columns` fallback to `SELECT *` so Arrow stays full-table.
- if not retained_columns:
- retained_columns = None
-
- table = _project_table_columns(full_table, retained_columns)
- logger.debug(f"Source schema: {table.to_arrow_schema()}")
+ setup_projection = _resolve_projection(full_table, primary_keys)
+ logger.debug(f"Source schema: {setup_projection.table.to_arrow_schema()}")
inner_query_with_limit = _build_query(
schema,
table_name,
should_use_incremental_field,
- table.type,
+ setup_projection.table.type,
incremental_field,
incremental_field_type,
db_incremental_field_last_value,
@@ -3516,7 +3498,7 @@ def postgres_source(
sample_percent=_size_sample_percent(
_estimated_row_count(cursor, schema, table_name, logger)
),
- enabled_columns=enabled_columns,
+ enabled_columns=setup_projection.enabled_columns,
primary_keys=primary_keys,
xmin_bounds=xmin_bounds,
)
@@ -3716,11 +3698,6 @@ def postgres_source(
def get_rows(chunk_size: int) -> Iterator[Any]:
binary_reporter = BinaryColumnReporter(logger)
- arrow_schema = table.to_arrow_schema()
- if xmin_bounds is not None:
- # The forced `_ph_xmin` projection isn't part of the discovered columns, so add it to
- # the Arrow schema (as the leading field, matching the SELECT) for a clean zip.
- arrow_schema = arrow_schema.insert(0, pa.field(XMIN_PROJECTED_COLUMN, pa.int64(), nullable=False))
with _tunnel_with_handshake_translation(tunnel) as (host, port):
cursor_factory = psycopg.ServerCursor if not using_read_replica and not is_duckdb else None
@@ -3802,6 +3779,32 @@ def postgres_source(
connection.commit()
return connection
+ def refreshed_projection() -> TableProjection[PostgreSQLColumn]:
+ """Re-read the catalog on a streaming connection, right before the read query.
+
+ A probe that fails keeps the setup projection, which is where this read would
+ have started anyway. See `resolve_table_projection` for why the read resolves
+ again. This costs one connect per sync, because every read path below builds its
+ query before it opens a connection of its own.
+ """
+ try:
+ with _connect_with_dropped_retry(get_connection, logger) as probe_connection:
+ # `get_connection` may bind ServerCursor as the factory, which needs a
+ # name, so take an unnamed client cursor directly.
+ with psycopg.Cursor(probe_connection) as probe_cursor:
+ fresh_table = _get_table(probe_cursor, schema, table_name, logger)
+ except Exception as e:
+ logger.debug(f"Could not re-read the catalog before streaming: {e}", exc_info=e)
+ return setup_projection
+ return _resolve_projection(fresh_table, primary_keys)
+
+ read_projection = refreshed_projection()
+ arrow_schema = read_projection.table.to_arrow_schema()
+ if xmin_bounds is not None:
+ # The forced `_ph_xmin` projection isn't part of the discovered columns, so add it
+ # to the Arrow schema (as the leading field, matching the SELECT) for a clean zip.
+ arrow_schema = arrow_schema.insert(0, pa.field(XMIN_PROJECTED_COLUMN, pa.int64(), nullable=False))
+
def offset_chunking(
offset: int,
chunk_size: int,
@@ -3829,11 +3832,11 @@ def postgres_source(
schema,
table_name,
should_use_incremental_field,
- table.type,
+ read_projection.table.type,
incremental_field,
incremental_field_type,
db_incremental_field_last_value,
- enabled_columns=enabled_columns,
+ enabled_columns=read_projection.enabled_columns,
primary_keys=primary_keys,
row_filters=row_filters,
xmin_bounds=xmin_bounds,
@@ -3859,7 +3862,7 @@ def postgres_source(
keyset_primary_keys,
last_key,
incremental_field=incremental_field,
- enabled_columns=enabled_columns,
+ enabled_columns=read_projection.enabled_columns,
row_filters=row_filters,
xmin_bounds=xmin_bounds,
)
@@ -4051,7 +4054,7 @@ def postgres_source(
incremental_field,
incremental_field_type,
db_incremental_field_last_value,
- enabled_columns=enabled_columns,
+ enabled_columns=read_projection.enabled_columns,
primary_keys=primary_keys,
row_filters=row_filters,
)
@@ -4082,12 +4085,12 @@ def postgres_source(
schema,
table_name,
should_use_incremental_field,
- table.type,
+ read_projection.table.type,
incremental_field,
incremental_field_type,
lo,
upper_bound_inclusive=hi,
- enabled_columns=enabled_columns,
+ enabled_columns=read_projection.enabled_columns,
primary_keys=primary_keys,
row_filters=row_filters,
)
@@ -4167,11 +4170,11 @@ def postgres_source(
schema,
table_name,
should_use_incremental_field,
- table.type,
+ read_projection.table.type,
incremental_field,
incremental_field_type,
db_incremental_field_last_value,
- enabled_columns=enabled_columns,
+ enabled_columns=read_projection.enabled_columns,
primary_keys=primary_keys,
row_filters=row_filters,
xmin_bounds=xmin_bounds,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
index 57f6dc1f6258..cddffc43008b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
@@ -51,6 +51,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
ColumnTypeCategory,
ValidatedRowFilter,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.types import Table
from products.warehouse_sources.backend.temporal.data_imports.sources.common.tests.resolver import addrinfo
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.exceptions import (
@@ -1924,6 +1925,118 @@ class TestSetupStatementTimeoutUnsupported:
assert list(cast(Iterable[Any], response.items())) == []
+class TestPostgresSourceSyncAllProjection:
+ """Sync-all names the discovered columns rather than rendering `SELECT *`.
+
+ A source role that holds column grants instead of table grants cannot run `SELECT *`, because
+ the star expands to columns it may not read. The read names what the streaming connection
+ discovers, not what setup discovered minutes earlier. No other test covers this wiring, only
+ the query builders in isolation."""
+
+ class _Cursor:
+ def __init__(self, recorder: list[str]):
+ self._recorder = recorder
+ column = mock.Mock()
+ column.name = "id"
+ self.description = [column]
+
+ def execute(self, query, *args, **kwargs):
+ self._recorder.append(query.as_string() if isinstance(query, sql.Composed) else str(query))
+ return None
+
+ def fetchmany(self, _n: int):
+ return []
+
+ def fetchone(self):
+ return None
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+ class _Connection:
+ def __init__(self, streaming_queries: list[str], setup_queries: list[str]):
+ self.autocommit = True
+ self.closed = False
+ self.broken = False
+ self.adapters = mock.Mock()
+ self._streaming_queries = streaming_queries
+ self._setup_queries = setup_queries
+
+ def cursor(self, *args, **kwargs):
+ recorder = self._streaming_queries if "name" in kwargs else self._setup_queries
+ return TestPostgresSourceSyncAllProjection._Cursor(recorder)
+
+ def commit(self):
+ return None
+
+ def close(self):
+ self.closed = True
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+ def test_sync_all_names_the_columns_rediscovered_before_streaming(self):
+ @contextmanager
+ def fake_tunnel():
+ yield ("localhost", 5432)
+
+ def table_with(*columns: str) -> Table[PostgreSQLColumn]:
+ return Table(
+ name="companies",
+ parents=("public",),
+ columns=[PostgreSQLColumn(name=name, data_type="text", nullable=False) for name in columns],
+ type="table",
+ )
+
+ streaming_queries: list[str] = []
+ setup_queries: list[str] = []
+ connection = self._Connection(streaming_queries, setup_queries)
+
+ module = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres"
+ with (
+ patch(f"{module}.psycopg.connect", return_value=connection),
+ patch(f"{module}.psycopg.Cursor", return_value=self._Cursor(setup_queries)),
+ # The source drops `nickname` between setup and the read. Naming it would fail the
+ # read as a permanent error, which disables the schema.
+ patch(
+ f"{module}._get_table",
+ side_effect=[table_with("id", "email", "nickname"), table_with("id", "email")],
+ ),
+ patch(f"{module}._is_read_replica", return_value=False),
+ patch(f"{module}._is_duckdb_connection", return_value=False),
+ patch(f"{module}._get_primary_keys", return_value=["id"]),
+ patch(f"{module}._is_partitioned_table", return_value=False),
+ patch(f"{module}._get_table_chunk_size", return_value=_TableChunking(batch_rows=100, fetch_rows=100)),
+ patch(f"{module}._get_rows_to_sync", return_value=0),
+ patch(f"{module}._role_subject_to_rls", return_value=False),
+ patch(f"{module}._get_partition_settings", return_value=None),
+ ):
+ response = postgres_source(
+ tunnel=lambda: fake_tunnel(),
+ user="u",
+ password="p",
+ database="db",
+ sslmode="prefer",
+ schema="public",
+ table_names=["companies"],
+ should_use_incremental_field=False,
+ logger=structlog.get_logger(),
+ db_incremental_field_last_value=None,
+ team_id=1,
+ )
+ list(cast(Iterable[Any], response.items()))
+
+ assert [query for query in streaming_queries if query.startswith("SELECT")] == [
+ 'SELECT "id", "email" FROM "public"."companies"'
+ ]
+
+
class TestIsConnectionDroppedError:
@pytest.mark.parametrize(
"error",
@@ -3496,9 +3609,10 @@ class TestOffsetChunkingConnectRecoveryConflict:
def connect_side_effect(*args, **kwargs):
connect_calls["n"] += 1
- # Calls 1 (setup) and 2 (initial server-cursor read) succeed; the offset-chunking
- # bootstrap connect hits the recovery conflict twice before succeeding.
- if connect_calls["n"] in (3, 4):
+ # Calls 1 (setup), 2 (catalog re-read before streaming) and 3 (initial server-cursor
+ # read) succeed; the offset-chunking bootstrap connect hits the recovery conflict
+ # twice before succeeding.
+ if connect_calls["n"] in (4, 5):
raise connect_error
return connection
@@ -3533,8 +3647,9 @@ class TestOffsetChunkingConnectRecoveryConflict:
# Before the fix the connect-time conflict escaped offset_chunking and raised here.
list(cast(Iterable[Any], response.items()))
- # 1 setup + 1 initial read + 3 offset-chunking connects (2 conflicts + 1 success).
- assert connect_mock.call_count == 5
+ # 1 setup + 1 catalog re-read + 1 initial read + 3 offset-chunking connects (2 conflicts
+ # + 1 success).
+ assert connect_mock.call_count == 6
class TestOffsetChunkingConnectTimeout:
@@ -3562,9 +3677,10 @@ class TestOffsetChunkingConnectTimeout:
def connect_side_effect(*args, **kwargs):
connect_calls["n"] += 1
- # Calls 1 (setup) and 2 (initial server-cursor read) succeed; the offset-chunking
- # bootstrap connect times out twice before succeeding.
- if connect_calls["n"] in (3, 4):
+ # Calls 1 (setup), 2 (catalog re-read before streaming) and 3 (initial server-cursor
+ # read) succeed; the offset-chunking bootstrap connect times out twice before
+ # succeeding.
+ if connect_calls["n"] in (4, 5):
raise psycopg.errors.ConnectionTimeout("connection timeout expired")
return connection
@@ -3602,8 +3718,9 @@ class TestOffsetChunkingConnectTimeout:
# Before the fix the connect-time timeout escaped offset_chunking and raised here.
list(cast(Iterable[Any], response.items()))
- # 1 setup + 1 initial read + 3 offset-chunking connects (2 timeouts + 1 success).
- assert connect_mock.call_count == 5
+ # 1 setup + 1 catalog re-read + 1 initial read + 3 offset-chunking connects (2 timeouts
+ # + 1 success).
+ assert connect_mock.call_count == 6
class TestOffsetChunkingRecoveryConflictTimeout:
@@ -9201,10 +9318,11 @@ class TestPartitionIterationConnectRetry:
def connect_side_effect(*args, **kwargs):
connect_calls["n"] += 1
- if connect_calls["n"] == 1:
- # Setup connection (metadata probes are patched out).
+ if connect_calls["n"] in (1, 2):
+ # Setup connection, then the catalog re-read before streaming (metadata probes
+ # are patched out).
return TestPartitionIterationConnectRetry._WindowConnection()
- if connect_calls["n"] == 2:
+ if connect_calls["n"] == 3:
# First per-window/per-partition connect: the setup commit() inside get_connection drops.
return TestPartitionIterationConnectRetry._WindowConnection(
commit_error=psycopg.OperationalError("the connection is lost")
@@ -9257,8 +9375,9 @@ class TestPartitionIterationConnectRetry:
# Before the fix the connect drop escaped iterate_date_windows / iterate_partitions here.
tables = list(cast(Iterable[Any], response.items()))
- # 1 setup + 2 per-window/per-partition connects (1 dropped commit + 1 success).
- assert connect_mock.call_count == 3
+ # 1 setup + 1 catalog re-read + 2 per-window/per-partition connects (1 dropped commit
+ # + 1 success).
+ assert connect_mock.call_count == 4
assert sum(table.num_rows for table in tables) == 3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
index add0b88eab98..f6a84d636a28 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
@@ -48,9 +48,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mix
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (
Column,
Table,
+ TableProjection,
ValidatedRowFilter,
compute_projected_columns,
- project_arrow_columns,
+ resolve_table_projection,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.batching import (
fetch_row_batches,
@@ -801,7 +802,7 @@ class RedshiftTableSetup:
full_table: Table[RedshiftColumn]
primary_keys: list[str] | None
- projected_table: Table[RedshiftColumn]
+ projection: TableProjection[RedshiftColumn]
chunk_size: int
rows_to_sync: int
partition_settings: PartitionSettings | None
@@ -1545,6 +1546,16 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
enabled_columns = inputs.enabled_columns
row_filters = inputs.row_filters
+ def _resolve_projection(
+ full_table: Table[RedshiftColumn], primary_keys: list[str] | None
+ ) -> TableProjection[RedshiftColumn]:
+ return resolve_table_projection(
+ full_table,
+ enabled_columns=enabled_columns,
+ primary_keys=primary_keys,
+ incremental_field=incremental_field,
+ )
+
def _discover_and_probe() -> RedshiftTableSetup:
with self.connect(config, team_id=inputs.team_id) as connection:
# Autocommit so each best-effort discovery probe runs in its own transaction. A probe
@@ -1574,8 +1585,8 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
logger.debug("Falling back to ['id'] for primary keys...")
primary_keys = ["id"]
- projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)
- table = project_arrow_columns(full_table, projected)
+ projection = _resolve_projection(full_table, primary_keys)
+ table = projection.table
logger.debug(f"Source schema: {table.to_arrow_schema()}")
inner_query_with_limit = _build_query(
@@ -1587,7 +1598,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
incremental_field_type,
db_incremental_field_last_value,
add_sampling=True,
- enabled_columns=enabled_columns,
+ enabled_columns=projection.enabled_columns,
primary_keys=primary_keys,
)
@@ -1599,7 +1610,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
incremental_field,
incremental_field_type,
db_incremental_field_last_value,
- enabled_columns=enabled_columns,
+ enabled_columns=projection.enabled_columns,
primary_keys=primary_keys,
row_filters=row_filters,
)
@@ -1643,7 +1654,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
return RedshiftTableSetup(
full_table=full_table,
primary_keys=primary_keys,
- projected_table=table,
+ projection=projection,
chunk_size=chunk_size,
rows_to_sync=rows_to_sync,
partition_settings=partition_settings,
@@ -1656,16 +1667,32 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
# from scratch. See `_retry_on_transient_connection_drop`.
setup = _retry_on_transient_connection_drop(_discover_and_probe, logger)
primary_keys = setup.primary_keys
- table = setup.projected_table
chunk_size = setup.chunk_size
rows_to_sync = setup.rows_to_sync
partition_settings = setup.partition_settings
duplicate_primary_keys = setup.duplicate_primary_keys
+ def _refreshed_projection(connection: psycopg.Connection) -> TableProjection[RedshiftColumn]:
+ """Re-read the catalog on the streaming connection, right before the read query.
+
+ A probe that fails keeps the setup projection, which is where this read would have
+ started anyway. See `resolve_table_projection` for why the read resolves again.
+ """
+ try:
+ with connection.cursor() as cursor:
+ fresh_table = self.get_table_metadata(cursor, schema, table_name, logger)
+ except Exception as e:
+ _rollback_if_aborted(connection)
+ logger.debug(f"Could not re-read the catalog before streaming: {e}", exc_info=e)
+ return setup.projection
+ return _resolve_projection(fresh_table, primary_keys)
+
def get_rows() -> Iterator[Any]:
- arrow_schema = table.to_arrow_schema()
with self.connect(config, team_id=inputs.team_id) as streaming_connection:
streaming_connection.adapters.register_loader("json", JsonAsStringLoader)
+ projection = _refreshed_projection(streaming_connection)
+ table = projection.table
+ arrow_schema = table.to_arrow_schema()
query = _build_query(
schema,
table_name,
@@ -1674,7 +1701,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
incremental_field,
incremental_field_type,
db_incremental_field_last_value,
- enabled_columns=enabled_columns,
+ enabled_columns=projection.enabled_columns,
primary_keys=primary_keys,
row_filters=row_filters,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
index baf5199d8286..1f0fc6ccb981 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
@@ -1528,6 +1528,33 @@ class TestBuildPipeline:
# streaming cursor.execute should have been invoked for the streaming query
assert streaming_cursor.execute.called
+ def test_sync_all_names_the_columns_rediscovered_before_streaming(self, build_pipeline_mocks, mocker):
+ # A role holding column grants instead of table grants cannot run `SELECT *`, because the
+ # star expands to columns it may not read. The cluster drops `nickname` between setup and
+ # the read here: naming it would fail the read as a permanent error, which disables the
+ # schema.
+ def table_with(*columns: str) -> Table:
+ return Table(
+ name="messages",
+ parents=("public",),
+ columns=[RedshiftColumn(name=name, data_type="varchar", nullable=True) for name in columns],
+ type="table",
+ )
+
+ mocker.patch.object(
+ RedshiftImplementation,
+ "get_table_metadata",
+ side_effect=[table_with("id", "email", "nickname"), table_with("id", "email")],
+ )
+ _, streaming_cursor = build_pipeline_mocks
+ impl = RedshiftImplementation()
+
+ response = impl.build_pipeline(_make_config(), _make_inputs())
+ list(response.items()) # type: ignore[arg-type]
+
+ streaming_query = streaming_cursor.stream.call_args.args[0]
+ assert streaming_query.as_string().startswith('SELECT "id", "email" FROM')
+
def test_chunk_size_override_skips_probe(self, build_pipeline_mocks, mocker):
mocked_chunk_size = mocker.patch.object(RedshiftImplementation, "get_chunk_size")
impl = RedshiftImplementation()