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.

feat(data-warehouse): add MotherDuck source (#78833)

Tom Owersbdf5914e0a50
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 4074d1e15756..e6a99d556f60 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -421,6 +421,7 @@ the row lists both.
| monday | HTTP (GraphQL) | requests | ✅ |
| mongodb | DB protocol | pymongo | ➖ |
| monte_carlo | HTTP (GraphQL) | requests | ✅ |
+| motherduck | DB protocol | duckdb (MotherDuck `md:` connection) | ➖ |
| mssql | DB protocol | pyodbc / pymssql | ➖ |
| mux | HTTP | requests | ✅ |
| my_hours | HTTP | requests | ✅ |
@@ -1150,7 +1151,6 @@ doesn't conflict with concurrent PRs.
- moneybird
- mono
- moodle
-- motherduck
- motion
- moxie
- mycase
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/motherduck.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/motherduck.py
index b9bfe02aa276..a7cd01d45cb5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/motherduck.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/motherduck.py
@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class MotherduckSourceConfig(config.Config):
- pass
+ access_token: str
+ database: str
+ schema: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/motherduck.py b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/motherduck.py
new file mode 100644
index 000000000000..e32c5482f358
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/motherduck.py
@@ -0,0 +1,424 @@
+"""MotherDuck driver for PostHog's data-warehouse import pipeline.
+
+MotherDuck is DuckDB served from the cloud, so the client is the ordinary
+`duckdb` package pointed at an `md:<database>` connection string carrying a
+MotherDuck access token. Everything MotherDuck-specific — connection string
+assembly, `information_schema` discovery, and the pipeline build — lives on
+`MotherDuckImplementation`. The source-class `MotherduckSource` is a thin
+PostHog-layer wrapper that holds an instance and validates credentials.
+
+DuckDB runs in-process inside the Temporal worker, so this driver bounds both
+what DuckDB may allocate (`DUCKDB_LOCAL_CONFIG`) and how many rows it
+materializes at once (an Arrow record-batch reader rather than a full fetch).
+"""
+
+from __future__ import annotations
+
+import re
+import collections
+from collections.abc import Iterator
+from contextlib import contextmanager
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import duckdb
+import pyarrow as pa
+import structlog
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import log_connection_open
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import AnsiIdentifierQuoter
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.implementation import (
+ SourceMetadata,
+ SQLSourceImplementation,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.incremental import (
+ IncrementalFieldFilter,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.location import (
+ normalize_namespace,
+ resolve_source_location,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.query_builder import (
+ ParamStyle,
+ SelectQueryBuilder,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.motherduck import (
+ MotherduckSourceConfig,
+)
+from products.warehouse_sources.backend.types import IncrementalFieldType
+
+__all__ = [
+ "MotherDuckImplementation",
+ "build_motherduck_connection_string",
+ "filter_motherduck_incremental_fields",
+]
+
+_IDENTIFIER_QUOTER = AnsiIdentifierQuoter()
+
+# DuckDB binds `?` placeholders positionally from a list.
+_QUERY_BUILDER = SelectQueryBuilder(quoter=_IDENTIFIER_QUOTER, param_style=ParamStyle.QMARK)
+
+# MotherDuck is a single global service — there is no per-account hostname to configure.
+MOTHERDUCK_SERVICE_HOST = "api.motherduck.com"
+
+# DuckDB's catalog metadata schemas. `main` is a real user schema in DuckDB, not a system one.
+MOTHERDUCK_SYSTEM_SCHEMAS = ("information_schema", "pg_catalog")
+
+# Rows materialized per Arrow batch. Bounds resident memory: DuckDB shares this process.
+DEFAULT_MOTHERDUCK_FETCH_SIZE = 5_000
+
+# DuckDB otherwise sizes itself against the whole host (80% of RAM, one thread per core), which is
+# the wrong budget for a library sharing a worker with the rest of the import pipeline.
+DUCKDB_LOCAL_CONFIG: dict[str, Any] = {"memory_limit": "2GB", "threads": 2}
+
+# The database name is interpolated into the `md:` connection string, so anything outside this
+# allowlist could smuggle extra connection parameters in alongside the token.
+_VALID_DATABASE_NAME = re.compile(r"^[A-Za-z0-9_.\-$]+$")
+
+
+def build_motherduck_connection_string(database: str, access_token: str) -> str:
+ """Assemble the `md:<database>?motherduck_token=…` DSN duckdb expects.
+
+ Raises `ValueError` for a missing token or a database name that could alter
+ the DSN's query string. Never log the return value: it carries the token.
+ """
+ name = database.strip()
+ if not name:
+ raise ValueError("Database name is missing")
+ if not _VALID_DATABASE_NAME.match(name):
+ raise ValueError(f"Invalid MotherDuck database name: {name!r}")
+ if not access_token:
+ raise ValueError("Access token is missing")
+ return f"md:{name}?{urlencode({'motherduck_token': access_token})}"
+
+
+def filter_motherduck_incremental_fields(
+ columns: list[tuple[str, str, bool]],
+) -> list[tuple[str, IncrementalFieldType, bool]]:
+ results: list[tuple[str, IncrementalFieldType, bool]] = []
+ for column_name, type, nullable in columns:
+ type = type.lower()
+ if type.startswith("timestamp"):
+ # Covers TIMESTAMP, TIMESTAMP WITH TIME ZONE and the _S/_MS/_NS precision variants.
+ results.append((column_name, IncrementalFieldType.Timestamp, nullable))
+ elif type == "date":
+ results.append((column_name, IncrementalFieldType.Date, nullable))
+ elif type in (
+ "bigint",
+ "integer",
+ "smallint",
+ "tinyint",
+ "hugeint",
+ "ubigint",
+ "uinteger",
+ "usmallint",
+ "utinyint",
+ "uhugeint",
+ ) or type.startswith("decimal"):
+ results.append((column_name, IncrementalFieldType.Numeric, nullable))
+
+ return results
+
+
+def _split_display_name(display_name: str, default_schema: Optional[str]) -> tuple[Optional[str], str]:
+ """Split a `schema.table` display name into `(schema, table)`.
+
+ Multi-schema discovery qualifies every table as `schema.table`; a single-schema
+ source keeps bare table names and falls back to the configured schema. The dotted
+ form mirrors `resolve_source_location`'s self-heal so listing keys and per-row
+ routing agree.
+ """
+ if "." in display_name:
+ schema, _, table = display_name.partition(".")
+ return (normalize_namespace(schema) or default_schema), table
+ return default_schema, display_name
+
+
+class MotherDuckImplementation(SQLSourceImplementation[MotherduckSourceConfig, Any, Any]):
+ """MotherDuck driver implementation paired with `MotherduckSource`.
+
+ Discovery reads DuckDB's `information_schema` and its `duckdb_constraints()` /
+ `duckdb_tables()` catalog functions, all scoped to `current_database()` so the
+ client's own `memory`, `system` and `temp` catalogs never surface as tables.
+
+ Partition sizing is deliberately not implemented: DuckDB's catalog exposes an
+ estimated row count but no on-disk byte size for an attached MotherDuck
+ database, and the shared partition math needs bytes. The base class returns
+ `None`, which falls back to default partition settings.
+ """
+
+ # ------------------------------------------------------------------
+ # Connection lifecycle
+ # ------------------------------------------------------------------
+
+ @contextmanager
+ def connect(self, config: MotherduckSourceConfig) -> Iterator[Any]:
+ """Open a MotherDuck-backed DuckDB connection for the duration of the context."""
+ connection_string = build_motherduck_connection_string(config.database, config.access_token)
+ log_connection_open(db_host=MOTHERDUCK_SERVICE_HOST, via="vendor_https")
+ connection = duckdb.connect(connection_string, config=dict(DUCKDB_LOCAL_CONFIG))
+ try:
+ yield connection
+ finally:
+ connection.close()
+
+ # ------------------------------------------------------------------
+ # Listing — batch queries run once during `get_schemas`
+ # ------------------------------------------------------------------
+
+ def get_columns(
+ self,
+ conn: Any,
+ config: MotherduckSourceConfig,
+ names: list[str] | None,
+ ) -> dict[str, list[tuple[str, str, bool]]]:
+ selected_schema = normalize_namespace(config.schema)
+ qualify = selected_schema is None
+
+ # Joined against `information_schema.tables` and restricted to `BASE TABLE`: a view's
+ # columns are otherwise indistinguishable here from a real table's, but its definition
+ # runs inside this Temporal worker at query time. A source owner could define a view over
+ # a locally-executed DuckDB table function (e.g. reading the worker's filesystem) and have
+ # it synced like any other table, so views are never offered for discovery.
+ select = (
+ "SELECT c.table_schema, c.table_name, c.column_name, c.data_type, c.is_nullable"
+ " FROM information_schema.columns c"
+ " JOIN information_schema.tables t"
+ " ON t.table_catalog = c.table_catalog"
+ " AND t.table_schema = c.table_schema"
+ " AND t.table_name = c.table_name"
+ " WHERE c.table_catalog = current_database()"
+ " AND t.table_type = 'BASE TABLE'"
+ )
+ order = " ORDER BY c.table_schema ASC, c.table_name ASC, c.ordinal_position ASC"
+
+ if selected_schema is not None:
+ result = conn.execute(f"{select} AND c.table_schema = ?{order}", [selected_schema]).fetchall()
+ else:
+ placeholders = ", ".join("?" for _ in MOTHERDUCK_SYSTEM_SCHEMAS)
+ result = conn.execute(
+ f"{select} AND c.table_schema NOT IN ({placeholders}){order}",
+ list(MOTHERDUCK_SYSTEM_SCHEMAS),
+ ).fetchall()
+
+ 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_name = f"{table_schema}.{table_name}" if qualify else table_name
+ schema_list[display_name].append((column_name, data_type, is_nullable == "YES"))
+
+ if names is not None:
+ # Match qualified (`schema.table`) and bare (`table`) names — a row requested by its
+ # qualified name can still map to a bare discovery key (or vice versa) mid-migration.
+ available = dict(schema_list)
+ filtered: dict[str, list[tuple[str, str, bool]]] = {}
+ for name in names:
+ if name in available:
+ filtered[name] = available[name]
+ elif "." in name:
+ _schema, _, unqualified = name.partition(".")
+ if unqualified in available:
+ filtered[name] = available[unqualified]
+ return filtered
+
+ return dict(schema_list)
+
+ def _display_names_by_pair(
+ self,
+ config: MotherduckSourceConfig,
+ tables: list[str],
+ ) -> dict[tuple[str, str], str]:
+ """Index the requested display names by their `(schema, table)` pair."""
+ default_schema = normalize_namespace(config.schema)
+ pairs: dict[tuple[str, str], str] = {}
+ for display_name in tables:
+ schema, table = _split_display_name(display_name, default_schema)
+ if schema is None:
+ continue
+ pairs[(schema, table)] = display_name
+ return pairs
+
+ def get_primary_keys(
+ self,
+ conn: Any,
+ config: MotherduckSourceConfig,
+ tables: list[str],
+ ) -> dict[str, list[str] | None]:
+ """Detect primary-key constraints for the given tables in one batched query.
+
+ `duckdb_constraints()` already returns the key's columns in order, so no
+ join or ordinal sort is needed. Most MotherDuck tables have no declared
+ primary key, and the catalog function is permission-sensitive, so a failure
+ degrades to "no keys found" and the base falls back to an `id` column.
+ """
+ result: dict[str, list[str] | None] = dict.fromkeys(tables)
+ if not tables:
+ return result
+
+ display_by_pair = self._display_names_by_pair(config, tables)
+
+ try:
+ rows = conn.execute(
+ "SELECT schema_name, table_name, constraint_column_names"
+ " FROM duckdb_constraints()"
+ " WHERE database_name = current_database() AND constraint_type = 'PRIMARY KEY'"
+ ).fetchall()
+ except Exception as e:
+ structlog.get_logger().warning("Failed to detect primary keys for MotherDuck tables", exc_info=e)
+ return result
+
+ for schema_name, table_name, columns in rows:
+ display_key = display_by_pair.get((schema_name, table_name))
+ if display_key is None or not columns:
+ continue
+ result[display_key] = list(columns)
+
+ return result
+
+ def get_row_counts(
+ self,
+ conn: Any,
+ config: MotherduckSourceConfig,
+ tables: list[str],
+ ) -> dict[str, int | None]:
+ """Report each table's row count from DuckDB's catalog estimate.
+
+ `estimated_size` is the planner's cardinality estimate, which keeps schema
+ discovery to a single metadata query instead of a `COUNT(*)` per table
+ billed against the customer's MotherDuck compute.
+ """
+ result: dict[str, int | None] = dict.fromkeys(tables)
+ if not tables:
+ return result
+
+ display_by_pair = self._display_names_by_pair(config, tables)
+
+ try:
+ rows = conn.execute(
+ "SELECT schema_name, table_name, estimated_size"
+ " FROM duckdb_tables()"
+ " WHERE database_name = current_database()"
+ ).fetchall()
+ except Exception as e:
+ structlog.get_logger().warning("Failed to read row counts for MotherDuck tables", exc_info=e)
+ return result
+
+ for schema_name, table_name, estimated_size in rows:
+ display_key = display_by_pair.get((schema_name, table_name))
+ if display_key is None or estimated_size is None:
+ continue
+ result[display_key] = int(estimated_size)
+
+ return result
+
+ def get_source_metadata(
+ self,
+ conn: Any,
+ config: MotherduckSourceConfig,
+ tables: list[str],
+ ) -> SourceMetadata:
+ """Stamp catalog/schema/table per discovered table so per-row routing can pin a namespace."""
+ default_schema = normalize_namespace(config.schema)
+ catalog_by_table: dict[str, str | None] = {}
+ schema_by_table: dict[str, str | None] = {}
+ table_name_by_table: dict[str, str | None] = {}
+ for display_name in tables:
+ schema, table = _split_display_name(display_name, default_schema)
+ catalog_by_table[display_name] = config.database
+ schema_by_table[display_name] = schema
+ table_name_by_table[display_name] = table
+ return SourceMetadata(
+ catalog_by_table=catalog_by_table,
+ schema_by_table=schema_by_table,
+ table_name_by_table=table_name_by_table,
+ )
+
+ def get_incremental_filter(self) -> IncrementalFieldFilter:
+ return filter_motherduck_incremental_fields
+
+ # ------------------------------------------------------------------
+ # Per-connection metadata — used during `build_pipeline`
+ # ------------------------------------------------------------------
+
+ def get_primary_keys_for_table(
+ self,
+ conn: Any,
+ schema: str,
+ table_name: str,
+ ) -> list[str] | None:
+ """Return the primary-key column names for a single table, or None.
+
+ Permission-sensitive like the schema-level `get_primary_keys` — a failing
+ lookup degrades to None so the pipeline falls back to a persisted or
+ `id`-column primary key instead of crashing a merge.
+ """
+ try:
+ rows = conn.execute(
+ "SELECT constraint_column_names"
+ " FROM duckdb_constraints()"
+ " WHERE database_name = current_database() AND constraint_type = 'PRIMARY KEY'"
+ " AND schema_name = ? AND table_name = ?",
+ [schema, table_name],
+ ).fetchall()
+ except Exception as e:
+ structlog.get_logger().warning(
+ "Failed to detect primary key for MotherDuck table",
+ schema=schema,
+ table_name=table_name,
+ exc_info=e,
+ )
+ return None
+
+ for (columns,) in rows:
+ if columns:
+ return list(columns)
+ return None
+
+ # ------------------------------------------------------------------
+ # Pipeline build — the `SourceResponse` for a single table
+ # ------------------------------------------------------------------
+
+ def build_pipeline(self, config: MotherduckSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ # Per-row routing: a multi-schema row pins its own namespace via `schema_metadata`, a
+ # single-schema row falls back to `config.schema`. The database is fixed per connection.
+ location = resolve_source_location(inputs, config_namespace=config.schema)
+ table_name = location.table_name
+ schema = location.schema
+ if not table_name:
+ raise ValueError("Table name is missing")
+ if not schema:
+ raise ValueError("Schema is missing")
+
+ logger = inputs.logger
+ incremental_field = inputs.incremental_field if inputs.should_use_incremental_field else None
+ incremental_field_type = inputs.incremental_field_type if inputs.should_use_incremental_field else None
+
+ with self.connect(config) as connection:
+ primary_keys = self.get_primary_keys_for_table(connection, schema, table_name)
+ query = _QUERY_BUILDER.select_all(
+ schema=schema,
+ table_name=table_name,
+ incremental_field=incremental_field,
+ incremental_field_type=incremental_field_type,
+ incremental_last_value=inputs.db_incremental_field_last_value,
+ enabled_columns=inputs.enabled_columns,
+ primary_keys=primary_keys,
+ row_filters=inputs.row_filters,
+ )
+ rows_to_sync = self.get_rows_to_sync(connection, query.sql, query.params, logger)
+
+ def get_rows() -> Iterator[pa.Table]:
+ with self.connect(config) as streaming_connection:
+ logger.debug(f"MotherDuck query: {query.sql}")
+ reader = streaming_connection.execute(query.sql, query.params).to_arrow_reader(
+ DEFAULT_MOTHERDUCK_FETCH_SIZE
+ )
+ for batch in reader:
+ yield pa.Table.from_batches([batch], schema=reader.schema)
+
+ return SourceResponse(
+ name=location.response_name,
+ items=get_rows,
+ primary_keys=primary_keys,
+ rows_to_sync=rows_to_sync,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/source.py
index a0ede30d7774..3706871f88dd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/source.py
@@ -1,21 +1,48 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.exceptions_capture import capture_exception
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.base import SQLSource
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.motherduck import (
MotherduckSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.motherduck.motherduck import (
+ MotherDuckImplementation,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+_MOTHERDUCK_IMPLEMENTATION = MotherDuckImplementation()
+
+# DuckDB prefixes every error message with its stable error class ("Catalog Error:", "Binder
+# Error:", …). The text after the prefix carries volatile object names, so we match the class.
+MotherDuckErrors = {
+ "Catalog Error": "Can't find that database or schema in MotherDuck. Check the database and schema names, then try again.",
+ "Binder Error": "MotherDuck rejected the query. Check that the database and schema still contain the tables you want to sync.",
+ "Invalid Input Error": "MotherDuck rejected the connection details. Check the database name and access token, then try again.",
+}
+
@SourceRegistry.register
-class MotherduckSource(SimpleSource[MotherduckSourceConfig]):
+class MotherduckSource(SQLSource[MotherduckSourceConfig]):
+ # MotherDuck speaks the DuckDB wire protocol through the `duckdb` client, which carries no
+ # vendor API version of its own.
+ api_docs_url = "https://motherduck.com/docs/"
+
+ @property
+ def get_implementation(self) -> MotherDuckImplementation:
+ return _MOTHERDUCK_IMPLEMENTATION
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.MOTHERDUCK
@@ -27,7 +54,78 @@ class MotherduckSource(SimpleSource[MotherduckSourceConfig]):
category=DataWarehouseSourceCategory.DATABASES,
keywords=["sql", "duckdb"],
label="MotherDuck",
+ caption="Enter your MotherDuck access token and database name to pull your MotherDuck tables into the PostHog Data warehouse. Create an access token in your MotherDuck account settings.",
iconPath="/static/services/motherduck.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="access_token",
+ label="Access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="database",
+ label="Database",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="my_db",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="schema",
+ label="Schema (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="Leave blank to import all schemas",
+ secret=False,
+ ),
+ ],
+ ),
)
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ **self.default_non_retryable_errors(),
+ "Catalog Error": "A database, schema, or table this source syncs no longer exists in MotherDuck, or your access token lost access to it. Check that it still exists, then resync.",
+ "Binder Error": "A column this source syncs no longer exists in MotherDuck. Reset the table so we pick up its new shape, then resync.",
+ "Invalid Input Error": "MotherDuck rejected the connection details. Check the database name and access token, then resync.",
+ }
+
+ def validate_credentials(
+ self,
+ config: MotherduckSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if not config.access_token:
+ return False, "Missing required parameter: access token"
+ if not config.database.strip():
+ return False, "Missing required parameter: database"
+
+ try:
+ self.get_schemas(config, team_id)
+ except ValueError as e:
+ # Raised by `build_motherduck_connection_string` for a database name we won't put in
+ # the connection string; the message already names the offending value.
+ return False, str(e)
+ except Exception as e:
+ error_msg = str(e)
+ if "token" in error_msg.lower():
+ return (
+ False,
+ "MotherDuck rejected the access token. Check that the token is correct and has not expired.",
+ )
+ for key, value in MotherDuckErrors.items():
+ if key in error_msg:
+ return False, value
+
+ capture_exception(e)
+ return False, "Could not connect to MotherDuck. Please check all connection details are valid."
+
+ return True, None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/tests/test_motherduck.py b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/tests/test_motherduck.py
new file mode 100644
index 000000000000..05cbfebab43b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/tests/test_motherduck.py
@@ -0,0 +1,433 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+import pyarrow as pa
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.motherduck import (
+ MotherduckSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.motherduck.motherduck import (
+ DEFAULT_MOTHERDUCK_FETCH_SIZE,
+ DUCKDB_LOCAL_CONFIG,
+ MotherDuckImplementation,
+ build_motherduck_connection_string,
+ filter_motherduck_incremental_fields,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.motherduck.source import MotherduckSource
+from products.warehouse_sources.backend.types import IncrementalFieldType
+
+_CONNECT_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.motherduck.motherduck.duckdb.connect"
+
+
+def _make_config(**overrides) -> MotherduckSourceConfig:
+ defaults: dict = {"access_token": "md-token", "database": "my_db", "schema": "analytics"}
+ defaults.update(overrides)
+ return MotherduckSourceConfig.from_dict(defaults)
+
+
+def _make_inputs(schema_name: str = "users", **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)
+
+
+def _conn() -> MagicMock:
+ """A DuckDB-shaped connection: `execute()` returns the connection itself."""
+ conn = MagicMock()
+ conn.execute.return_value = conn
+ conn.fetchall.return_value = []
+ conn.fetchone.return_value = None
+ return conn
+
+
+def impl() -> MotherDuckImplementation:
+ return MotherDuckImplementation()
+
+
+class TestMotherDuck:
+ # ------------------------------------------------------------------
+ # Connection string
+ # ------------------------------------------------------------------
+
+ def test_connection_string_url_encodes_the_token(self):
+ assert build_motherduck_connection_string(" my_db ", "to ken/+=") == "md:my_db?motherduck_token=to+ken%2F%2B%3D"
+
+ @pytest.mark.parametrize(
+ "database",
+ [
+ "",
+ " ",
+ # Anything that could append its own connection parameters or split the DSN.
+ "my_db?motherduck_token=attacker",
+ "my_db&motherduck_token=attacker",
+ "my db",
+ "my_db#frag",
+ "my/db",
+ ],
+ )
+ def test_connection_string_rejects_unsafe_database_names(self, database):
+ with pytest.raises(ValueError):
+ build_motherduck_connection_string(database, "md-token")
+
+ def test_connection_string_requires_a_token(self):
+ with pytest.raises(ValueError):
+ build_motherduck_connection_string("my_db", "")
+
+ # ------------------------------------------------------------------
+ # Incremental field types
+ # ------------------------------------------------------------------
+
+ @pytest.mark.parametrize(
+ "data_type,expected",
+ [
+ ("TIMESTAMP", IncrementalFieldType.Timestamp),
+ ("TIMESTAMP WITH TIME ZONE", IncrementalFieldType.Timestamp),
+ ("TIMESTAMP_NS", IncrementalFieldType.Timestamp),
+ ("DATE", IncrementalFieldType.Date),
+ ("BIGINT", IncrementalFieldType.Numeric),
+ ("INTEGER", IncrementalFieldType.Numeric),
+ ("HUGEINT", IncrementalFieldType.Numeric),
+ ("UBIGINT", IncrementalFieldType.Numeric),
+ # DuckDB reports the parameterized form, so an equality match would drop these.
+ ("DECIMAL(18,3)", IncrementalFieldType.Numeric),
+ ],
+ )
+ def test_incremental_filter_picks_up_supported_types(self, data_type, expected):
+ assert filter_motherduck_incremental_fields([("c", data_type, True)]) == [("c", expected, True)]
+
+ @pytest.mark.parametrize("data_type", ["VARCHAR", "BOOLEAN", "DOUBLE", "FLOAT", "BLOB", "JSON", "INTEGER[]"])
+ def test_incremental_filter_drops_unsupported_types(self, data_type):
+ # Floats are deliberately excluded — an imprecise cursor skips or re-reads rows at the boundary.
+ assert filter_motherduck_incremental_fields([("c", data_type, True)]) == []
+
+ # ------------------------------------------------------------------
+ # connect()
+ # ------------------------------------------------------------------
+
+ def test_connect_bounds_duckdb_resources_and_passes_the_dsn(self, impl):
+ with patch(_CONNECT_PATH) as mock_connect:
+ with impl.connect(_make_config()):
+ pass
+ assert mock_connect.call_args.args[0] == "md:my_db?motherduck_token=md-token"
+ # DuckDB shares this process, so it must not size itself against the whole host.
+ assert mock_connect.call_args.kwargs["config"] == DUCKDB_LOCAL_CONFIG
+
+ def test_connect_closes_on_exit(self, impl):
+ with patch(_CONNECT_PATH) as mock_connect:
+ with impl.connect(_make_config()):
+ mock_connect.return_value.close.assert_not_called()
+ mock_connect.return_value.close.assert_called_once()
+
+ def test_connect_closes_on_error(self, impl):
+ with patch(_CONNECT_PATH) as mock_connect:
+ with pytest.raises(RuntimeError):
+ with impl.connect(_make_config()):
+ raise RuntimeError("boom")
+ mock_connect.return_value.close.assert_called_once()
+
+ # ------------------------------------------------------------------
+ # Listing
+ # ------------------------------------------------------------------
+
+ def test_get_columns_groups_columns_by_table(self, impl):
+ conn = _conn()
+ conn.fetchall.return_value = [
+ ("analytics", "users", "id", "BIGINT", "NO"),
+ ("analytics", "users", "email", "VARCHAR", "YES"),
+ ("analytics", "orders", "id", "BIGINT", "NO"),
+ ]
+ result = impl.get_columns(conn, _make_config(), names=None)
+ # Single-schema source keeps bare table names.
+ assert set(result.keys()) == {"users", "orders"}
+ assert result["users"] == [("id", "BIGINT", False), ("email", "VARCHAR", True)]
+
+ def test_get_columns_scopes_to_the_configured_schema(self, impl):
+ conn = _conn()
+ impl.get_columns(conn, _make_config(schema="sales"), names=None)
+ sql, params = conn.execute.call_args.args
+ assert "table_schema = ?" in sql
+ # The client also holds `memory`, `system` and `temp` catalogs that are not customer data.
+ assert "table_catalog = current_database()" in sql
+ assert params == ["sales"]
+
+ @pytest.mark.parametrize("blank", ["", " ", None])
+ def test_get_columns_blank_schema_discovers_all_namespaces_qualified(self, impl, blank):
+ conn = _conn()
+ conn.fetchall.return_value = [
+ ("analytics", "users", "id", "BIGINT", "NO"),
+ ("sales", "users", "id", "BIGINT", "NO"),
+ ("sales", "orders", "id", "BIGINT", "NO"),
+ ]
+ result = impl.get_columns(conn, _make_config(schema=blank), names=None)
+ # Same table name in two schemas must stay distinct and qualified.
+ assert set(result.keys()) == {"analytics.users", "sales.users", "sales.orders"}
+ sql, params = conn.execute.call_args.args
+ assert "table_schema NOT IN (?, ?)" in sql
+ assert params == ["information_schema", "pg_catalog"]
+
+ def test_get_columns_excludes_views(self, impl):
+ # A view's definition runs inside this worker at query time — e.g. over a locally-executed
+ # DuckDB table function reading the filesystem — so only `BASE TABLE` entries are ever
+ # offered for discovery/sync.
+ conn = _conn()
+ impl.get_columns(conn, _make_config(), names=None)
+ sql = conn.execute.call_args.args[0]
+ assert "t.table_type = 'BASE TABLE'" in sql
+
+ def test_get_columns_filters_by_names(self, impl):
+ conn = _conn()
+ conn.fetchall.return_value = [
+ ("analytics", "users", "id", "BIGINT", "NO"),
+ ("analytics", "orders", "id", "BIGINT", "NO"),
+ ]
+ assert list(impl.get_columns(conn, _make_config(), names=["users"]).keys()) == ["users"]
+
+ def test_get_columns_qualified_name_falls_back_to_bare_discovery_key(self, impl):
+ # Mid-migration a row may be requested qualified while a configured-schema source still
+ # discovers it bare — keep the requested (qualified) key, mapped to the bare columns.
+ conn = _conn()
+ conn.fetchall.return_value = [("analytics", "users", "id", "BIGINT", "NO")]
+ result = impl.get_columns(conn, _make_config(schema="analytics"), names=["analytics.users"])
+ assert result == {"analytics.users": [("id", "BIGINT", False)]}
+
+ def test_get_primary_keys_returns_constraint_columns_in_order(self, impl):
+ conn = _conn()
+ conn.fetchall.return_value = [("analytics", "users", ["id", "tenant_id"])]
+ out = impl.get_primary_keys(conn, _make_config(), tables=["users", "orders"])
+ assert out == {"users": ["id", "tenant_id"], "orders": None}
+ # One batched catalog query, not one per table.
+ assert conn.execute.call_count == 1
+
+ def test_get_primary_keys_routes_to_qualified_display_names(self, impl):
+ conn = _conn()
+ conn.fetchall.return_value = [
+ ("analytics", "users", ["id"]),
+ ("sales", "users", ["uuid"]),
+ ]
+ out = impl.get_primary_keys(conn, _make_config(schema=""), tables=["analytics.users", "sales.users"])
+ assert out == {"analytics.users": ["id"], "sales.users": ["uuid"]}
+
+ def test_get_primary_keys_swallows_failure(self, impl):
+ # Discovery must keep working without keys — the base falls back to an `id` column.
+ conn = _conn()
+ conn.execute.side_effect = Exception("Catalog Error: duckdb_constraints does not exist")
+ assert impl.get_primary_keys(conn, _make_config(), tables=["users"]) == {"users": None}
+
+ def test_get_row_counts_reads_catalog_estimates(self, impl):
+ conn = _conn()
+ conn.fetchall.return_value = [
+ ("analytics", "users", 1_200),
+ ("analytics", "orders", None),
+ ("analytics", "unrequested", 5),
+ ]
+ out = impl.get_row_counts(conn, _make_config(), tables=["users", "orders"])
+ assert out == {"users": 1_200, "orders": None}
+
+ def test_get_row_counts_swallows_failure(self, impl):
+ conn = _conn()
+ conn.execute.side_effect = Exception("Catalog Error: duckdb_tables does not exist")
+ assert impl.get_row_counts(conn, _make_config(), tables=["users"]) == {"users": None}
+
+ def test_get_source_metadata_single_schema_pins_configured_namespace(self, impl):
+ meta = impl.get_source_metadata(MagicMock(), _make_config(schema="analytics"), tables=["users"])
+ assert meta.catalog_by_table == {"users": "my_db"}
+ assert meta.schema_by_table == {"users": "analytics"}
+ assert meta.table_name_by_table == {"users": "users"}
+
+ def test_get_source_metadata_multi_schema_splits_qualified_names(self, impl):
+ meta = impl.get_source_metadata(MagicMock(), _make_config(schema=""), tables=["analytics.users", "sales.users"])
+ assert meta.schema_by_table == {"analytics.users": "analytics", "sales.users": "sales"}
+ assert meta.table_name_by_table == {"analytics.users": "users", "sales.users": "users"}
+
+ def test_get_primary_keys_for_table_scopes_the_lookup(self, impl):
+ conn = _conn()
+ conn.fetchall.return_value = [(["id", "tenant_id"],)]
+ assert impl.get_primary_keys_for_table(conn, "analytics", "users") == ["id", "tenant_id"]
+ _sql, params = conn.execute.call_args.args
+ assert params == ["analytics", "users"]
+
+ @pytest.mark.parametrize("rows", [[], [(None,)], [([],)]])
+ def test_get_primary_keys_for_table_returns_none_without_a_key(self, impl, rows):
+ conn = _conn()
+ conn.fetchall.return_value = rows
+ assert impl.get_primary_keys_for_table(conn, "analytics", "users") is None
+
+ def test_get_primary_keys_for_table_returns_none_when_lookup_fails(self, impl):
+ # A failing lookup must degrade to None so the pipeline falls back instead of crashing.
+ conn = _conn()
+ conn.execute.side_effect = Exception("Catalog Error")
+ assert impl.get_primary_keys_for_table(conn, "analytics", "users") is None
+
+ # ------------------------------------------------------------------
+ # build_pipeline
+ # ------------------------------------------------------------------
+
+ def _pipeline_mocks(self, primary_key_rows, rows_to_sync, batches):
+ metadata_conn = _conn()
+ metadata_conn.fetchall.return_value = primary_key_rows
+ metadata_conn.fetchone.return_value = (rows_to_sync,)
+
+ streaming_conn = _conn()
+ schema = batches[0].schema
+ streaming_conn.to_arrow_reader.return_value = pa.RecordBatchReader.from_batches(schema, batches)
+ return metadata_conn, streaming_conn
+
+ def test_build_pipeline_streams_bounded_arrow_batches(self, impl):
+ batches = [pa.RecordBatch.from_pydict({"id": [1, 2]}), pa.RecordBatch.from_pydict({"id": [3]})]
+ metadata_conn, streaming_conn = self._pipeline_mocks([(["id"],)], 3, batches)
+
+ with patch(_CONNECT_PATH, side_effect=[metadata_conn, streaming_conn]):
+ response = impl.build_pipeline(_make_config(), _make_inputs(schema_name="users"))
+ assert response.name == "users"
+ assert response.primary_keys == ["id"]
+ assert response.rows_to_sync == 3
+ tables = list(response.items())
+
+ assert [t.num_rows for t in tables] == [2, 1]
+ sql, params = streaming_conn.execute.call_args.args
+ assert sql == 'SELECT * FROM "analytics"."users"'
+ assert params == []
+ # DuckDB runs in-process, so the reader must be asked for bounded batches.
+ streaming_conn.to_arrow_reader.assert_called_once_with(DEFAULT_MOTHERDUCK_FETCH_SIZE)
+
+ def test_build_pipeline_incremental_query_filters_and_orders(self, impl):
+ metadata_conn, streaming_conn = self._pipeline_mocks([(["id"],)], 1, [pa.RecordBatch.from_pydict({"id": [1]})])
+ inputs = _make_inputs(
+ schema_name="users",
+ should_use_incremental_field=True,
+ incremental_field="updated_at",
+ incremental_field_type=IncrementalFieldType.Timestamp,
+ db_incremental_field_last_value="2026-01-01T00:00:00",
+ )
+
+ with patch(_CONNECT_PATH, side_effect=[metadata_conn, streaming_conn]):
+ response = impl.build_pipeline(_make_config(), inputs)
+ list(response.items())
+
+ sql, params = streaming_conn.execute.call_args.args
+ assert 'WHERE "updated_at" > ?' in sql
+ # `sort_mode` defaults to ascending, so the query must actually order that way.
+ assert sql.endswith('ORDER BY "updated_at" ASC')
+ assert params == ["2026-01-01T00:00:00"]
+
+ def test_build_pipeline_projection_retains_the_primary_key(self, impl):
+ # Dropping the PK from the projection would break the Delta merge on every later sync.
+ metadata_conn, streaming_conn = self._pipeline_mocks([(["id"],)], 1, [pa.RecordBatch.from_pydict({"id": [1]})])
+
+ with patch(_CONNECT_PATH, side_effect=[metadata_conn, streaming_conn]):
+ response = impl.build_pipeline(_make_config(), _make_inputs(enabled_columns=["email"]))
+ list(response.items())
+
+ sql, _params = streaming_conn.execute.call_args.args
+ assert sql.startswith('SELECT "email", "id" FROM "analytics"."users"')
+
+ def test_build_pipeline_multi_schema_row_routes_to_its_own_namespace(self, impl):
+ metadata_conn, streaming_conn = self._pipeline_mocks([(["id"],)], 1, [pa.RecordBatch.from_pydict({"id": [1]})])
+
+ with patch(_CONNECT_PATH, side_effect=[metadata_conn, streaming_conn]):
+ response = impl.build_pipeline(_make_config(schema=""), _make_inputs(schema_name="sales.users"))
+ # Delta subdir keeps the qualified, normalized name so cross-schema duplicates stay distinct.
+ assert response.name == "sales_users"
+ list(response.items())
+
+ sql, _params = streaming_conn.execute.call_args.args
+ assert 'FROM "sales"."users"' in sql
+ # The PK probe targets the resolved namespace too.
+ assert metadata_conn.execute.call_args_list[0].args[1] == ["sales", "users"]
+
+ def test_build_pipeline_rejects_an_unresolvable_namespace(self, impl):
+ # A blank config namespace plus a bare row name leaves nothing to qualify the table with,
+ # and an unqualified `FROM users` would silently read whichever schema DuckDB resolves to.
+ with patch(_CONNECT_PATH) as mock_connect:
+ with pytest.raises(ValueError):
+ impl.build_pipeline(_make_config(schema=""), _make_inputs(schema_name="users"))
+ mock_connect.assert_not_called()
+
+ # ------------------------------------------------------------------
+ # Source-level behavior
+ # ------------------------------------------------------------------
+
+ @pytest.fixture
+ def source(self) -> MotherduckSource:
+ return MotherduckSource()
+
+ def test_source_is_visible_and_marked_alpha(self, source):
+ # `unreleasedSource` hides a source from users entirely — a finished source must not set it.
+ config = source.get_source_config
+ assert not config.unreleasedSource
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ def test_schema_field_is_optional_for_multi_schema_support(self, source):
+ # `is_multi_schema_capable_sql_source` keys off the schema field being optional.
+ schema_field = next(f for f in source.get_source_config.fields if f.name == "schema")
+ assert isinstance(schema_field, SourceFieldInputConfig)
+ assert schema_field.required is False
+
+ def test_access_token_is_stored_as_a_secret(self, source):
+ token_field = next(f for f in source.get_source_config.fields if f.name == "access_token")
+ assert isinstance(token_field, SourceFieldInputConfig)
+ assert token_field.secret is True
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+
+ @pytest.mark.parametrize(
+ "error_msg",
+ [
+ "Catalog Error: Table with name users does not exist!",
+ "Binder Error: Referenced column email not found in FROM clause!",
+ "Invalid Input Error: The following options were not recognized: motherduck_token",
+ "Source column type changed",
+ ],
+ )
+ def test_permanent_failures_are_non_retryable(self, source, error_msg):
+ non_retryable = source.get_non_retryable_errors()
+ assert any(pattern in error_msg for pattern in non_retryable), f"Error should be non-retryable: {error_msg}"
+
+ @pytest.mark.parametrize(
+ "overrides,expected_fragment",
+ [
+ ({"access_token": ""}, "access token"),
+ ({"database": " "}, "database"),
+ ],
+ )
+ def test_validate_credentials_requires_connection_details(self, source, overrides, expected_fragment):
+ ok, message = source.validate_credentials(_make_config(**overrides), team_id=1)
+ assert ok is False
+ assert message is not None and expected_fragment in message
+
+ @pytest.mark.parametrize(
+ "error,expected_fragment",
+ [
+ (Exception("IO Error: MotherDuck token is invalid"), "access token"),
+ (Exception("Catalog Error: Database with name nope does not exist!"), "database and schema names"),
+ (Exception("Binder Error: Referenced column not found"), "rejected the query"),
+ (Exception("Invalid Input Error: bad option"), "connection details"),
+ (ValueError("Invalid MotherDuck database name: 'my db'"), "Invalid MotherDuck database name"),
+ (Exception("something totally unexpected"), "Could not connect to MotherDuck"),
+ ],
+ )
+ def test_validate_credentials_maps_connection_errors(self, source, error, expected_fragment):
+ with patch.object(MotherduckSource, "get_schemas", side_effect=error):
+ ok, message = source.validate_credentials(_make_config(), team_id=1)
+ assert ok is False
+ assert message is not None and expected_fragment in message
+
+ def test_validate_credentials_success(self, source):
+ with patch.object(MotherduckSource, "get_schemas", return_value=[MagicMock()]):
+ assert source.validate_credentials(_make_config(), team_id=1) == (True, None)