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 redshift to SQLSourceImplementation (#59712)

Daniel RC7fbe8260ee22
diff --git a/posthog/temporal/data_imports/sources/redshift/redshift.py b/posthog/temporal/data_imports/sources/redshift/redshift.py
index e9a74237994c..53a0ae01bd58 100644
--- a/posthog/temporal/data_imports/sources/redshift/redshift.py
+++ b/posthog/temporal/data_imports/sources/redshift/redshift.py
@@ -1,9 +1,18 @@
+"""Redshift driver for PostHog's data-warehouse import pipeline.
+
+Everything Redshift-specific — psycopg connection lifecycle (with SSH
+tunnel), schema listing, sortkey discovery, per-cursor metadata for the
+streaming sync, and the dlt pipeline build — lives on
+`RedshiftImplementation`. The source-class `RedshiftSource` is a thin
+PostHog-layer wrapper that just holds an instance and validates
+credentials.
+"""
+
from __future__ import annotations
-import math
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, Literal, LiteralString, Optional, cast
import psycopg
@@ -19,20 +28,43 @@ 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,
QueryTimeoutException,
TemporaryFileSizeExceedsLimitException,
build_pyarrow_decimal_type,
table_from_iterator,
)
+from posthog.temporal.data_imports.sources.common.mixins import open_ssh_tunnel
from posthog.temporal.data_imports.sources.common.sql import Column, Table
-
-from products.data_warehouse.backend.types import IncrementalFieldType, PartitionSettings
+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 RedshiftSourceConfig
+
+from products.data_warehouse.backend.types import IncrementalFieldType
+
+__all__ = [
+ "JsonAsStringLoader",
+ "RedshiftColumn",
+ "RedshiftImplementation",
+ "filter_redshift_incremental_fields",
+]
+
+
+# Shared psycopg.connect kwargs for Redshift. SSL is required; the SSL
+# cert paths are intentionally pointed at non-existent files so psycopg
+# uses the system default verification without picking up an unintended
+# client cert.
+_REDSHIFT_CONNECT_OPTS: dict[str, Any] = {
+ "sslmode": "require",
+ "connect_timeout": 15,
+ "sslrootcert": "/tmp/no.txt",
+ "sslcert": "/tmp/no.txt",
+ "sslkey": "/tmp/no.txt",
+ "options": "-c client_encoding=UTF8",
+}
def filter_redshift_incremental_fields(
@@ -52,124 +84,6 @@ def filter_redshift_incremental_fields(
return results
-def get_redshift_row_count(
- host: str, port: int, database: str, user: str, password: str, schema: str, names: list[str] | None = None
-) -> dict[str, int]:
- """Get row counts for all tables in a Redshift schema."""
- connection = psycopg.connect(
- host=host,
- port=port,
- dbname=database,
- user=user,
- password=password,
- sslmode="require",
- connect_timeout=15,
- sslrootcert="/tmp/no.txt",
- sslcert="/tmp/no.txt",
- sslkey="/tmp/no.txt",
- options="-c client_encoding=UTF8",
- )
-
- try:
- with connection.cursor() as cursor:
- cursor.execute(
- sql.SQL("SET statement_timeout = {timeout}").format(timeout=sql.Literal(1000 * 30)) # 30 secs
- )
-
- params: dict = {"schema": schema}
- names_filter = ""
- if names:
- params["names"] = names
- names_filter = 'AND "table" = ANY(%(names)s)'
-
- cursor.execute(
- f"""
- SELECT "table" AS table_name, tbl_rows AS row_count
- FROM svv_table_info
- WHERE schema = %(schema)s {names_filter}
- """,
- params,
- )
- row_count_result = cursor.fetchall()
- row_counts = {row[0]: int(row[1]) for row in row_count_result}
-
- views_params: dict = {"schema": schema}
- views_names_filter = ""
- if names is not None:
- views_params["names"] = names
- views_names_filter = "AND viewname = ANY(%(names)s)"
-
- cursor.execute(
- f"SELECT viewname FROM pg_views WHERE schemaname = %(schema)s {views_names_filter}",
- views_params,
- )
- views = cursor.fetchall()
-
- if views:
- view_counts = [
- sql.SQL("SELECT {view_name} AS table_name, COUNT(*) AS row_count FROM {schema}.{view}").format(
- view_name=sql.Literal(view[0]),
- schema=sql.Identifier(schema),
- view=sql.Identifier(view[0]),
- )
- for view in views
- ]
- cursor.execute(sql.SQL(" UNION ALL ").join(view_counts))
- for row in cursor.fetchall():
- row_counts[row[0]] = int(row[1])
-
- return row_counts
- except Exception:
- return {}
- finally:
- connection.close()
-
-
-def get_schemas(
- host: str, database: str, user: str, password: str, schema: str, port: int, names: list[str] | None = None
-) -> dict[str, list[tuple[str, str, bool]]]:
- """Get all tables from Redshift source schemas to sync."""
- connection = psycopg.connect(
- host=host,
- port=port,
- dbname=database,
- user=user,
- password=password,
- sslmode="require",
- connect_timeout=15,
- sslrootcert="/tmp/no.txt",
- sslcert="/tmp/no.txt",
- sslkey="/tmp/no.txt",
- options="-c client_encoding=UTF8",
- )
-
- with connection.cursor() as cursor:
- params: dict = {"schema": schema}
- names_filter = ""
- if names:
- params["names"] = names
- names_filter = "AND table_name = ANY(%(names)s)"
-
- cursor.execute(
- f"""
- SELECT table_name, column_name, data_type, is_nullable
- FROM information_schema.columns
- WHERE table_schema = %(schema)s {names_filter}
- ORDER BY table_name ASC
- """,
- params,
- )
- result = cursor.fetchall()
-
- schema_list: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)
- for row in result:
- schema_list[row[0]].append((row[1], row[2], row[3] == "YES"))
-
- connection.close()
-
- return schema_list
-
-
class JsonAsStringLoader(Loader):
def load(self, data):
if data is None:
@@ -253,321 +167,6 @@ def _explain_query(cursor: psycopg.Cursor, query: sql.Composed, logger: Filterin
logger.debug(f"EXPLAIN raised an exception: {e}")
-def get_leading_sortkey_columns_for_schemas(
- host: str,
- database: str,
- user: str,
- password: str,
- schema: str,
- port: int,
- table_names: list[str],
-) -> dict[str, set[str]] | None:
- """Return the columns that drive `WHERE col >= …` predicate pushdown per table.
-
- Redshift is columnar with no traditional B-tree indexes; SORTKEYs are the
- structure that accelerates predicate pushdown. The `sortkey` value reported
- by `pg_table_def` encodes both the kind of sortkey and the column's
- position:
-
- - **Compound sortkeys** use positive integers (1, 2, 3, …) where ``sortkey = 1``
- is the leading column. Only the leading column meaningfully accelerates
- `WHERE col >= …`; subsequent columns require equality predicates on
- preceding columns to be useful.
- - **Interleaved sortkeys** mix signs (e.g. ``-1, 2, -3, 4``). All non-zero
- sortkey columns contribute equally to predicate pushdown by design — the
- whole point of interleaved sortkeys is to give every column equal
- weight. Treating only ``sortkey = -1`` as indexed produces false warnings
- on the other interleaved columns.
-
- Returns None when discovery fails so the caller defaults to no-warning.
- Tables with no sortkey return an empty set so the warning fires.
- """
- if not table_names:
- return {}
-
- result: dict[str, set[str]] = {table: set() for table in table_names}
-
- try:
- with psycopg.connect(
- host=host,
- port=port,
- dbname=database,
- user=user,
- password=password,
- sslmode="require",
- connect_timeout=15,
- sslrootcert="/tmp/no.txt",
- sslcert="/tmp/no.txt",
- sslkey="/tmp/no.txt",
- options="-c client_encoding=UTF8",
- ) as connection:
- with connection.cursor() as cursor:
- # pg_table_def only returns rows for schemas in search_path; without
- # this SET, schema=anything-other-than-public-or-the-username silently
- # returns zero rows and the helper marks every sortkey column as
- # unindexed. Documented behavior: docs.aws.amazon.com/redshift/latest/dg/r_PG_TABLE_DEF.html
- cursor.execute(sql.SQL("SET search_path TO {schema}").format(schema=sql.Identifier(schema)))
- cursor.execute(
- sql.SQL("""
- SELECT tablename, "column", sortkey
- FROM pg_table_def
- WHERE schemaname = {schema}
- AND tablename = ANY({names})
- AND sortkey != 0
- """).format(schema=sql.Literal(schema), names=sql.Literal(table_names))
- )
- # Group rows by table so we can classify compound vs interleaved
- # before deciding which columns count as indexed. Negative sortkey
- # values are the marker Redshift uses for interleaved sortkeys.
- rows_by_table: dict[str, list[tuple[str, int]]] = {}
- for table_name, column_name, sortkey_value in cursor.fetchall():
- rows_by_table.setdefault(table_name, []).append((column_name, sortkey_value))
-
- for table_name, sortkey_rows in rows_by_table.items():
- is_interleaved = any(sk < 0 for _, sk in sortkey_rows)
- if is_interleaved:
- result[table_name] = {col for col, _ in sortkey_rows}
- else:
- result[table_name] = {col for col, sk in sortkey_rows if sk == 1}
- except Exception as e:
- structlog.get_logger().warning("Failed to detect sortkeys for Redshift schemas", exc_info=e)
- return None
-
- return result
-
-
-def get_primary_keys_for_schemas(
- host: str,
- database: str,
- user: str,
- password: str,
- schema: str,
- port: int,
- table_names: list[str],
-) -> dict[str, list[str] | None]:
- """Detect primary keys for all tables in a single query."""
- result: dict[str, list[str] | None] = dict.fromkeys(table_names)
-
- try:
- with psycopg.connect(
- host=host,
- port=port,
- dbname=database,
- user=user,
- password=password,
- sslmode="require",
- connect_timeout=15,
- sslrootcert="/tmp/no.txt",
- sslcert="/tmp/no.txt",
- sslkey="/tmp/no.txt",
- options="-c client_encoding=UTF8",
- ) as connection:
- with connection.cursor() as cursor:
- cursor.execute(
- sql.SQL("""
- SELECT tc.table_name, kcu.column_name
- FROM information_schema.table_constraints tc
- JOIN information_schema.key_column_usage kcu
- ON tc.constraint_name = kcu.constraint_name
- AND tc.table_schema = kcu.table_schema
- AND tc.table_name = kcu.table_name
- WHERE tc.table_schema = {schema}
- AND tc.table_name = ANY({names})
- AND tc.constraint_type = 'PRIMARY KEY'
- """).format(schema=sql.Literal(schema), names=sql.Literal(table_names))
- )
- rows = cursor.fetchall()
-
- pks: dict[str, list[str]] = collections.defaultdict(list)
- for table_name, column_name in rows:
- pks[table_name].append(column_name)
-
- for table_name, pk_cols in pks.items():
- result[table_name] = pk_cols
- except Exception as e:
- structlog.get_logger().warning("Failed to detect primary keys for Redshift schemas", exc_info=e)
-
- return result
-
-
-def _get_primary_keys(
- cursor: psycopg.Cursor, schema: str, table_name: str, logger: FilteringBoundLogger
-) -> list[str] | None:
- query = sql.SQL("""
- SELECT
- kcu.column_name
- FROM
- information_schema.table_constraints tc
- JOIN
- information_schema.key_column_usage kcu
- ON tc.constraint_name = kcu.constraint_name
- AND tc.table_schema = kcu.table_schema
- WHERE
- tc.table_schema = {schema}
- AND tc.table_name = {table}
- AND tc.constraint_type = 'PRIMARY KEY'""").format(schema=sql.Literal(schema), table=sql.Literal(table_name))
-
- _explain_query(cursor, query, logger)
- logger.debug(f"Running query: {query.as_string()}")
- cursor.execute(query)
- rows = cursor.fetchall()
- if len(rows) > 0:
- return [row[0] for row in rows]
-
- logger.warning(
- f"No primary keys found for {table_name}. If the table is not a view, (a) does the table have a primary key set? (b) is the primary key returned from querying information_schema?"
- )
-
- return None
-
-
-def _has_duplicate_primary_keys(
- cursor: psycopg.Cursor, schema: str, table_name: str, primary_keys: list[str] | None, logger: FilteringBoundLogger
-) -> bool:
- if not primary_keys or len(primary_keys) == 0:
- return False
-
- try:
- sql_query = cast(
- LiteralString,
- f"""
- SELECT {", ".join(["{}" for _ in primary_keys])}
- FROM {{}}.{{}}
- GROUP BY {", ".join([str(i + 1) for i, _ in enumerate(primary_keys)])}
- HAVING COUNT(*) > 1
- LIMIT 1
- """,
- )
- query = sql.SQL(sql_query).format(
- *[sql.Identifier(key) for key in primary_keys], sql.Identifier(schema), sql.Identifier(table_name)
- )
- _explain_query(cursor, query, logger)
- logger.debug(f"Running query: {query.as_string()}")
- cursor.execute(query)
- row = cursor.fetchone()
-
- return row is not None
- except psycopg.errors.QueryCanceled:
- raise
- except Exception as e:
- capture_exception(e)
- return False
-
-
-def _get_table_chunk_size(cursor: psycopg.Cursor, inner_query: sql.Composed, logger: FilteringBoundLogger) -> int:
- try:
- # Note: pg_column_size works in Redshift but may have slight differences
- query = sql.SQL("""
- SELECT percentile_cont(0.95) within group (order by subquery.row_size) FROM (
- SELECT pg_column_size(t) as row_size FROM ({}) as t
- ) as subquery
- """).format(inner_query)
-
- _explain_query(cursor, query, logger)
- logger.debug(f"Running query: {query.as_string()}")
- cursor.execute(query)
- row = cursor.fetchone()
-
- if row is None:
- logger.debug(f"_get_table_chunk_size: No results returned. Using DEFAULT_CHUNK_SIZE={DEFAULT_CHUNK_SIZE}")
- return DEFAULT_CHUNK_SIZE
-
- row_size_bytes = row[0] or 1
- 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
- except psycopg.errors.QueryCanceled:
- raise
- except Exception as e:
- logger.debug(f"_get_table_chunk_size: Error: {e}. Using DEFAULT_CHUNK_SIZE={DEFAULT_CHUNK_SIZE}", exc_info=e)
-
- return DEFAULT_CHUNK_SIZE
-
-
-def _get_rows_to_sync(cursor: psycopg.Cursor, inner_query: sql.Composed, logger: FilteringBoundLogger) -> int:
- try:
- query = sql.SQL("""
- SELECT COUNT(*) FROM ({}) as t
- """).format(inner_query)
-
- _explain_query(cursor, query, logger)
- logger.debug(f"Running query: {query.as_string()}")
- cursor.execute(query)
- row = cursor.fetchone()
-
- if row is None:
- logger.debug("_get_rows_to_sync: No results returned. Using 0 as rows to sync")
- return 0
-
- rows_to_sync = row[0] or 0
- rows_to_sync_int = int(rows_to_sync)
-
- logger.debug(f"_get_rows_to_sync: rows_to_sync_int={rows_to_sync_int}")
-
- return int(rows_to_sync)
- except psycopg.errors.QueryCanceled:
- raise
- 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)
-
- if "temporary file size exceeds temp_file_limit" in str(e):
- raise TemporaryFileSizeExceedsLimitException(
- f"Error: {e}. Please ensure your incremental field is set as a SORTKEY on the table"
- )
-
- return 0
-
-
-def _get_partition_settings(
- cursor: psycopg.Cursor, schema: str, table_name: str, logger: FilteringBoundLogger
-) -> PartitionSettings | None:
- # Redshift uses different function for table size - using SVV_TABLE_INFO
- query = sql.SQL("""
- SELECT
- CASE WHEN tbl_rows = 0 OR size = 0 THEN NULL
- ELSE round({bytes_per_partition} / ((size * 1024 * 1024) / tbl_rows)) END,
- tbl_rows
- FROM svv_table_info
- WHERE schema = {schema} AND "table" = {table}
- """).format(
- bytes_per_partition=sql.Literal(DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES),
- schema=sql.Literal(schema),
- table=sql.Literal(table_name),
- )
-
- try:
- _explain_query(cursor, query, logger)
- logger.debug(f"Running query: {query.as_string()}")
- cursor.execute(query)
- except psycopg.errors.QueryCanceled:
- raise
- except Exception as e:
- capture_exception(e)
- logger.debug(f"_get_partition_settings: returning None due to error: {e}")
- return None
-
- result = cursor.fetchone()
-
- if result is None or len(result) == 0 or result[0] is None:
- logger.debug("_get_partition_settings: query result is None, returning None")
- return None
-
- partition_size = int(result[0])
- total_rows = int(result[1])
- partition_count = math.floor(total_rows / partition_size)
-
- if partition_count == 0:
- logger.debug(f"_get_partition_settings: partition_count=1, partition_size={partition_size}")
- return PartitionSettings(partition_count=1, partition_size=partition_size)
-
- logger.debug(f"_get_partition_settings: partition_count={partition_count}, partition_size={partition_size}")
- return PartitionSettings(partition_count=partition_count, partition_size=partition_size)
-
-
class RedshiftColumn(Column):
"""Implementation of the `Column` protocol for a Redshift source."""
@@ -629,94 +228,531 @@ class RedshiftColumn(Column):
return pa.field(self.name, arrow_type, nullable=self.nullable)
-def _get_table(
- cursor: psycopg.Cursor, schema: str, table_name: str, logger: FilteringBoundLogger
-) -> Table[RedshiftColumn]:
- # Check if it's a view
- is_view_query = sql.SQL(
- "SELECT {table} IN (SELECT viewname FROM pg_views WHERE schemaname = {schema}) as res"
- ).format(schema=sql.Literal(schema), table=sql.Literal(table_name))
- is_view_res = cursor.execute(is_view_query).fetchone()
- is_view = is_view_res is not None and is_view_res[0] is True
-
- query = sql.SQL("""
- SELECT
- column_name,
- data_type,
- is_nullable,
- numeric_precision,
- numeric_scale
- FROM
- information_schema.columns
- WHERE
- table_schema = {schema}
- AND table_name = {table}""").format(schema=sql.Literal(schema), table=sql.Literal(table_name))
-
- _explain_query(cursor, query, logger)
- logger.debug(f"Running query: {query.as_string()}")
- cursor.execute(query)
-
- 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
- else:
- numeric_precision = None
- numeric_scale = None
-
- columns.append(
- RedshiftColumn(
- name=name,
- data_type=data_type,
- nullable=nullable == "YES",
- numeric_precision=numeric_precision,
- numeric_scale=numeric_scale,
+class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycopg.Connection, Any]): # noqa: type-var
+ # `psycopg.Cursor` does not satisfy `_CursorLike` (its `execute`
+ # signature uses `params` instead of `args`, and accepts `Query`
+ # rather than `str`), so the cursor type is widened to `Any` here.
+ """Redshift driver implementation paired with `RedshiftSource`.
+
+ Owns the full Redshift lifecycle — SSH tunnel + psycopg connection,
+ `information_schema` and `svv_table_info` batch listing queries used
+ during schema discovery, per-cursor metadata used during the
+ streaming sync, and the dlt pipeline factory (`build_pipeline`).
+ """
+
+ # ------------------------------------------------------------------
+ # Connection lifecycle
+ # ------------------------------------------------------------------
+
+ @contextmanager
+ def connect(self, config: RedshiftSourceConfig) -> Iterator[psycopg.Connection]:
+ """Open a psycopg connection for the duration of the context.
+
+ Opens the SSH tunnel (if configured) and connects with the
+ Redshift-wide SSL conventions in one place — every listing
+ method takes the resulting connection, so discovery against an
+ SSH-tunneled cluster only opens the tunnel once.
+ """
+ with open_ssh_tunnel(config) as (host, port):
+ with psycopg.connect(
+ host=host,
+ port=port,
+ dbname=config.database,
+ user=config.user,
+ password=config.password,
+ **_REDSHIFT_CONNECT_OPTS,
+ ) as conn:
+ yield conn
+
+ # ------------------------------------------------------------------
+ # Listing — batch queries run once during `get_schemas`
+ # ------------------------------------------------------------------
+
+ def get_columns(
+ self,
+ conn: psycopg.Connection,
+ config: RedshiftSourceConfig,
+ names: list[str] | None,
+ ) -> dict[str, list[tuple[str, str, bool]]]:
+ with conn.cursor() as cursor:
+ params: dict = {"schema": config.schema}
+ names_filter = ""
+ if names:
+ params["names"] = names
+ names_filter = "AND table_name = ANY(%(names)s)"
+
+ cursor.execute(
+ f"""
+ SELECT table_name, column_name, data_type, is_nullable
+ FROM information_schema.columns
+ WHERE table_schema = %(schema)s {names_filter}
+ ORDER BY table_name ASC
+ """,
+ params,
)
+ result = cursor.fetchall()
+
+ schema_list: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)
+ for row in result:
+ schema_list[row[0]].append((row[1], row[2], row[3] == "YES"))
+ return dict(schema_list)
+
+ def get_primary_keys(
+ self,
+ conn: psycopg.Connection,
+ config: RedshiftSourceConfig,
+ tables: list[str],
+ ) -> dict[str, list[str] | None]:
+ """Detect primary keys for all tables in a single query.
+
+ Permission-sensitive — some Redshift deployments restrict access
+ to `information_schema.table_constraints`. Swallow and log any
+ failure so schema discovery keeps working without PKs.
+ """
+ result: dict[str, list[str] | None] = dict.fromkeys(tables)
+ if not tables:
+ return result
+
+ try:
+ with conn.cursor() as cursor:
+ cursor.execute(
+ sql.SQL("""
+ SELECT tc.table_name, kcu.column_name
+ FROM information_schema.table_constraints tc
+ JOIN information_schema.key_column_usage kcu
+ ON tc.constraint_name = kcu.constraint_name
+ AND tc.table_schema = kcu.table_schema
+ AND tc.table_name = kcu.table_name
+ WHERE tc.table_schema = {schema}
+ AND tc.table_name = ANY({names})
+ AND tc.constraint_type = 'PRIMARY KEY'
+ """).format(schema=sql.Literal(config.schema), names=sql.Literal(tables))
+ )
+ rows = cursor.fetchall()
+ except Exception as e:
+ structlog.get_logger().warning("Failed to detect primary keys for Redshift schemas", exc_info=e)
+ return result
+
+ pks: dict[str, list[str]] = collections.defaultdict(list)
+ for table_name, column_name in rows:
+ pks[table_name].append(column_name)
+ for table_name, pk_cols in pks.items():
+ result[table_name] = pk_cols
+ return result
+
+ def get_row_counts(
+ self,
+ conn: psycopg.Connection,
+ config: RedshiftSourceConfig,
+ tables: list[str],
+ ) -> dict[str, int | None]:
+ """Return per-table row counts using `svv_table_info` for tables and `COUNT(*)` for views.
+
+ `svv_table_info.tbl_rows` is a Redshift system table that gives
+ cheap row count estimates for materialized tables; views aren't
+ in it, so they fall through to a (slower) `UNION ALL` of
+ `COUNT(*)` queries. Errors are swallowed — schema discovery
+ keeps working without row counts.
+ """
+ if not tables:
+ return {}
+
+ result: dict[str, int | None] = {}
+ try:
+ with conn.cursor() as cursor:
+ cursor.execute(
+ sql.SQL("SET statement_timeout = {timeout}").format(timeout=sql.Literal(1000 * 30)) # 30 secs
+ )
+
+ params: dict = {"schema": config.schema, "names": tables}
+ cursor.execute(
+ """
+ SELECT "table" AS table_name, tbl_rows AS row_count
+ FROM svv_table_info
+ WHERE schema = %(schema)s AND "table" = ANY(%(names)s)
+ """,
+ params,
+ )
+ for table_name, row_count in cursor.fetchall():
+ result[table_name] = int(row_count)
+
+ cursor.execute(
+ "SELECT viewname FROM pg_views WHERE schemaname = %(schema)s AND viewname = ANY(%(names)s)",
+ params,
+ )
+ views = cursor.fetchall()
+
+ if views:
+ view_counts = [
+ sql.SQL("SELECT {view_name} AS table_name, COUNT(*) AS row_count FROM {schema}.{view}").format(
+ view_name=sql.Literal(view[0]),
+ schema=sql.Identifier(config.schema),
+ view=sql.Identifier(view[0]),
+ )
+ for view in views
+ ]
+ cursor.execute(sql.SQL(" UNION ALL ").join(view_counts))
+ for row in cursor.fetchall():
+ result[row[0]] = int(row[1])
+ except Exception:
+ return {}
+
+ return result
+
+ def get_leading_index_columns(
+ self,
+ conn: psycopg.Connection,
+ config: RedshiftSourceConfig,
+ tables: list[str],
+ ) -> dict[str, set[str]] | None:
+ """Return the columns that drive `WHERE col >= …` predicate pushdown per table.
+
+ Redshift is columnar with no traditional B-tree indexes; SORTKEYs are the
+ structure that accelerates predicate pushdown. The `sortkey` value reported
+ by `pg_table_def` encodes both the kind of sortkey and the column's
+ position:
+
+ - **Compound sortkeys** use positive integers (1, 2, 3, …) where ``sortkey = 1``
+ is the leading column. Only the leading column meaningfully accelerates
+ `WHERE col >= …`; subsequent columns require equality predicates on
+ preceding columns to be useful.
+ - **Interleaved sortkeys** mix signs (e.g. ``-1, 2, -3, 4``). All non-zero
+ sortkey columns contribute equally to predicate pushdown by design — the
+ whole point of interleaved sortkeys is to give every column equal
+ weight. Treating only ``sortkey = -1`` as indexed produces false warnings
+ on the other interleaved columns.
+
+ Returns None when discovery fails so the caller defaults to no-warning.
+ Tables with no sortkey return an empty set so the warning fires.
+ """
+ if not tables:
+ return {}
+
+ result: dict[str, set[str]] = {table: set() for table in tables}
+
+ try:
+ with conn.cursor() as cursor:
+ # pg_table_def only returns rows for schemas in search_path; without
+ # this SET, schema=anything-other-than-public-or-the-username silently
+ # returns zero rows and the helper marks every sortkey column as
+ # unindexed. Documented behavior: docs.aws.amazon.com/redshift/latest/dg/r_PG_TABLE_DEF.html
+ cursor.execute(sql.SQL("SET search_path TO {schema}").format(schema=sql.Identifier(config.schema)))
+ cursor.execute(
+ sql.SQL("""
+ SELECT tablename, "column", sortkey
+ FROM pg_table_def
+ WHERE schemaname = {schema}
+ AND tablename = ANY({names})
+ AND sortkey != 0
+ """).format(schema=sql.Literal(config.schema), names=sql.Literal(tables))
+ )
+ # Group rows by table so we can classify compound vs interleaved
+ # before deciding which columns count as indexed. Negative sortkey
+ # values are the marker Redshift uses for interleaved sortkeys.
+ rows_by_table: dict[str, list[tuple[str, int]]] = {}
+ for table_name, column_name, sortkey_value in cursor.fetchall():
+ rows_by_table.setdefault(table_name, []).append((column_name, sortkey_value))
+
+ for table_name, sortkey_rows in rows_by_table.items():
+ is_interleaved = any(sk < 0 for _, sk in sortkey_rows)
+ if is_interleaved:
+ result[table_name] = {col for col, _ in sortkey_rows}
+ else:
+ result[table_name] = {col for col, sk in sortkey_rows if sk == 1}
+ except Exception as e:
+ structlog.get_logger().warning("Failed to detect sortkeys for Redshift schemas", exc_info=e)
+ return None
+
+ return result
+
+ def get_incremental_filter(self) -> IncrementalFieldFilter:
+ return filter_redshift_incremental_fields
+
+ # ------------------------------------------------------------------
+ # Per-cursor metadata — used during `build_pipeline`
+ # ------------------------------------------------------------------
+
+ def get_primary_keys_for_table(
+ self,
+ cursor: psycopg.Cursor,
+ schema: str,
+ table_name: str,
+ logger: FilteringBoundLogger | None = None,
+ ) -> list[str] | None:
+ """Return the primary-key column names for a single table, or None."""
+ query = sql.SQL("""
+ SELECT
+ kcu.column_name
+ FROM
+ information_schema.table_constraints tc
+ JOIN
+ information_schema.key_column_usage kcu
+ ON tc.constraint_name = kcu.constraint_name
+ AND tc.table_schema = kcu.table_schema
+ WHERE
+ tc.table_schema = {schema}
+ AND tc.table_name = {table}
+ AND tc.constraint_type = 'PRIMARY KEY'""").format(
+ schema=sql.Literal(schema), table=sql.Literal(table_name)
)
- table_type: Literal["view", "table"] = "view" if is_view else "table"
+ if logger is not None:
+ _explain_query(cursor, query, logger)
+ logger.debug(f"Running query: {query.as_string()}")
+ cursor.execute(query)
+ rows = cursor.fetchall()
+ if len(rows) > 0:
+ return [row[0] for row in rows]
- return Table(name=table_name, parents=(schema,), columns=columns, type=table_type)
+ if logger is not None:
+ logger.warning(
+ f"No primary keys found for {table_name}. If the table is not a view, (a) does the table have a primary key set? (b) is the primary key returned from querying information_schema?"
+ )
+ return None
+ def has_duplicate_primary_keys(
+ self,
+ cursor: psycopg.Cursor,
+ schema: str,
+ table_name: str,
+ primary_keys: list[str] | None,
+ logger: FilteringBoundLogger,
+ ) -> bool:
+ if not primary_keys or len(primary_keys) == 0:
+ return False
+
+ try:
+ sql_query = cast(
+ LiteralString,
+ f"""
+ SELECT {", ".join(["{}" for _ in primary_keys])}
+ FROM {{}}.{{}}
+ GROUP BY {", ".join([str(i + 1) for i, _ in enumerate(primary_keys)])}
+ HAVING COUNT(*) > 1
+ LIMIT 1
+ """,
+ )
+ query = sql.SQL(sql_query).format(
+ *[sql.Identifier(key) for key in primary_keys],
+ sql.Identifier(schema),
+ sql.Identifier(table_name),
+ )
+ _explain_query(cursor, query, logger)
+ logger.debug(f"Running query: {query.as_string()}")
+ cursor.execute(query)
+ row = cursor.fetchone()
+ return row is not None
+ except psycopg.errors.QueryCanceled:
+ raise
+ except Exception as e:
+ capture_exception(e)
+ return False
+
+ def get_table_metadata(
+ self,
+ cursor: psycopg.Cursor,
+ schema: str,
+ table_name: str,
+ logger: FilteringBoundLogger | None = None,
+ ) -> Table[RedshiftColumn]:
+ """Return rich column metadata for building a PyArrow schema."""
+ # Check if it's a view
+ is_view_query = sql.SQL(
+ "SELECT {table} IN (SELECT viewname FROM pg_views WHERE schemaname = {schema}) as res"
+ ).format(schema=sql.Literal(schema), table=sql.Literal(table_name))
+ is_view_res = cursor.execute(is_view_query).fetchone()
+ is_view = is_view_res is not None and is_view_res[0] is True
-def redshift_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: Optional[Any],
- chunk_size_override: Optional[int] = None,
- team_id: Optional[int] = None,
- incremental_field: Optional[str] = None,
- incremental_field_type: Optional[IncrementalFieldType] = None,
-) -> SourceResponse:
- table_name = table_names[0]
- if not table_name:
- raise ValueError("Table name is missing")
-
- with tunnel() as (host, port):
- with psycopg.connect(
- host=host,
- port=port,
- dbname=database,
- user=user,
- password=password,
- sslmode="require",
- connect_timeout=15,
- sslrootcert="/tmp/no.txt",
- sslcert="/tmp/no.txt",
- sslkey="/tmp/no.txt",
- options="-c client_encoding=UTF8",
- ) as connection:
+ query = sql.SQL("""
+ SELECT
+ column_name,
+ data_type,
+ is_nullable,
+ numeric_precision,
+ numeric_scale
+ FROM
+ information_schema.columns
+ WHERE
+ table_schema = {schema}
+ AND table_name = {table}""").format(schema=sql.Literal(schema), table=sql.Literal(table_name))
+
+ if logger is not None:
+ _explain_query(cursor, query, logger)
+ logger.debug(f"Running query: {query.as_string()}")
+ cursor.execute(query)
+
+ 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
+ else:
+ numeric_precision = None
+ numeric_scale = None
+
+ columns.append(
+ RedshiftColumn(
+ name=name,
+ data_type=data_type,
+ nullable=nullable == "YES",
+ numeric_precision=numeric_precision,
+ numeric_scale=numeric_scale,
+ )
+ )
+
+ table_type: Literal["view", "table"] = "view" if is_view else "table"
+ return Table(name=table_name, parents=(schema,), columns=columns, type=table_type)
+
+ def get_rows_to_sync(
+ self,
+ cursor: psycopg.Cursor,
+ inner_query: Any,
+ inner_query_args: Any,
+ logger: FilteringBoundLogger,
+ ) -> int:
+ """Count the rows the given `inner_query` will produce.
+
+ Overrides the base helper to (1) let `psycopg.errors.QueryCanceled`
+ bubble out so `build_pipeline` can promote it to
+ `QueryTimeoutException`, and (2) promote Redshift's
+ `temporary file size exceeds temp_file_limit` to
+ `TemporaryFileSizeExceedsLimitException` — both are listed in
+ `get_non_retryable_errors` and need to escape the base's catch-all
+ `except Exception` that otherwise returns 0.
+ """
+ try:
+ query = sql.SQL("SELECT COUNT(*) FROM ({}) as t").format(inner_query)
+ cursor.execute(query)
+ row = cursor.fetchone()
+ if row is None:
+ return 0
+ return int(row[0] or 0)
+ except psycopg.errors.QueryCanceled:
+ raise
+ 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)
+ if "temporary file size exceeds temp_file_limit" in str(e):
+ raise TemporaryFileSizeExceedsLimitException(
+ f"Error: {e}. Please ensure your incremental field is set as a SORTKEY on the table"
+ )
+ return 0
+
+ def fetch_table_stats(
+ self,
+ cursor: psycopg.Cursor,
+ schema: str,
+ table_name: str,
+ logger: FilteringBoundLogger,
+ ) -> TableStats | None:
+ """Return `size` (in MB) and `tbl_rows` from `svv_table_info`.
+
+ `size` is reported in megabytes by Redshift's system table —
+ converted to bytes here so the shared `get_partition_settings`
+ math operates on a single unit. Returns None when either value
+ is missing or zero so the base falls back to no partitioning.
+ """
+ query = sql.SQL("""
+ SELECT size, tbl_rows
+ FROM svv_table_info
+ WHERE schema = {schema} AND "table" = {table}
+ """).format(schema=sql.Literal(schema), table=sql.Literal(table_name))
+
+ try:
+ _explain_query(cursor, query, logger)
+ logger.debug(f"Running query: {query.as_string()}")
+ cursor.execute(query)
+ result = cursor.fetchone()
+ except psycopg.errors.QueryCanceled:
+ raise
+ except Exception as e:
+ capture_exception(e)
+ logger.debug(f"fetch_table_stats: returning None due to error: {e}")
+ return None
+
+ if result is None:
+ logger.debug("fetch_table_stats: no results returning None")
+ return None
+
+ size_mb, tbl_rows = result
+ if size_mb is None or tbl_rows is None or size_mb == 0 or tbl_rows == 0:
+ logger.debug("fetch_table_stats: missing or zero size/rows, returning None")
+ return None
+
+ return TableStats(table_size_bytes=int(size_mb) * 1024 * 1024, row_count=int(tbl_rows))
+
+ def fetch_average_row_size(
+ self,
+ cursor: psycopg.Cursor,
+ schema: str,
+ table_name: str,
+ inner_query: Any,
+ inner_query_args: Any,
+ logger: FilteringBoundLogger,
+ ) -> int | None:
+ """Sample the 95th percentile of `pg_column_size(t)` across the filtered query.
+
+ `inner_query` is a `psycopg.sql.Composed` whose literals are
+ already bound — no separate `inner_query_args` is interpolated
+ here, mirroring how the rest of the Redshift driver builds
+ queries.
+ """
+ try:
+ query = sql.SQL("""
+ SELECT percentile_cont(0.95) within group (order by subquery.row_size) FROM (
+ SELECT pg_column_size(t) as row_size FROM ({}) as t
+ ) as subquery
+ """).format(inner_query)
+
+ _explain_query(cursor, query, logger)
+ logger.debug(f"Running query: {query.as_string()}")
+ cursor.execute(query)
+ row = cursor.fetchone()
+
+ if row is None or row[0] is None:
+ logger.debug("fetch_average_row_size: no results returning None")
+ return None
+
+ return int(row[0] or 1)
+ except psycopg.errors.QueryCanceled:
+ raise
+ 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: RedshiftSourceConfig,
+ inputs: SourceInputs,
+ *,
+ chunk_size_override: int | None = None,
+ ) -> SourceResponse:
+ # `chunk_size_override` is sourced from
+ # `ExternalDataSchema.sync_type_config` by the caller
+ # (`RedshiftSource.source_for_pipeline`) — keeping the ORM
+ # lookup at the source layer lets the driver stay free of
+ # Django model imports.
+ 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:
logger.debug("Getting table types...")
- table = _get_table(cursor, schema, table_name, logger)
+ table = self.get_table_metadata(cursor, schema, table_name, logger)
logger.debug(f"Source schema: {table.to_arrow_schema()}")
inner_query_with_limit = _build_query(
@@ -744,7 +780,7 @@ def redshift_source(
)
try:
logger.debug("Getting primary keys...")
- primary_keys = _get_primary_keys(cursor, schema, table_name, logger)
+ primary_keys = self.get_primary_keys_for_table(cursor, schema, table_name, logger)
if primary_keys:
logger.debug(f"Found primary keys: {primary_keys}")
logger.debug("Getting table chunk size...")
@@ -752,23 +788,33 @@ def redshift_source(
chunk_size = chunk_size_override
logger.debug(f"Using chunk_size_override: {chunk_size_override}")
else:
- chunk_size = _get_table_chunk_size(cursor, inner_query_with_limit, logger)
+ # `inner_query_with_limit` is a `psycopg.sql.Composed`
+ # rather than a `str`; the override on
+ # `fetch_average_row_size` accepts it via `Any`.
+ chunk_size = self.get_chunk_size(
+ cursor,
+ schema,
+ table_name,
+ inner_query_with_limit, # type: ignore[arg-type]
+ None,
+ logger,
+ )
logger.debug("Getting rows to sync...")
- rows_to_sync = _get_rows_to_sync(cursor, inner_query_without_limit, logger)
+ rows_to_sync = self.get_rows_to_sync(cursor, inner_query_without_limit, None, logger)
logger.debug("Getting partition settings...")
partition_settings = (
- _get_partition_settings(cursor, schema, table_name, logger)
+ self.get_partition_settings(cursor, schema, table_name, logger)
if should_use_incremental_field
else None
)
- has_duplicate_primary_keys = False
+ duplicate_primary_keys = False
# Fallback on checking for an `id` field on the table
if primary_keys is None and "id" in table:
logger.debug("Falling back to ['id'] for primary keys...")
primary_keys = ["id"]
logger.debug("Checking duplicate primary keys...")
- has_duplicate_primary_keys = _has_duplicate_primary_keys(
+ duplicate_primary_keys = self.has_duplicate_primary_keys(
cursor, schema, table_name, primary_keys, logger
)
except psycopg.errors.QueryCanceled:
@@ -778,29 +824,11 @@ def redshift_source(
)
raise
- def get_rows(chunk_size: int) -> Iterator[Any]:
- arrow_schema = table.to_arrow_schema()
- with tunnel() as (host, port):
-
- def get_connection():
- connection = psycopg.connect(
- host=host,
- port=port,
- dbname=database,
- user=user,
- password=password,
- sslmode="require",
- connect_timeout=15,
- sslrootcert="/tmp/no.txt",
- sslcert="/tmp/no.txt",
- sslkey="/tmp/no.txt",
- options="-c client_encoding=UTF8",
- )
- connection.adapters.register_loader("json", JsonAsStringLoader)
- return connection
-
- with get_connection() as connection:
- with connection.cursor() as cursor:
+ def get_rows() -> Iterator[Any]:
+ arrow_schema = table.to_arrow_schema()
+ with self.connect(config) as streaming_connection:
+ streaming_connection.adapters.register_loader("json", JsonAsStringLoader)
+ with streaming_connection.cursor() as cursor:
query = _build_query(
schema,
table_name,
@@ -823,14 +851,14 @@ def redshift_source(
yield table_from_iterator((dict(zip(column_names, row)) for row in rows), arrow_schema)
- name = NamingConvention.normalize_identifier(table_name)
-
- return SourceResponse(
- name=name,
- items=lambda: get_rows(chunk_size),
- 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,
- has_duplicate_primary_keys=has_duplicate_primary_keys,
- )
+ 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,
+ has_duplicate_primary_keys=duplicate_primary_keys,
+ )
diff --git a/posthog/temporal/data_imports/sources/redshift/source.py b/posthog/temporal/data_imports/sources/redshift/source.py
index 96fed9d76830..1885c48b37c6 100644
--- a/posthog/temporal/data_imports/sources/redshift/source.py
+++ b/posthog/temporal/data_imports/sources/redshift/source.py
@@ -1,6 +1,5 @@
from typing import Optional, cast
-import structlog
from psycopg import OperationalError
from sshtunnel import BaseSSHTunnelForwarderError
@@ -14,22 +13,17 @@ 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 RedshiftSourceConfig
-from posthog.temporal.data_imports.sources.redshift.redshift import (
- filter_redshift_incremental_fields,
- get_leading_sortkey_columns_for_schemas as get_redshift_leading_sortkey_columns_for_schemas,
- get_primary_keys_for_schemas as get_redshift_primary_keys_for_schemas,
- get_redshift_row_count,
- get_schemas as get_redshift_schemas,
- redshift_source,
-)
+from posthog.temporal.data_imports.sources.redshift.redshift import RedshiftImplementation
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
-from products.data_warehouse.backend.types import ExternalDataSourceType, IncrementalField
+_REDSHIFT_IMPLEMENTATION = RedshiftImplementation()
RedshiftErrors = {
"password authentication failed for user": "Invalid user or password",
@@ -43,11 +37,15 @@ RedshiftErrors = {
@SourceRegistry.register
-class RedshiftSource(SimpleSource[RedshiftSourceConfig], SSHTunnelMixin, ValidateDatabaseHostMixin):
+class RedshiftSource(SQLSource[RedshiftSourceConfig], SSHTunnelMixin, ValidateDatabaseHostMixin):
def __init__(self, source_name: str = "Redshift"):
super().__init__()
self.source_name = source_name
+ @property
+ def get_implementation(self) -> RedshiftImplementation:
+ return _REDSHIFT_IMPLEMENTATION
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.REDSHIFT
@@ -126,6 +124,7 @@ class RedshiftSource(SimpleSource[RedshiftSourceConfig], SSHTunnelMixin, Validat
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
+ **self.default_non_retryable_errors(),
"NoSuchTableError": None,
"is not permitted to log in": None,
"could not translate host name": None,
@@ -144,100 +143,8 @@ class RedshiftSource(SimpleSource[RedshiftSourceConfig], SSHTunnelMixin, Validat
"password authentication failed connection": None,
"connection timeout expired": None,
"Connection refused": None,
- # Raised from the shared `_evolve_pyarrow_schema` in `pipelines/pipeline/utils.py`
- # when an integer column's source type was widened (e.g. `INTEGER` → `BIGINT`)
- # after the destination table was created with the narrower type. Delta Lake can't
- # widen an existing column in place, so retrying won't help — the table must be
- # reset and fully re-synced to adopt the new type.
- "Source column type changed": "A column's type changed in your source database (for example an integer column was widened to bigint) and no longer fits the type we stored. We can't widen an existing column in place — please reset and fully re-sync this table to adopt the new type.",
}
- def get_schemas(
- self,
- config: RedshiftSourceConfig,
- 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_redshift_schemas(
- host=host,
- port=port,
- user=config.user,
- password=config.password,
- database=config.database,
- schema=config.schema,
- names=names,
- )
- try:
- detected_pks = get_redshift_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 Redshift schemas", exc_info=e)
- detected_pks = {}
-
- indexed_columns_by_table = get_redshift_leading_sortkey_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()),
- )
-
- if with_counts:
- row_counts = get_redshift_row_count(
- host=host,
- port=port,
- user=config.user,
- password=config.password,
- database=config.database,
- schema=config.schema,
- names=names,
- )
- else:
- row_counts = {}
-
- for table_name, columns in db_schemas.items():
- incremental_field_tuples = filter_redshift_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,
- row_count=row_counts.get(table_name, None),
- columns=columns,
- detected_primary_keys=resolve_detected_primary_keys(detected_pks.get(table_name), columns),
- )
- )
-
- return schemas
-
def validate_credentials(
self, config: RedshiftSourceConfig, team_id: int, schema_name: Optional[str] = None
) -> tuple[bool, str | None]:
@@ -274,24 +181,11 @@ class RedshiftSource(SimpleSource[RedshiftSourceConfig], SSHTunnelMixin, Validat
return True, None
def source_for_pipeline(self, config: RedshiftSourceConfig, inputs: SourceInputs) -> SourceResponse:
- from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
-
- ssh_tunnel = self.make_ssh_tunnel_func(config)
-
- schema = ExternalDataSchema.objects.get(id=inputs.schema_id)
-
- return redshift_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,
- chunk_size_override=schema.chunk_size_override,
- team_id=inputs.team_id,
+ # Resolve `chunk_size_override` (stored on
+ # `ExternalDataSchema.sync_type_config`) here so the driver
+ # implementation in `redshift.py` stays free of Django ORM
+ # imports.
+ schema_row = ExternalDataSchema.objects.get(id=inputs.schema_id)
+ return self.get_implementation.build_pipeline(
+ config, inputs, chunk_size_override=schema_row.chunk_size_override
)
diff --git a/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.py b/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.py
new file mode 100644
index 000000000000..ada9346471df
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.py
@@ -0,0 +1,485 @@
+import pytest
+from unittest.mock import MagicMock
+
+from psycopg import sql
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from posthog.temporal.data_imports.pipelines.pipeline.utils import TemporaryFileSizeExceedsLimitException
+from posthog.temporal.data_imports.sources.common.sql import Table, TableStats
+from posthog.temporal.data_imports.sources.generated_configs import RedshiftSourceConfig
+from posthog.temporal.data_imports.sources.redshift.redshift import (
+ RedshiftColumn,
+ RedshiftImplementation,
+ filter_redshift_incremental_fields,
+)
+from posthog.temporal.data_imports.sources.redshift.source import _REDSHIFT_IMPLEMENTATION, RedshiftSource
+
+from products.data_warehouse.backend.types import IncrementalFieldType
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_config(**overrides) -> RedshiftSourceConfig:
+ defaults: dict = {
+ "host": "localhost",
+ "port": 5439,
+ "database": "dev",
+ "user": "u",
+ "password": "p",
+ "schema": "public",
+ }
+ defaults.update(overrides)
+ return RedshiftSourceConfig.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 TestFilterIncrementalFields:
+ @pytest.mark.parametrize(
+ "data_type,expected_type",
+ [
+ ("timestamp", IncrementalFieldType.Timestamp),
+ ("timestamp without time zone", IncrementalFieldType.Timestamp),
+ ("timestamp with time zone", IncrementalFieldType.Timestamp),
+ ("date", IncrementalFieldType.Date),
+ ("integer", IncrementalFieldType.Integer),
+ ("bigint", IncrementalFieldType.Integer),
+ ("smallint", IncrementalFieldType.Integer),
+ ("int4", IncrementalFieldType.Integer),
+ ("int8", IncrementalFieldType.Integer),
+ ],
+ )
+ def test_includes_incremental_types(self, data_type, expected_type):
+ result = filter_redshift_incremental_fields([("col", data_type, True)])
+ assert result == [("col", expected_type, True)]
+
+ @pytest.mark.parametrize("data_type", ["varchar", "text", "json", "super", "real"])
+ def test_excludes_non_incremental_types(self, data_type):
+ result = filter_redshift_incremental_fields([("col", data_type, True)])
+ assert result == []
+
+
+class TestRedshiftColumnToArrowField:
+ def test_decimal_requires_precision(self):
+ col = RedshiftColumn(name="x", data_type="decimal", nullable=True)
+ with pytest.raises(TypeError, match="numeric_precision"):
+ col.to_arrow_field()
+
+ def test_bigint_maps_to_int64(self):
+ col = RedshiftColumn(name="x", data_type="bigint", nullable=False)
+ field = col.to_arrow_field()
+ assert "int64" in str(field.type)
+ assert field.nullable is False
+
+ def test_timestamptz_carries_utc_timezone(self):
+ col = RedshiftColumn(name="x", data_type="timestamptz", nullable=True)
+ field = col.to_arrow_field()
+ assert "UTC" in str(field.type)
+
+
+# ---------------------------------------------------------------------------
+# Per-cursor metadata queries — exercise impl methods directly
+# ---------------------------------------------------------------------------
+
+
+def impl() -> RedshiftImplementation:
+ return RedshiftImplementation()
+
+
+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, "public", "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, "public", "t") == ["id", "email"]
+
+
+class TestGetTableMetadata:
+ def test_builds_table_with_columns(self, impl, cursor):
+ cursor.execute.return_value = cursor
+ # First fetchone for is-view check; iteration for columns
+ cursor.fetchone.return_value = (False,)
+ cursor.__iter__.return_value = iter(
+ [
+ ("id", "integer", "NO", None, None),
+ ("email", "varchar", "YES", None, None),
+ ]
+ )
+ table = impl.get_table_metadata(cursor, "public", "users")
+ assert table.name == "users"
+ assert table.parents == ("public",)
+ assert len(table.columns) == 2
+ assert table.type == "table"
+
+ def test_marks_view_when_is_view_true(self, impl, cursor):
+ cursor.execute.return_value = cursor
+ cursor.fetchone.return_value = (True,)
+ cursor.__iter__.return_value = iter([("id", "integer", "NO", None, None)])
+ table = impl.get_table_metadata(cursor, "public", "myview")
+ assert table.type == "view"
+
+ def test_populates_numeric_precision_and_scale_for_decimals(self, impl, cursor):
+ cursor.execute.return_value = cursor
+ cursor.fetchone.return_value = (False,)
+ cursor.__iter__.return_value = iter(
+ [
+ ("amount", "decimal", "NO", 10, 2),
+ ]
+ )
+ table = impl.get_table_metadata(cursor, "public", "orders")
+ assert table.columns[0].numeric_precision == 10
+ assert table.columns[0].numeric_scale == 2
+
+
+class TestGetRowsToSync:
+ def _inner(self):
+ return sql.SQL("SELECT 1").format()
+
+ def test_returns_count_from_row(self, impl, cursor, logger):
+ cursor.fetchone.return_value = (123,)
+ result = impl.get_rows_to_sync(cursor, self._inner(), None, logger)
+ assert result == 123
+
+ def test_returns_zero_on_none_row(self, impl, cursor, logger):
+ cursor.fetchone.return_value = None
+ assert impl.get_rows_to_sync(cursor, self._inner(), None, logger) == 0
+
+ def test_returns_zero_on_generic_exception(self, impl, cursor, logger):
+ cursor.execute.side_effect = RuntimeError("boom")
+ assert impl.get_rows_to_sync(cursor, self._inner(), None, logger) == 0
+
+ def test_raises_on_temp_file_limit(self, impl, cursor, logger):
+ cursor.execute.side_effect = RuntimeError("temporary file size exceeds temp_file_limit")
+ with pytest.raises(TemporaryFileSizeExceedsLimitException):
+ impl.get_rows_to_sync(cursor, self._inner(), None, logger)
+
+
+class TestFetchTableStats:
+ def test_returns_none_when_no_row(self, impl, cursor, logger):
+ cursor.fetchone.return_value = None
+ assert impl.fetch_table_stats(cursor, "public", "t", logger) is None
+
+ def test_returns_none_when_size_zero(self, impl, cursor, logger):
+ cursor.fetchone.return_value = (0, 100)
+ assert impl.fetch_table_stats(cursor, "public", "t", logger) is None
+
+ def test_returns_none_when_rows_zero(self, impl, cursor, logger):
+ cursor.fetchone.return_value = (10, 0)
+ assert impl.fetch_table_stats(cursor, "public", "t", logger) is None
+
+ def test_converts_size_mb_to_bytes(self, impl, cursor, logger):
+ cursor.fetchone.return_value = (2, 100) # 2 MB, 100 rows
+ stats = impl.fetch_table_stats(cursor, "public", "t", logger)
+ assert stats == TableStats(table_size_bytes=2 * 1024 * 1024, row_count=100)
+
+ def test_returns_none_on_exception(self, impl, cursor, logger):
+ cursor.execute.side_effect = RuntimeError("boom")
+ assert impl.fetch_table_stats(cursor, "public", "t", logger) is None
+
+
+class TestFetchAverageRowSize:
+ def _inner(self):
+ return sql.SQL("SELECT 1").format()
+
+ def test_returns_none_when_no_row(self, impl, cursor, logger):
+ cursor.fetchone.return_value = None
+ assert impl.fetch_average_row_size(cursor, "public", "t", self._inner(), None, logger) is None
+
+ def test_returns_none_when_row_value_is_none(self, impl, cursor, logger):
+ cursor.fetchone.return_value = (None,)
+ assert impl.fetch_average_row_size(cursor, "public", "t", self._inner(), None, logger) is None
+
+ def test_returns_row_size_bytes(self, impl, cursor, logger):
+ cursor.fetchone.return_value = (256.4,)
+ result = impl.fetch_average_row_size(cursor, "public", "t", self._inner(), None, logger)
+ assert result == 256
+
+ def test_returns_none_on_exception(self, impl, cursor, logger):
+ cursor.execute.side_effect = [None, RuntimeError("boom")]
+ assert impl.fetch_average_row_size(cursor, "public", "t", self._inner(), None, logger) is None
+
+
+class TestHasDuplicatePrimaryKeys:
+ def test_returns_false_when_no_pks(self, impl, cursor, logger):
+ assert impl.has_duplicate_primary_keys(cursor, "public", "t", None, logger) is False
+ assert impl.has_duplicate_primary_keys(cursor, "public", "t", [], logger) is False
+
+ def test_returns_true_when_row_found(self, impl, cursor, logger):
+ cursor.fetchone.return_value = (1,)
+ assert impl.has_duplicate_primary_keys(cursor, "public", "t", ["id"], logger) is True
+
+ def test_returns_false_when_no_row(self, impl, cursor, logger):
+ cursor.fetchone.return_value = None
+ assert impl.has_duplicate_primary_keys(cursor, "public", "t", ["id"], logger) is False
+
+ def test_returns_false_on_exception(self, impl, cursor, logger):
+ cursor.execute.side_effect = RuntimeError("boom")
+ assert impl.has_duplicate_primary_keys(cursor, "public", "t", ["id"], logger) is False
+
+
+# ---------------------------------------------------------------------------
+# Listing — exercise impl methods that take a real cursor mock
+# ---------------------------------------------------------------------------
+
+
+class TestGetColumns:
+ def test_returns_columns_grouped_by_table(self, impl):
+ conn = MagicMock()
+ cur = MagicMock()
+ cur.__enter__.return_value = cur
+ cur.fetchall.return_value = [
+ ("users", "id", "integer", "NO"),
+ ("users", "email", "varchar", "YES"),
+ ("orders", "id", "bigint", "NO"),
+ ]
+ conn.cursor.return_value = cur
+
+ result = impl.get_columns(conn, _make_config(), names=None)
+
+ assert result == {
+ "users": [("id", "integer", False), ("email", "varchar", True)],
+ "orders": [("id", "bigint", False)],
+ }
+
+ def 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
+
+ assert impl.get_columns(conn, _make_config(), names=["foo"]) == {}
+
+
+class TestGetPrimaryKeys:
+ def test_returns_empty_for_no_tables(self, impl):
+ result = impl.get_primary_keys(MagicMock(), _make_config(), [])
+ assert result == {}
+
+ def test_returns_pk_columns_grouped_by_table(self, impl):
+ conn = MagicMock()
+ cur = MagicMock()
+ cur.__enter__.return_value = cur
+ cur.fetchall.return_value = [("users", "id"), ("users", "tenant_id"), ("orders", "id")]
+ conn.cursor.return_value = cur
+
+ result = impl.get_primary_keys(conn, _make_config(), ["users", "orders", "items"])
+ assert result == {"users": ["id", "tenant_id"], "orders": ["id"], "items": None}
+
+ def test_swallows_errors_and_returns_none_per_table(self, impl):
+ conn = MagicMock()
+ cur = MagicMock()
+ cur.__enter__.return_value = cur
+ cur.execute.side_effect = Exception("denied")
+ conn.cursor.return_value = cur
+
+ result = impl.get_primary_keys(conn, _make_config(), ["users"])
+ assert result == {"users": None}
+
+
+class TestGetLeadingIndexColumns:
+ def _make_conn(self, rows):
+ conn = MagicMock()
+ cur = MagicMock()
+ cur.__enter__.return_value = cur
+ cur.fetchall.return_value = rows
+ conn.cursor.return_value = cur
+ return conn
+
+ def test_returns_empty_for_no_tables(self, impl):
+ assert impl.get_leading_index_columns(MagicMock(), _make_config(), []) == {}
+
+ def test_returns_leading_compound_sortkey(self, impl):
+ # tablename, column, sortkey
+ conn = self._make_conn(
+ [
+ ("messages", "created_at", 1),
+ ("messages", "user_id", 2),
+ ]
+ )
+ result = impl.get_leading_index_columns(conn, _make_config(), ["messages"])
+ assert result == {"messages": {"created_at"}}
+
+ def test_treats_interleaved_sortkey_as_indexed(self, impl):
+ conn = self._make_conn(
+ [
+ ("messages", "a", -1),
+ ("messages", "b", 2),
+ ("messages", "c", -3),
+ ]
+ )
+ result = impl.get_leading_index_columns(conn, _make_config(), ["messages"])
+ assert result == {"messages": {"a", "b", "c"}}
+
+ def test_tables_with_no_sortkey_are_empty(self, impl):
+ conn = self._make_conn([])
+ result = impl.get_leading_index_columns(conn, _make_config(), ["messages", "logs"])
+ assert result == {"messages": set(), "logs": set()}
+
+ def test_returns_none_on_exception(self, impl):
+ conn = MagicMock()
+ cur = MagicMock()
+ cur.__enter__.return_value = cur
+ cur.execute.side_effect = Exception("denied")
+ conn.cursor.return_value = cur
+ assert impl.get_leading_index_columns(conn, _make_config(), ["t"]) is None
+
+
+# ---------------------------------------------------------------------------
+# Source wiring — singleton + get_implementation + non-retryable errors
+# ---------------------------------------------------------------------------
+
+
+class TestRedshiftSourceWiring:
+ def test_get_implementation_returns_singleton(self):
+ source = RedshiftSource()
+ assert source.get_implementation is _REDSHIFT_IMPLEMENTATION
+
+
+class TestRedshiftSourceNonRetryableErrors:
+ @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, error_msg):
+ non_retryable = RedshiftSource().get_non_retryable_errors()
+ is_non_retryable = any(pattern in error_msg for pattern in non_retryable.keys())
+ assert is_non_retryable
+
+
+class TestRedshiftSourceForPipeline:
+ def test_forwards_chunk_size_override_from_external_data_schema(self, mocker):
+ schema_row = MagicMock()
+ schema_row.chunk_size_override = 9999
+ mocker.patch(
+ "posthog.temporal.data_imports.sources.redshift.source.ExternalDataSchema.objects.get",
+ return_value=schema_row,
+ )
+ build_pipeline = mocker.patch.object(RedshiftImplementation, "build_pipeline", return_value=MagicMock())
+
+ source = RedshiftSource()
+ config = _make_config()
+ inputs = _make_inputs()
+ source.source_for_pipeline(config, inputs)
+
+ build_pipeline.assert_called_once_with(config, inputs, chunk_size_override=9999)
+
+
+# ---------------------------------------------------------------------------
+# End-to-end build_pipeline — wired through RedshiftImplementation
+# ---------------------------------------------------------------------------
+
+
+def build_pipeline_mocks(mocker):
+ """Patch psycopg.connect + per-cursor metadata methods on RedshiftImplementation
+ so `build_pipeline` can run end-to-end without a real Redshift server.
+ """
+ fake_table = Table(
+ name="messages",
+ parents=("public",),
+ columns=[RedshiftColumn(name="id", data_type="integer", nullable=False)],
+ type="table",
+ )
+
+ mocker.patch.object(RedshiftImplementation, "get_table_metadata", return_value=fake_table)
+ mocker.patch.object(RedshiftImplementation, "get_primary_keys_for_table", return_value=["id"])
+ mocker.patch.object(RedshiftImplementation, "get_rows_to_sync", return_value=0)
+ mocker.patch.object(RedshiftImplementation, "get_chunk_size", return_value=1000)
+ mocker.patch.object(RedshiftImplementation, "get_partition_settings", return_value=None)
+ mocker.patch.object(RedshiftImplementation, "has_duplicate_primary_keys", return_value=False)
+
+ streaming_cursor = MagicMock()
+ streaming_cursor.__enter__.return_value = streaming_cursor
+ streaming_cursor.description = [MagicMock(name="id")]
+ streaming_cursor.description[0].name = "id"
+ streaming_cursor.fetchmany.return_value = []
+
+ # The metadata pass uses the patched `RedshiftImplementation`
+ # methods, so a single cursor mock can serve both connections —
+ # only the streaming connection requires `conn.adapters` to be set.
+ state = {"first_conn": True}
+
+ def connect_side_effect(*args, **kwargs):
+ conn = MagicMock()
+ conn.__enter__.return_value = conn
+ conn.cursor.return_value = streaming_cursor
+ if not state["first_conn"]:
+ conn.adapters = MagicMock()
+ state["first_conn"] = False
+ return conn
+
+ mock_connect = mocker.patch(
+ "posthog.temporal.data_imports.sources.redshift.redshift.psycopg.connect",
+ side_effect=connect_side_effect,
+ )
+ return mock_connect, streaming_cursor
+
+
+class TestBuildPipeline:
+ def test_returns_source_response(self, build_pipeline_mocks):
+ mock_connect, _ = build_pipeline_mocks
+ impl = RedshiftImplementation()
+ response = impl.build_pipeline(_make_config(), _make_inputs())
+ assert response.name == "messages"
+ assert response.primary_keys == ["id"]
+ # psycopg.connect was called at least once for the metadata pass
+ assert mock_connect.called
+
+ def test_streaming_drains_without_error(self, build_pipeline_mocks):
+ _, streaming_cursor = build_pipeline_mocks
+ impl = RedshiftImplementation()
+ response = impl.build_pipeline(_make_config(), _make_inputs())
+ list(response.items()) # type: ignore[arg-type]
+ # streaming cursor.execute should have been invoked for the streaming query
+ assert streaming_cursor.execute.called
+
+ def test_chunk_size_override_skips_probe(self, build_pipeline_mocks, mocker):
+ mocked_chunk_size = mocker.patch.object(RedshiftImplementation, "get_chunk_size")
+ impl = RedshiftImplementation()
+ impl.build_pipeline(_make_config(), _make_inputs(), chunk_size_override=4242)
+ mocked_chunk_size.assert_not_called()