:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(warehouse-sources): fall back to pg_catalog for redshift columns (#101753)
jake sciottocccf8fb50cfa
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.pyindex ed294d1149ab..b65813245f62 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@@ -10,6 +10,7 @@ credentials.from __future__ import annotations+import reimport timeimport collectionsfrom collections.abc import Callable, Iterator@@ -130,6 +131,73 @@ SYSTEM_REDSHIFT_SCHEMAS = ["pg_catalog", "information_schema", "pg_internal", "p# `pa.Table.from_pydict` raises a `KeyError`. The `padb_internal` prefix is Redshift-reserved.REDSHIFT_INTERNAL_COLUMN_LIKE = "padb_internal%"+# `information_schema.columns` filters on the connecting role's privileges, and on some clusters it+# returns no rows for a materialized view the role can nonetheless `SELECT` from. Discovery then+# reports the relation as missing or unreadable, and a schema refresh disables its sync.+# `pg_catalog` applies no privilege filter, so it is the fallback for relations discovery already+# knows by name; a role that truly cannot read one still gets the real `permission denied` at sync+# time, which names the actual problem.+_CATALOG_COLUMNS_SQL = """+ SELECT+ n.nspname,+ c.relname,+ a.attname,+ format_type(a.atttypid, a.atttypmod),+ CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END+ FROM pg_catalog.pg_attribute a+ JOIN pg_catalog.pg_class c ON c.oid = a.attrelid+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace+ WHERE a.attnum > 0+ AND NOT a.attisdropped+ AND a.attname NOT LIKE %(internal_column)s+ AND {where}+ ORDER BY n.nspname ASC, c.relname ASC, a.attnum ASC+"""++_TYPE_MODIFIER_PATTERN = re.compile(r"\((\d+)(?:,\s*(\d+))?\)")+++@frozen+class _CatalogColumn:+ """One `pg_catalog` column, normalized to what `information_schema.columns` would report."""++ schema: str+ table: str+ name: str+ data_type: str+ nullable: bool+ numeric_precision: int | None+ numeric_scale: int | None++ @classmethod+ def from_row(cls, schema: str, table: str, name: str, formatted_type: str, is_nullable: str) -> _CatalogColumn:+ """Build from a `_CATALOG_COLUMNS_SQL` row.++ `format_type` renders the modifier inline (`character varying(256)`, `numeric(18,2)`), while+ `information_schema.columns` reports the bare type and carries precision and scale in their+ own columns. Only `numeric`/`decimal` keep the modifier values; a missing scale is 0, as in+ the catalog.+ """+ data_type = formatted_type+ precision: int | None = None+ scale: int | None = None+ match = _TYPE_MODIFIER_PATTERN.search(formatted_type)+ if match is not None:+ data_type = " ".join((formatted_type[: match.start()] + formatted_type[match.end() :]).split())+ if data_type in ("numeric", "decimal"):+ precision = int(match.group(1))+ scale = int(match.group(2) or 0)+ return cls(+ schema=schema,+ table=table,+ name=name,+ data_type=data_type,+ nullable=is_nullable == "YES",+ numeric_precision=precision,+ numeric_scale=scale,+ )++# A single-node Redshift cluster rejects any `FETCH FORWARD` above 1000 rows with# "Fetch size N exceeds the limit of 1000 for a single node configuration". The limit is fixed by# the node topology, so a cluster that rejects one fetch rejects every fetch: without a retry at@@ -748,7 +816,7 @@ class RedshiftColumn(Column):case "smallint" | "int2":arrow_type = pa.int16()case "numeric" | "decimal":- if not self.numeric_precision or not self.numeric_scale:+ if self.numeric_precision is None or self.numeric_scale is None:raise TypeError("expected `numeric_precision` and `numeric_scale` to be `int`, got `NoneType`")arrow_type = build_pyarrow_decimal_type(self.numeric_precision, self.numeric_scale)case "real" | "float4":@@ -873,16 +941,9 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoqualify = selected_schema is Nonewith conn.cursor() as cursor:- params: dict = {"internal_column": REDSHIFT_INTERNAL_COLUMN_LIKE}- where: list[str] = ["column_name NOT LIKE %(internal_column)s"]- if selected_schema is not None:- params["schema"] = selected_schema- where.append("table_schema = %(schema)s")- else:- placeholders, system_params = _named_placeholders("system_schema", SYSTEM_REDSHIFT_SCHEMAS)- params.update(system_params)- where.append(f"table_schema NOT IN ({placeholders})")- where.append("table_schema NOT LIKE 'pg_temp_%%'")+ where, params = self._scope_predicates(selected_schema, "table_schema")+ params["internal_column"] = REDSHIFT_INTERNAL_COLUMN_LIKE+ where.append("column_name NOT LIKE %(internal_column)s")if names:name_clause, name_params = self._column_name_predicate(names, selected_schema)params.update(name_params)@@ -899,15 +960,41 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco)result = cursor.fetchall()+ undiscovered = self._undiscovered_relations(conn, cursor, selected_schema, names, result)+ catalog_columns = (+ self._columns_from_catalog(conn, cursor, undiscovered, selected_schema) if undiscovered else []+ )+schema_list: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)for table_schema, table_name, column_name, data_type, is_nullable in result:display = _display_name(table_schema, table_name, qualify=qualify)schema_list[display].append((column_name, data_type, is_nullable == "YES"))+ for column in catalog_columns:+ display = _display_name(column.schema, column.table, qualify=qualify)+ schema_list[display].append((column.name, column.data_type, column.nullable))return dict(schema_list)@staticmethod- def _column_name_predicate(names: list[str], selected_schema: Optional[str]) -> tuple[str, dict[str, str]]:- """Build a WHERE fragment restricting `information_schema.columns` to the requested tables.+ def _scope_predicates(selected_schema: Optional[str], schema_column: str) -> tuple[list[str], dict[str, str]]:+ """WHERE fragments that pin a catalog query to the configured namespace(s).++ Pinned schema → that schema only. Blank schema → every namespace except the Redshift+ system schemas and per-session temp schemas.+ """+ if selected_schema is not None:+ return [f"{schema_column} = %(schema)s"], {"schema": selected_schema}+ placeholders, params = _named_placeholders("system_schema", SYSTEM_REDSHIFT_SCHEMAS)+ return [f"{schema_column} NOT IN ({placeholders})", f"{schema_column} NOT LIKE 'pg_temp_%%'"], params++ @staticmethod+ def _column_name_predicate(+ names: list[str],+ selected_schema: Optional[str],+ *,+ schema_column: str = "table_schema",+ table_column: str = "table_name",+ ) -> tuple[str, dict[str, str]]:+ """Build a WHERE fragment restricting a column listing to the requested tables.Pinned schema → match by bare `table_name`. Blank schema → match each qualified`schema.table` on both parts (bare names fall back to any-schema for legacy self-heal).@@ -917,18 +1004,84 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycofor index, name in enumerate(names):if selected_schema is not None:params[f"name_{index}"] = name- clauses.append(f"table_name = %(name_{index})s")+ clauses.append(f"{table_column} = %(name_{index})s")continueschema, _, table = name.partition(".")if table:params[f"sch_{index}"] = schemaparams[f"tbl_{index}"] = table- clauses.append(f"(table_schema = %(sch_{index})s AND table_name = %(tbl_{index})s)")+ clauses.append(f"({schema_column} = %(sch_{index})s AND {table_column} = %(tbl_{index})s)")else:params[f"name_{index}"] = name- clauses.append(f"table_name = %(name_{index})s")+ clauses.append(f"{table_column} = %(name_{index})s")return "(" + " OR ".join(clauses) + ")", params+ def _undiscovered_relations(+ self,+ conn: psycopg.Connection,+ cursor: Any,+ selected_schema: Optional[str],+ names: list[str] | None,+ listed: list[tuple[Any, ...]],+ ) -> list[str]:+ """Display names that `information_schema.columns` returned no rows for, but that should exist.++ With explicit `names` those are the requested relations themselves — the caller knows they+ exist. Without, the candidates are the materialized views `svv_mv_info` lists in scope, the+ relation type `information_schema` hides from non-owner roles. That probe is best-effort: a+ role without access to `svv_mv_info` keeps the plain listing.+ """+ found_pairs = {(table_schema, table_name) for table_schema, table_name, *_ in listed}+ found_tables = {table_name for _, table_name in found_pairs}++ def is_found(display: str) -> bool:+ schema, table = _split_display_name(display, selected_schema)+ return table in found_tables if schema is None else (schema, table) in found_pairs++ if names:+ return [name for name in names if not is_found(name)]++ where, params = self._scope_predicates(selected_schema, "schema_name")+ try:+ cursor.execute(f"SELECT schema_name, name FROM svv_mv_info WHERE {' AND '.join(where)}", params)+ rows = cursor.fetchall()+ except Exception:+ _recover_after_failed_probe(conn)+ return []+ return [+ display+ for schema_name, view_name in rows+ if not is_found(display := _display_name(schema_name, view_name, qualify=selected_schema is None))+ ]++ def _columns_from_catalog(+ self,+ conn: psycopg.Connection,+ cursor: Any,+ names: list[str],+ selected_schema: Optional[str],+ ) -> list[_CatalogColumn]:+ """Columns of `names`, read from `pg_catalog` instead of `information_schema.columns`.++ Best-effort: a failure here leaves discovery with what `information_schema` returned, the+ same result as before the fallback existed.+ """+ where, params = self._scope_predicates(selected_schema, "n.nspname")+ name_clause, name_params = self._column_name_predicate(+ names, selected_schema, schema_column="n.nspname", table_column="c.relname"+ )+ where.append(name_clause)+ params.update(name_params)+ params["internal_column"] = REDSHIFT_INTERNAL_COLUMN_LIKE+ try:+ cursor.execute(_CATALOG_COLUMNS_SQL.format(where=" AND ".join(where)), params)+ rows = cursor.fetchall()+ except Exception as e:+ _recover_after_failed_probe(conn)+ structlog.get_logger().warning("Failed to read Redshift columns from pg_catalog", exc_info=e)+ return []+ return [_CatalogColumn.from_row(*row) for row in rows]+def get_primary_keys(self,conn: psycopg.Connection,@@ -1354,22 +1507,38 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco_explain_query(cursor, query, logger)logger.debug(f"Running query: {query.as_string()}")cursor.execute(query)+ rows = [+ _CatalogColumn(+ schema=schema,+ table=table_name,+ name=name,+ data_type=data_type,+ nullable=nullable == "YES",+ numeric_precision=numeric_precision,+ numeric_scale=numeric_scale,+ )+ for name, data_type, nullable, numeric_precision, numeric_scale in cursor+ ]+ if not rows:+ rows = self._column_metadata_from_catalog(cursor, schema, table_name)numeric_data_types = {"numeric", "decimal"}columns = []- for name, data_type, nullable, numeric_precision_candidate, numeric_scale_candidate in cursor:- if data_type in numeric_data_types:- numeric_precision = numeric_precision_candidate or DEFAULT_NUMERIC_PRECISION- numeric_scale = numeric_scale_candidate or DEFAULT_NUMERIC_SCALE+ for row in rows:+ if row.data_type in numeric_data_types:+ numeric_precision = (+ row.numeric_precision if row.numeric_precision is not None else DEFAULT_NUMERIC_PRECISION+ )+ numeric_scale = row.numeric_scale if row.numeric_scale is not None else DEFAULT_NUMERIC_SCALEelse:numeric_precision = Nonenumeric_scale = Nonecolumns.append(RedshiftColumn(- name=name,- data_type=data_type,- nullable=nullable == "YES",+ name=row.name,+ data_type=row.data_type,+ nullable=row.nullable,numeric_precision=numeric_precision,numeric_scale=numeric_scale,)@@ -1382,6 +1551,14 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycotable_type = "view"return Table(name=table_name, parents=(schema,), columns=columns, type=table_type)+ @staticmethod+ def _column_metadata_from_catalog(cursor: psycopg.Cursor, schema: str, table_name: str) -> list[_CatalogColumn]:+ cursor.execute(+ _CATALOG_COLUMNS_SQL.format(where="n.nspname = %(schema)s AND c.relname = %(table)s"),+ {"schema": schema, "table": table_name, "internal_column": REDSHIFT_INTERNAL_COLUMN_LIKE},+ )+ return [_CatalogColumn.from_row(*row) for row in cursor.fetchall()]+def get_rows_to_sync(self,cursor: psycopg.Cursor,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.pyindex 8f01d8642693..b19afd21df03 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@@ -1,6 +1,7 @@from collections.abc import Iteratorfrom contextlib import contextmanagerfrom datetime import date+from typing import Anyimport pytestfrom unittest.mock import MagicMock, call, patch@@ -456,17 +457,52 @@ class TestGetTableMetadata:assert table.type == "view"- def test_populates_numeric_precision_and_scale_for_decimals(self, impl, cursor):+ @pytest.mark.parametrize(+ "catalog_precision,catalog_scale,expected",+ [+ (10, 2, (10, 2)),+ # `numeric(18,0)` reports a scale of 0, which is a value, not a missing one: swapping it+ # for the default made `decimal128(18,18)`, which cannot hold an integer.+ (18, 0, (18, 0)),+ (None, None, (38, 18)),+ ],+ )+ def test_populates_numeric_precision_and_scale_for_decimals(+ self, impl, cursor, catalog_precision, catalog_scale, expected+ ):cursor.execute.return_value = cursorcursor.fetchone.return_value = (False,)- cursor.__iter__.return_value = iter(- [- ("amount", "decimal", "NO", 10, 2),- ]- )+ cursor.__iter__.return_value = iter([("amount", "decimal", "NO", catalog_precision, catalog_scale)])+table = impl.get_table_metadata(cursor, "public", "orders")- assert table.columns[0].numeric_precision == 10- assert table.columns[0].numeric_scale == 2++ assert (table.columns[0].numeric_precision, table.columns[0].numeric_scale) == expected+ assert str(table.columns[0].to_arrow_field().type) == f"decimal128({expected[0]}, {expected[1]})"++ def test_reads_columns_from_pg_catalog_when_information_schema_hides_the_relation(self, impl, cursor):+ # Without the fallback a materialized view the role can read but `information_schema`+ # does not list synced with an empty Arrow schema.+ cursor.execute.return_value = cursor+ cursor.fetchone.return_value = (True,)+ cursor.__iter__.return_value = iter([])+ cursor.fetchall.return_value = [+ ("public", "daily_totals", "day", "date", "NO"),+ ("public", "daily_totals", "total", "numeric(18,2)", "YES"),+ ("public", "daily_totals", "units", "numeric(18)", "YES"),+ ]++ table = impl.get_table_metadata(cursor, "public", "daily_totals")++ assert table.type == "materialized_view"+ assert [(c.name, c.data_type, c.nullable) for c in table.columns] == [+ ("day", "date", False),+ ("total", "numeric", True),+ ("units", "numeric", True),+ ]+ assert [(c.numeric_precision, c.numeric_scale) for c in table.columns[1:]] == [(18, 2), (18, 0)]+ catalog_sql, catalog_params = cursor.execute.call_args.args+ assert "pg_catalog.pg_attribute" in catalog_sql+ assert catalog_params == {"schema": "public", "table": "daily_totals", "internal_column": "padb_internal%"}def test_excludes_redshift_internal_columns_from_arrow_schema(self, impl, cursor):# Materialized views expose `padb_internal_*` bookkeeping columns in@@ -942,17 +978,24 @@ class TestHasDuplicatePrimaryKeys:# ---------------------------------------------------------------------------+def _columns_conn(*fetches: list[tuple[Any, ...]]) -> tuple[MagicMock, MagicMock]:+ conn = MagicMock()+ cur = MagicMock()+ cur.__enter__.return_value = cur+ cur.fetchall.side_effect = [*fetches, [], [], []]+ conn.cursor.return_value = cur+ return conn, cur++class TestGetColumns:def test_returns_columns_grouped_by_table(self, impl):- conn = MagicMock()- cur = MagicMock()- cur.__enter__.return_value = cur- cur.fetchall.return_value = [- ("public", "users", "id", "integer", "NO"),- ("public", "users", "email", "varchar", "YES"),- ("public", "orders", "id", "bigint", "NO"),- ]- conn.cursor.return_value = cur+ conn, cur = _columns_conn(+ [+ ("public", "users", "id", "integer", "NO"),+ ("public", "users", "email", "varchar", "YES"),+ ("public", "orders", "id", "bigint", "NO"),+ ]+ )result = impl.get_columns(conn, _make_config(), names=None)@@ -961,43 +1004,33 @@ class TestGetColumns:"users": [("id", "integer", False), ("email", "varchar", True)],"orders": [("id", "bigint", False)],}- executed_sql = cur.execute.call_args.args[0]+ executed_sql = cur.execute.call_args_list[0].args[0]assert "table_schema = %(schema)s" in executed_sqldef test_returns_empty_when_no_rows(self, impl):- conn = MagicMock()- cur = MagicMock()- cur.__enter__.return_value = cur- cur.fetchall.return_value = []- conn.cursor.return_value = cur+ conn, _cur = _columns_conn([])assert impl.get_columns(conn, _make_config(), names=["foo"]) == {}def test_excludes_redshift_internal_columns(self, impl):# Discovery must drop the `padb_internal_*` columns Redshift stamps onto materialized# views — they never come back from `SELECT *`, so surfacing them desyncs the schema.- conn = MagicMock()- cur = MagicMock()- cur.__enter__.return_value = cur- cur.fetchall.return_value = []- conn.cursor.return_value = cur+ conn, cur = _columns_conn([])impl.get_columns(conn, _make_config(), names=None)- executed_sql, executed_params = cur.execute.call_args.args+ executed_sql, executed_params = cur.execute.call_args_list[0].argsassert "column_name NOT LIKE %(internal_column)s" in executed_sqlassert executed_params["internal_column"] == "padb_internal%"def test_blank_schema_qualifies_and_excludes_system_schemas(self, impl):- conn = MagicMock()- cur = MagicMock()- cur.__enter__.return_value = cur# Same table name in two schemas must stay distinct.- cur.fetchall.return_value = [- ("analytics", "users", "id", "integer", "NO"),- ("public", "users", "id", "bigint", "NO"),- ]- conn.cursor.return_value = cur+ conn, cur = _columns_conn(+ [+ ("analytics", "users", "id", "integer", "NO"),+ ("public", "users", "id", "bigint", "NO"),+ ]+ )result = impl.get_columns(conn, _make_config(schema=""), names=None)@@ -1005,17 +1038,13 @@ class TestGetColumns:"analytics.users": [("id", "integer", False)],"public.users": [("id", "bigint", False)],}- executed_sql, executed_params = cur.execute.call_args.args+ executed_sql, executed_params = cur.execute.call_args_list[0].argsassert "table_schema NOT IN" in executed_sqlassert "pg_temp_%" in executed_sqlassert set(executed_params.values()) >= {"pg_catalog", "information_schema", "pg_internal", "pg_automv"}def test_blank_schema_with_qualified_names_filters_by_pair(self, impl):- conn = MagicMock()- cur = MagicMock()- cur.__enter__.return_value = cur- cur.fetchall.return_value = [("analytics", "users", "id", "integer", "NO")]- conn.cursor.return_value = cur+ conn, cur = _columns_conn([("analytics", "users", "id", "integer", "NO")])result = impl.get_columns(conn, _make_config(schema=""), names=["analytics.users"])@@ -1025,6 +1054,72 @@ class TestGetColumns:assert executed_params["sch_0"] == "analytics"assert executed_params["tbl_0"] == "users"+ def test_requested_relation_hidden_from_information_schema_is_read_from_pg_catalog(self, impl):+ # A materialized view the role can read may still have no `information_schema.columns`+ # rows, which made "edit sync method" report the relation as missing or unreadable.+ conn, cur = _columns_conn(+ [("public", "orders", "id", "bigint", "NO")],+ [+ ("public", "daily_totals", "day", "date", "NO"),+ ("public", "daily_totals", "total", "numeric(18,2)", "YES"),+ ("public", "daily_totals", "label", "character varying(256)", "YES"),+ ("public", "daily_totals", "refreshed_at", "timestamp without time zone", "YES"),+ ],+ )++ result = impl.get_columns(conn, _make_config(schema=""), names=["public.orders", "public.daily_totals"])++ assert result == {+ "public.orders": [("id", "bigint", False)],+ "public.daily_totals": [+ ("day", "date", False),+ ("total", "numeric", True),+ ("label", "character varying", True),+ ("refreshed_at", "timestamp without time zone", True),+ ],+ }+ catalog_sql, catalog_params = cur.execute.call_args.args+ assert "pg_catalog.pg_attribute" in catalog_sql+ assert "n.nspname = %(sch_0)s AND c.relname = %(tbl_0)s" in catalog_sql+ assert catalog_params["tbl_0"] == "daily_totals"+ assert "orders" not in catalog_params.values()++ def test_full_listing_adds_materialized_views_missing_from_information_schema(self, impl):+ # A schema refresh disables the sync of every table it no longer lists, so a hidden+ # materialized view has to come back from `svv_mv_info` + `pg_catalog`. One that+ # `information_schema` did list must not be read twice.+ conn, cur = _columns_conn(+ [+ ("public", "orders", "id", "bigint", "NO"),+ ("public", "listed_mv", "id", "bigint", "NO"),+ ],+ [("public", "listed_mv"), ("public", "hidden_mv")],+ [("public", "hidden_mv", "id", "integer", "NO")],+ )++ result = impl.get_columns(conn, _make_config(), names=None)++ assert result == {+ "orders": [("id", "bigint", False)],+ "listed_mv": [("id", "bigint", False)],+ "hidden_mv": [("id", "integer", False)],+ }+ mv_sql = cur.execute.call_args_list[1].args[0]+ assert "svv_mv_info" in mv_sql+ catalog_params = cur.execute.call_args.args[1]+ assert catalog_params["name_0"] == "hidden_mv"+ assert "listed_mv" not in catalog_params.values()++ def test_full_listing_keeps_information_schema_rows_when_mv_probe_fails(self, impl):+ conn, cur = _columns_conn([("public", "orders", "id", "bigint", "NO")])+ cur.execute.side_effect = [cur, Exception("permission denied for relation svv_mv_info")]+ conn.info.transaction_status = TransactionStatus.INERROR++ result = impl.get_columns(conn, _make_config(), names=None)++ assert result == {"orders": [("id", "bigint", False)]}+ conn.rollback.assert_called_once()+class TestGetPrimaryKeys:def test_returns_empty_for_no_tables(self, impl):diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_redshift_source.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_redshift_source.pynew file mode 100644index 000000000000..b7712e0d1c32--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_redshift_source.py@@ -0,0 +1,117 @@+"""Redshift source discovery against a live Postgres.++Redshift speaks the Postgres wire protocol and derives its catalogs from Postgres, and no Redshift+cluster is reachable from CI, so the Django test database stands in for the cluster. Postgres hides+a materialized view from `information_schema.columns` for real (`relkind = 'm'`), which is the same+symptom the Redshift `pg_catalog` fallback exists for, so these tests fail without it.+"""++import uuid+from collections.abc import Iterator+from contextlib import contextmanager++import pytest+from unittest import mock++import psycopg+from rest_framework import status+from rest_framework.test import APIClient++from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.test_jobs_db import (+ _get_test_database_url,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift import RedshiftImplementation+from products.warehouse_sources.backend.temporal.data_imports.sources.redshift.source import RedshiftSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++SCHEMA = "redshift_e2e"+MATERIALIZED_VIEW = "daily_totals_mv"+++def materialized_view(db: None) -> Iterator[None]:+ with psycopg.connect(_get_test_database_url(), autocommit=True) as conn:+ conn.execute(f"DROP SCHEMA IF EXISTS {SCHEMA} CASCADE")+ conn.execute(f"CREATE SCHEMA {SCHEMA}")+ conn.execute(+ f"CREATE TABLE {SCHEMA}.orders "+ "(id bigint PRIMARY KEY, amount numeric(18,2), label varchar(256), created_at timestamp)"+ )+ conn.execute(f"INSERT INTO {SCHEMA}.orders VALUES (1, 10.5, 'first', now())")+ conn.execute(+ f"CREATE MATERIALIZED VIEW {SCHEMA}.{MATERIALIZED_VIEW} AS "+ f"SELECT id, created_at::date AS day, sum(amount) AS total, max(created_at) AS refreshed_at "+ f"FROM {SCHEMA}.orders GROUP BY 1, 2"+ )+ try:+ yield+ finally:+ conn.execute(f"DROP SCHEMA IF EXISTS {SCHEMA} CASCADE")+++@contextmanager+def _redshift_backed_by_test_database() -> Iterator[None]:+ """Route the Redshift driver's connection to the test database, keeping every query real."""++ @contextmanager+ def connect(self: RedshiftImplementation, config: object, *, team_id: int | None = None):+ with psycopg.connect(_get_test_database_url()) as conn:+ yield conn++ with (+ mock.patch.object(RedshiftImplementation, "connect", connect),+ mock.patch.object(RedshiftSource, "is_database_host_valid", return_value=(True, None)),+ ):+ yield++[email protected]("materialized_view")+def test_incremental_fields_for_a_materialized_view_hidden_from_information_schema(team, user):+ source = ExternalDataSource.objects.create(+ team=team,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ source_type=ExternalDataSourceType.REDSHIFT,+ job_inputs={+ "host": "redshift.example.com",+ "port": "5439",+ "database": "warehouse",+ "user": "posthog",+ "password": "not-a-real-password",+ "schema": SCHEMA,+ },+ )+ schema = ExternalDataSchema.objects.create(+ team=team, source=source, name=MATERIALIZED_VIEW, should_sync=True, sync_type="full_refresh"+ )+ client = APIClient()+ client.force_login(user)++ with _redshift_backed_by_test_database():+ response = client.post(f"/api/environments/{team.pk}/external_data_schemas/{schema.id}/incremental_fields")++ assert response.status_code == status.HTTP_200_OK, response.json()+ body = response.json()+ assert body["incremental_available"] is True+ assert {(f["field"], f["field_type"]) for f in body["incremental_fields"]} == {+ ("id", "integer"),+ ("day", "date"),+ ("refreshed_at", "timestamp"),+ }+ assert {c["field"] for c in body["available_columns"]} == {"id", "day", "total", "refreshed_at"}++[email protected]("materialized_view")+def test_sync_time_metadata_for_a_materialized_view_hidden_from_information_schema():+ with psycopg.connect(_get_test_database_url(), autocommit=True) as conn, conn.cursor() as cursor:+ table = RedshiftImplementation().get_table_metadata(cursor, SCHEMA, MATERIALIZED_VIEW)++ assert [(column.name, column.data_type) for column in table.columns] == [+ ("id", "bigint"),+ ("day", "date"),+ ("total", "numeric"),+ ("refreshed_at", "timestamp without time zone"),+ ]+ assert str(table.to_arrow_schema().field("total").type) == "decimal128(38, 18)"