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 postgres to SQLSourceImplementation (#59700)

Daniel RCd9e53ae09d53
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.py
index ff809ee99363..6dbbfa263be1 100644
--- a/posthog/temporal/data_imports/sources/postgres/postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py
@@ -29,7 +29,7 @@ from posthog.temporal.data_imports.pipelines.helpers import (
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,
@@ -40,7 +40,11 @@ from posthog.temporal.data_imports.pipelines.pipeline.utils import (
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 posthog.temporal.data_imports.sources.common.sql.implementation import SQLSourceImplementation
+from posthog.temporal.data_imports.sources.common.sql.incremental import IncrementalFieldFilter
+from posthog.temporal.data_imports.sources.generated_configs import PostgresSourceConfig
from posthog.temporal.data_imports.sources.postgres.partitioned_tables import (
build_partition_query,
get_estimated_row_count_for_partitioned_table as _get_estimated_row_count_for_partitioned_table,
@@ -413,6 +417,41 @@ def _get_discovered_tables(
return {name: all_tables[name] for name in names if name in all_tables}, qualify_with_schema
+def _row_counts_from_conn(
+ connection: psycopg.Connection,
+ schema: str | None,
+ names: list[str] | None,
+) -> dict[str, int]:
+ if _normalize_selected_schema(schema) is None and not names:
+ return {}
+ try:
+ with connection.cursor() as cursor:
+ cursor.execute(
+ sql.SQL("SET LOCAL statement_timeout = {timeout}").format(
+ timeout=sql.Literal(1000 * 30) # 30 secs
+ )
+ )
+ discovered_tables, _qualify_with_schema = _get_discovered_tables(cursor, schema, names)
+ if not discovered_tables:
+ return {}
+
+ counts = [
+ sql.SQL("SELECT {table_name} AS table_name, COUNT(*) AS row_count FROM {schema}.{table}").format(
+ table_name=sql.Literal(display_name),
+ schema=sql.Identifier(schema_name),
+ table=sql.Identifier(table_name),
+ )
+ for display_name, (_source_catalog, schema_name, table_name) in discovered_tables.items()
+ ]
+
+ union_counts = sql.SQL(" UNION ALL ").join(counts)
+ cursor.execute(union_counts)
+ row_count_result = cursor.fetchall()
+ return {row[0]: row[1] for row in row_count_result}
+ except:
+ return {}
+
+
def get_postgres_row_count(
host: str,
port: int,
@@ -429,33 +468,84 @@ def get_postgres_row_count(
with pg_connection(
host=host, port=port, database=database, user=user, password=password, require_ssl=require_ssl
) as connection:
- with connection.cursor() as cursor:
- cursor.execute(
- sql.SQL("SET LOCAL statement_timeout = {timeout}").format(
- timeout=sql.Literal(1000 * 30) # 30 secs
- )
- )
- discovered_tables, _qualify_with_schema = _get_discovered_tables(cursor, schema, names)
- if not discovered_tables:
- return {}
-
- counts = [
- sql.SQL("SELECT {table_name} AS table_name, COUNT(*) AS row_count FROM {schema}.{table}").format(
- table_name=sql.Literal(display_name),
- schema=sql.Identifier(schema_name),
- table=sql.Identifier(table_name),
- )
- for display_name, (_source_catalog, schema_name, table_name) in discovered_tables.items()
- ]
-
- union_counts = sql.SQL(" UNION ALL ").join(counts)
- cursor.execute(union_counts)
- row_count_result = cursor.fetchall()
- return {row[0]: row[1] for row in row_count_result}
+ return _row_counts_from_conn(connection, schema, names)
except:
return {}
+def _schemas_from_conn(
+ connection: psycopg.Connection,
+ schema: str | None,
+ names: list[str] | None,
+) -> dict[str, PostgresDiscoveredSchema]:
+ """Discover columns for tables on the given pre-opened connection."""
+ with connection.cursor() as cursor:
+ discovered_tables, _qualify_with_schema = _get_discovered_tables(cursor, schema, names)
+ if not discovered_tables:
+ return {}
+
+ source_schemas = sorted(
+ {schema_name for _table_catalog, schema_name, _table_name in discovered_tables.values()}
+ )
+ schema_placeholders, schema_params = _build_named_value_placeholders("schema", source_schemas)
+
+ cursor.execute(
+ f"""
+ SELECT * FROM (
+ SELECT
+ table_schema,
+ table_name,
+ column_name,
+ data_type,
+ is_nullable,
+ ordinal_position
+ FROM information_schema.columns
+ WHERE table_schema IN ({schema_placeholders})
+ UNION ALL
+ SELECT
+ n.nspname AS table_schema,
+ c.relname AS table_name,
+ a.attname AS column_name,
+ pg_catalog.format_type(a.atttypid, a.atttypmod) AS data_type,
+ CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END AS is_nullable,
+ a.attnum AS ordinal_position
+ FROM pg_class c
+ JOIN pg_namespace n ON c.relnamespace = n.oid
+ JOIN pg_attribute a ON a.attrelid = c.oid
+ WHERE c.relkind = 'm'
+ AND n.nspname IN ({schema_placeholders})
+ AND a.attnum > 0
+ AND NOT a.attisdropped
+ ) t
+ ORDER BY table_schema ASC, table_name ASC, ordinal_position ASC
+ """,
+ schema_params,
+ )
+ result = cursor.fetchall()
+
+ columns_by_table: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)
+ discovered_pairs_by_schema_and_table = {
+ (schema_name, table_name): display_name
+ for display_name, (_source_catalog, schema_name, table_name) in discovered_tables.items()
+ }
+ for table_schema, table_name, column_name, data_type, is_nullable, _ordinal_position in result:
+ display_name = discovered_pairs_by_schema_and_table.get((table_schema, table_name))
+ if display_name is None:
+ continue
+
+ columns_by_table[display_name].append((column_name, data_type, is_nullable == "YES"))
+
+ return {
+ display_name: PostgresDiscoveredSchema(
+ source_catalog=source_catalog,
+ source_schema=schema_name,
+ source_table_name=table_name,
+ columns=columns_by_table.get(display_name, []),
+ )
+ for display_name, (source_catalog, schema_name, table_name) in discovered_tables.items()
+ }
+
+
def get_schemas(
host: str,
database: str,
@@ -467,75 +557,10 @@ def get_schemas(
names: list[str] | None = None,
) -> dict[str, PostgresDiscoveredSchema]:
"""Get all tables from PostgreSQL source schemas to sync."""
-
with pg_connection(
host=host, port=port, database=database, user=user, password=password, require_ssl=require_ssl
) as connection:
- with connection.cursor() as cursor:
- discovered_tables, _qualify_with_schema = _get_discovered_tables(cursor, schema, names)
- if not discovered_tables:
- return {}
-
- source_schemas = sorted(
- {schema_name for _table_catalog, schema_name, _table_name in discovered_tables.values()}
- )
- schema_placeholders, schema_params = _build_named_value_placeholders("schema", source_schemas)
-
- cursor.execute(
- f"""
- SELECT * FROM (
- SELECT
- table_schema,
- table_name,
- column_name,
- data_type,
- is_nullable,
- ordinal_position
- FROM information_schema.columns
- WHERE table_schema IN ({schema_placeholders})
- UNION ALL
- SELECT
- n.nspname AS table_schema,
- c.relname AS table_name,
- a.attname AS column_name,
- pg_catalog.format_type(a.atttypid, a.atttypmod) AS data_type,
- CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END AS is_nullable,
- a.attnum AS ordinal_position
- FROM pg_class c
- JOIN pg_namespace n ON c.relnamespace = n.oid
- JOIN pg_attribute a ON a.attrelid = c.oid
- WHERE c.relkind = 'm'
- AND n.nspname IN ({schema_placeholders})
- AND a.attnum > 0
- AND NOT a.attisdropped
- ) t
- ORDER BY table_schema ASC, table_name ASC, ordinal_position ASC
- """,
- schema_params,
- )
- result = cursor.fetchall()
-
- columns_by_table: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)
- discovered_pairs_by_schema_and_table = {
- (schema_name, table_name): display_name
- for display_name, (_source_catalog, schema_name, table_name) in discovered_tables.items()
- }
- for table_schema, table_name, column_name, data_type, is_nullable, _ordinal_position in result:
- display_name = discovered_pairs_by_schema_and_table.get((table_schema, table_name))
- if display_name is None:
- continue
-
- columns_by_table[display_name].append((column_name, data_type, is_nullable == "YES"))
-
- return {
- display_name: PostgresDiscoveredSchema(
- source_catalog=source_catalog,
- source_schema=schema_name,
- source_table_name=table_name,
- columns=columns_by_table.get(display_name, []),
- )
- for display_name, (source_catalog, schema_name, table_name) in discovered_tables.items()
- }
+ return _schemas_from_conn(connection, schema, names)
def get_primary_keys_for_schemas(
@@ -564,6 +589,74 @@ def get_primary_keys_for_schemas(
return result
+def _foreign_keys_from_conn(
+ connection: psycopg.Connection,
+ schema: str | None,
+ names: list[str] | None,
+) -> dict[str, list[tuple[str, str, str]]]:
+ """Discover foreign keys on a pre-opened connection."""
+ with connection.cursor() as cursor:
+ discovered_tables, qualify_with_schema = _get_discovered_tables(cursor, schema, names)
+ if not discovered_tables:
+ return {}
+
+ source_schemas = sorted(
+ {schema_name for _table_catalog, schema_name, _table_name in discovered_tables.values()}
+ )
+ schema_placeholders, schema_params = _build_named_value_placeholders("schema", source_schemas)
+
+ cursor.execute(
+ f"""
+ SELECT
+ tc.table_schema AS source_schema_name,
+ tc.table_name AS table_name,
+ kcu.column_name AS column_name,
+ ccu.table_schema AS target_schema_name,
+ ccu.table_name AS target_table_name,
+ ccu.column_name AS target_column_name
+ FROM information_schema.table_constraints AS tc
+ JOIN information_schema.key_column_usage AS kcu
+ ON tc.constraint_name = kcu.constraint_name
+ AND tc.constraint_schema = kcu.constraint_schema
+ AND tc.table_schema = kcu.table_schema
+ JOIN information_schema.constraint_column_usage AS ccu
+ ON ccu.constraint_name = tc.constraint_name
+ AND ccu.constraint_schema = tc.constraint_schema
+ WHERE tc.constraint_type = 'FOREIGN KEY'
+ AND tc.table_schema IN ({schema_placeholders})
+ ORDER BY tc.table_schema, tc.table_name, kcu.ordinal_position
+ """,
+ schema_params,
+ )
+ result = cursor.fetchall()
+
+ foreign_keys_by_table: dict[str, list[tuple[str, str, str]]] = collections.defaultdict(list)
+ discovered_pairs_by_schema_and_table = {
+ (schema_name, table_name): display_name
+ for display_name, (_source_catalog, schema_name, table_name) in discovered_tables.items()
+ }
+ for (
+ source_schema_name,
+ table_name,
+ column_name,
+ target_schema_name,
+ target_table_name,
+ target_column_name,
+ ) in result:
+ display_name = discovered_pairs_by_schema_and_table.get((source_schema_name, table_name))
+ if display_name is None:
+ continue
+
+ target_display_name = _get_display_table_name(
+ target_schema_name,
+ target_table_name,
+ qualify_with_schema=qualify_with_schema or target_schema_name != source_schema_name,
+ )
+ foreign_keys_by_table[display_name].append((column_name, target_display_name, target_column_name))
+
+ return foreign_keys_by_table
+
+
def get_foreign_keys(
host: str,
database: str,
@@ -575,70 +668,10 @@ def get_foreign_keys(
names: list[str] | None = None,
) -> dict[str, list[tuple[str, str, str]]]:
"""Get foreign keys for tables in the selected PostgreSQL schema."""
-
with pg_connection(
host=host, port=port, database=database, user=user, password=password, require_ssl=require_ssl
) as connection:
- with connection.cursor() as cursor:
- discovered_tables, qualify_with_schema = _get_discovered_tables(cursor, schema, names)
- if not discovered_tables:
- return {}
-
- source_schemas = sorted(
- {schema_name for _table_catalog, schema_name, _table_name in discovered_tables.values()}
- )
- schema_placeholders, schema_params = _build_named_value_placeholders("schema", source_schemas)
-
- cursor.execute(
- f"""
- SELECT
- tc.table_schema AS source_schema_name,
- tc.table_name AS table_name,
- kcu.column_name AS column_name,
- ccu.table_schema AS target_schema_name,
- ccu.table_name AS target_table_name,
- ccu.column_name AS target_column_name
- FROM information_schema.table_constraints AS tc
- JOIN information_schema.key_column_usage AS kcu
- ON tc.constraint_name = kcu.constraint_name
- AND tc.constraint_schema = kcu.constraint_schema
- AND tc.table_schema = kcu.table_schema
- JOIN information_schema.constraint_column_usage AS ccu
- ON ccu.constraint_name = tc.constraint_name
- AND ccu.constraint_schema = tc.constraint_schema
- WHERE tc.constraint_type = 'FOREIGN KEY'
- AND tc.table_schema IN ({schema_placeholders})
- ORDER BY tc.table_schema, tc.table_name, kcu.ordinal_position
- """,
- schema_params,
- )
- result = cursor.fetchall()
-
- foreign_keys_by_table: dict[str, list[tuple[str, str, str]]] = collections.defaultdict(list)
- discovered_pairs_by_schema_and_table = {
- (schema_name, table_name): display_name
- for display_name, (_source_catalog, schema_name, table_name) in discovered_tables.items()
- }
- for (
- source_schema_name,
- table_name,
- column_name,
- target_schema_name,
- target_table_name,
- target_column_name,
- ) in result:
- display_name = discovered_pairs_by_schema_and_table.get((source_schema_name, table_name))
- if display_name is None:
- continue
-
- target_display_name = _get_display_table_name(
- target_schema_name,
- target_table_name,
- qualify_with_schema=qualify_with_schema or target_schema_name != source_schema_name,
- )
- foreign_keys_by_table[display_name].append((column_name, target_display_name, target_column_name))
-
- return foreign_keys_by_table
+ return _foreign_keys_from_conn(connection, schema, names)
def get_connection_metadata(
@@ -1963,3 +1996,68 @@ def postgres_source(
rows_to_sync=rows_to_sync,
has_duplicate_primary_keys=has_duplicate_primary_keys,
)
+
+
+# psycopg's `Cursor.execute` accepts `sql.Composable`/`bytes` in addition to `str`, so it
+# does not satisfy the narrow `_CursorLike(execute(query: str, ...))` protocol on the base.
+# Use `Any` for the cursor type variable.
+class PostgresImplementation(SQLSourceImplementation[PostgresSourceConfig, psycopg.Connection, Any]):
+ """Minimal `SQLSourceImplementation` stub paired with `PostgresSource`.
+
+ `PostgresSource` overrides `get_schemas` and `source_for_pipeline` end to
+ end — multi-schema discovery, `enabled_columns` column selection, CDC
+ dispatch, SSL cutoff, and storage-key naming all live there because none of
+ them fit `SourceInputs` or the base template. This impl only exists to
+ satisfy the `SQLSource` type contract; only the four abstract methods are
+ implemented. A deeper migration that pushes Postgres onto the base template
+ would extend `SourceInputs` and is tracked as future work.
+ """
+
+ @contextmanager
+ def connect(
+ self,
+ config: PostgresSourceConfig,
+ *,
+ require_ssl: bool = False,
+ ) -> Iterator[psycopg.Connection]:
+ """Open a single psycopg connection (through the SSH tunnel if configured)."""
+ with open_ssh_tunnel(config) as (host, port):
+ with pg_connection(
+ host=host,
+ port=port,
+ database=config.database,
+ user=config.user,
+ password=config.password,
+ require_ssl=require_ssl,
+ ) as conn:
+ yield conn
+
+ def get_columns(
+ self,
+ conn: psycopg.Connection,
+ config: PostgresSourceConfig,
+ names: list[str] | None,
+ ) -> dict[str, list[tuple[str, str, bool]]]:
+ discovered = _schemas_from_conn(conn, config.schema, names)
+ return {display_name: discovered_schema.columns for display_name, discovered_schema in discovered.items()}
+
+ def get_incremental_filter(self) -> IncrementalFieldFilter:
+ return filter_postgres_incremental_fields
+
+ def build_pipeline(self, config: PostgresSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ """Postgres syncs go through `PostgresSource.source_for_pipeline`, not this method.
+
+ The production path needs the `ExternalDataSchema` lookup to thread
+ `enabled_columns`, `require_ssl` (derived from `source_requires_ssl`),
+ `is_initial_sync`, `chunk_size_override`, and the multi-schema /
+ CDC-streaming reconciliation into `postgres_source(...)`. None of that is
+ available from `SourceInputs` alone, and silently defaulting `require_ssl`
+ to `False` here would let new (post-cutoff) sources bypass SSL on the base
+ template path. Raise loudly so a refactor that drops the source-level
+ override surfaces immediately rather than going to prod unencrypted.
+ """
+ raise NotImplementedError(
+ "PostgresImplementation.build_pipeline is intentionally not implemented — "
+ "use PostgresSource.source_for_pipeline which forwards require_ssl, "
+ "enabled_columns, chunk_size_override, and CDC reconciliation."
+ )
diff --git a/posthog/temporal/data_imports/sources/postgres/source.py b/posthog/temporal/data_imports/sources/postgres/source.py
index c27dbff4136f..dfa47b78af50 100644
--- a/posthog/temporal/data_imports/sources/postgres/source.py
+++ b/posthog/temporal/data_imports/sources/postgres/source.py
@@ -19,15 +19,17 @@ from posthog.schema import (
from posthog.exceptions_capture import capture_exception
from posthog.temporal.data_imports.naming_convention import NamingConvention
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 PostgresSourceConfig
from posthog.temporal.data_imports.sources.postgres.cdc.config import PostgresCDCConfig
from posthog.temporal.data_imports.sources.postgres.cdc.slot_manager import cdc_pg_connection, drop_slot_and_publication
from posthog.temporal.data_imports.sources.postgres.postgres import (
+ PostgresImplementation,
SSLRequiredError,
filter_postgres_incremental_fields,
get_connection_metadata as get_postgres_connection_metadata,
@@ -55,12 +57,19 @@ PostgresErrors = {
}
+_POSTGRES_IMPLEMENTATION = PostgresImplementation()
+
+
@SourceRegistry.register
-class PostgresSource(SimpleSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDatabaseHostMixin):
+class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDatabaseHostMixin):
def __init__(self, source_name: str = "Postgres"):
super().__init__()
self.source_name = source_name
+ @property
+ def get_implementation(self) -> PostgresImplementation:
+ return _POSTGRES_IMPLEMENTATION
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.POSTGRES
diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
index 84758e45e916..526587a7d80d 100644
--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
@@ -37,6 +37,7 @@ from posthog.temporal.data_imports.sources.postgres.partitioned_tables import (
from posthog.temporal.data_imports.sources.postgres.postgres import (
SSL_REQUIRED_AFTER_DATE,
JsonAsStringLoader,
+ PostgresImplementation,
PostgreSQLColumn,
RangeAsStringLoader,
SafeDateLoader,
@@ -91,6 +92,18 @@ class TestSafeDateLoader:
assert loader.load(input_data) == expected
+class TestPostgresImplementationWiring:
+ def test_source_exposes_postgres_implementation_singleton(self):
+ source = PostgresSource()
+ assert isinstance(source.get_implementation, PostgresImplementation)
+ # Same instance across two PostgresSource constructions — module-level singleton.
+ assert source.get_implementation is PostgresSource().get_implementation
+
+ def test_get_incremental_filter_returns_filter_postgres_incremental_fields(self):
+ impl = PostgresSource().get_implementation
+ assert impl.get_incremental_filter() is filter_postgres_incremental_fields
+
+
class TestPostgresSourceNonRetryableErrors:
@pytest.fixture
def source(self):