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 as a direct source connection (#78917)

Jovan Sakovic049682463924
diff --git a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
index 133a28e7ee82..099c84da98e9 100644
--- a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
@@ -1123,6 +1123,10 @@ const Content = ({
showVisualizationSettings,
isEmbeddedMode,
}: any): JSX.Element | null => {
+ const { selectedDirectSource } = useValues(sqlEditorLogic)
+ // dataNodeLogic's timer resets on every loadData dispatch, so a rerun issued while a
+ // query is still in flight restarts the count (a local isLoading-keyed timer wouldn't).
+ const { loadingTimeSeconds } = useValues(dataNodeLogic)
const [sortColumns, setSortColumns] = useState<SortColumn[]>([])
const sortedRows = useMemo(() => {
@@ -1217,6 +1221,15 @@ const Content = ({
pollResponse={pollResponse}
setProgress={setProgress}
progress={progress}
+ suggestion={
+ // Only worth saying once the query is demonstrably slow.
+ selectedDirectSource?.source_type === 'Motherduck' && loadingTimeSeconds >= 60 ? (
+ <p className="text-xs m-0 text-center">
+ This query runs live on your MotherDuck database. Speed depends on its capacity and
+ current load.
+ </p>
+ ) : undefined
+ }
/>
</div>
)
diff --git a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts
index 06976638289d..4ba46a624d64 100644
--- a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts
+++ b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts
@@ -7,6 +7,7 @@ import { urls } from 'scenes/urls'
import IconPostHog from 'public/posthog-icon.svg'
import IconClickHouse from 'public/services/clickhouse.png'
import IconDuckDB from 'public/services/duckdb.svg'
+import IconMotherDuck from 'public/services/motherduck.png'
import IconMySQL from 'public/services/mysql.png'
import IconPostgres from 'public/services/postgres.png'
import IconRedshift from 'public/services/redshift.png'
@@ -45,7 +46,7 @@ export interface ConnectionSelectOptionGroup {
options: ConnectionSelectOption[]
}
-type ConnectionEngine = 'duckdb' | 'postgres' | 'mysql' | 'snowflake' | 'redshift' | 'clickhouse'
+type ConnectionEngine = 'duckdb' | 'postgres' | 'mysql' | 'snowflake' | 'redshift' | 'clickhouse' | 'motherduck'
const ENGINE_LABELS: Record<ConnectionEngine, string> = {
duckdb: 'DuckDB',
@@ -54,6 +55,7 @@ const ENGINE_LABELS: Record<ConnectionEngine, string> = {
snowflake: 'Snowflake',
redshift: 'Redshift',
clickhouse: 'ClickHouse',
+ motherduck: 'MotherDuck',
}
const ENGINE_ICONS: Record<ConnectionEngine, string> = {
@@ -63,6 +65,7 @@ const ENGINE_ICONS: Record<ConnectionEngine, string> = {
snowflake: IconSnowflake,
redshift: IconRedshift,
clickhouse: IconClickHouse,
+ motherduck: IconMotherDuck,
}
function getConnectionEngine(
@@ -73,7 +76,8 @@ function getConnectionEngine(
source.engine === 'mysql' ||
source.engine === 'snowflake' ||
source.engine === 'redshift' ||
- source.engine === 'clickhouse'
+ source.engine === 'clickhouse' ||
+ source.engine === 'motherduck'
) {
return source.engine
}
diff --git a/posthog/hogql/database/direct_motherduck_table.py b/posthog/hogql/database/direct_motherduck_table.py
new file mode 100644
index 000000000000..1ea8c8eeec52
--- /dev/null
+++ b/posthog/hogql/database/direct_motherduck_table.py
@@ -0,0 +1,47 @@
+from posthog.hogql.database.direct_sql_table import DirectSQLTable
+from posthog.hogql.database.models import FieldOrTable
+from posthog.hogql.errors import QueryError
+from posthog.hogql.escape_sql import escape_duckdb_identifier
+
+
+class DirectMotherDuckTable(DirectSQLTable):
+ motherduck_database: str
+ motherduck_schema: str
+ motherduck_table_name: str
+
+ # DuckDB resolves identifiers case-insensitively while preserving stored case, so match a
+ # HogQL field to its canonically-cased column regardless of how the user typed it.
+ def _canonical_field_key(self, name: str | int) -> str | None:
+ target = str(name).lower()
+ for key in self.fields:
+ if key.lower() == target:
+ return key
+ return None
+
+ def has_field(self, name: str | int) -> bool:
+ return super().has_field(name) or self._canonical_field_key(name) is not None
+
+ def get_field(self, name: str | int) -> FieldOrTable:
+ if super().has_field(name):
+ return super().get_field(name)
+ key = self._canonical_field_key(name)
+ if key is not None:
+ return self.fields[key]
+ return super().get_field(name)
+
+ def to_printed_duckdb(self, context) -> str:
+ if not self.motherduck_database.strip() or not self.motherduck_schema.strip():
+ raise QueryError("Direct MotherDuck tables require a database and schema name.")
+ return ".".join(
+ [
+ escape_duckdb_identifier(self.motherduck_database),
+ escape_duckdb_identifier(self.motherduck_schema),
+ escape_duckdb_identifier(self.motherduck_table_name),
+ ]
+ )
+
+ def to_printed_postgres(self, context) -> str:
+ raise QueryError("Direct MotherDuck tables cannot be printed into Postgres SQL")
+
+ def to_printed_clickhouse(self, context) -> str:
+ raise QueryError("Direct MotherDuck tables cannot be printed into ClickHouse SQL")
diff --git a/posthog/hogql/direct_query_metrics.py b/posthog/hogql/direct_query_metrics.py
index 3a3f02554db9..ca557e42d7b3 100644
--- a/posthog/hogql/direct_query_metrics.py
+++ b/posthog/hogql/direct_query_metrics.py
@@ -19,7 +19,7 @@ from prometheus_client import (
Histogram,
)
-DirectQueryDialect = Literal["postgres", "mysql", "snowflake", "redshift", "clickhouse"]
+DirectQueryDialect = Literal["postgres", "mysql", "snowflake", "redshift", "clickhouse", "motherduck"]
DirectQueryStatus = Literal["success", "error"]
DIRECT_QUERY_TOTAL = PromCounter(
@@ -43,6 +43,11 @@ SNOWFLAKE_CONNECTION_CACHE_TOTAL = PromCounter(
"Direct Snowflake connection-cache lookups by result (reused vs opened).",
labelnames=["result"],
)
+DIRECT_CONNECTION_CACHE_TOTAL = PromCounter(
+ "hogql_direct_connection_cache_total",
+ "Direct-query connection-cache lookups by engine and result (reused vs opened).",
+ labelnames=["engine", "result"],
+)
@contextmanager
diff --git a/posthog/hogql/direct_sql/__init__.py b/posthog/hogql/direct_sql/__init__.py
index 09f7918fa6af..f7bfab44f960 100644
--- a/posthog/hogql/direct_sql/__init__.py
+++ b/posthog/hogql/direct_sql/__init__.py
@@ -1,6 +1,7 @@
from posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult, DirectSQLAdapter
from posthog.hogql.direct_sql.capability import direct_capable_source_types, is_direct_capable
from posthog.hogql.direct_sql.clickhouse_adapter import ClickHouseAdapter
+from posthog.hogql.direct_sql.motherduck_adapter import MotherDuckAdapter
from posthog.hogql.direct_sql.mysql_adapter import MySQLAdapter
from posthog.hogql.direct_sql.postgres_adapter import PostgresAdapter
from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement
@@ -13,12 +14,14 @@ register_adapter(MySQLAdapter())
register_adapter(SnowflakeAdapter())
register_adapter(RedshiftAdapter())
register_adapter(ClickHouseAdapter())
+register_adapter(MotherDuckAdapter())
__all__ = [
"DirectQueryRequest",
"DirectQueryResult",
"DirectSQLAdapter",
"ClickHouseAdapter",
+ "MotherDuckAdapter",
"PostgresAdapter",
"MySQLAdapter",
"SnowflakeAdapter",
diff --git a/posthog/hogql/direct_sql/motherduck_adapter.py b/posthog/hogql/direct_sql/motherduck_adapter.py
new file mode 100644
index 000000000000..513a59e2c4cd
--- /dev/null
+++ b/posthog/hogql/direct_sql/motherduck_adapter.py
@@ -0,0 +1,283 @@
+from __future__ import annotations
+
+import re
+import threading
+from typing import TYPE_CHECKING, cast
+
+import sqlparse
+from opentelemetry import trace
+from sqlparse import tokens as sqlparse_tokens
+from sqlparse.sql import Token
+
+from posthog.hogql.constants import HogQLDialect
+from posthog.hogql.direct_query_metrics import DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL, observe_direct_query
+from posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult
+from posthog.hogql.direct_sql.capability import is_direct_capable
+from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement
+from posthog.hogql.errors import ExposedHogQLError
+from posthog.hogql.motherduck_connection_cache import cached_motherduck_connection
+
+if TYPE_CHECKING:
+ import duckdb
+
+ from posthog.models.team import Team
+
+ from products.warehouse_sources.backend.facade.models import ExternalDataSource
+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.motherduck import (
+ MotherduckSourceConfig,
+ )
+ from products.warehouse_sources.backend.temporal.data_imports.sources.motherduck.source import MotherduckSource
+
+DIRECT_MOTHERDUCK_DEFAULT_STATEMENT_TIMEOUT_SECONDS = 600
+# Hard backstop against loading an unbounded result set into memory. The connection is
+# opened read-only, but a raw passthrough `SELECT * FROM huge_table` with no LIMIT would
+# still stream everything back. HogQL-authored queries already carry a LIMIT from the printer.
+DIRECT_MOTHERDUCK_MAX_ROWS = 1_000_000
+RAW_MOTHERDUCK_READ_ONLY_ERROR = "Raw MotherDuck queries must be read-only SELECT statements."
+RAW_MOTHERDUCK_BLOCKED_FUNCTION_ERROR = "This DuckDB function is not allowed in direct queries."
+DIRECT_MOTHERDUCK_ROW_CAP_ERROR = (
+ f"MotherDuck query returned more than {DIRECT_MOTHERDUCK_MAX_ROWS:,} rows. Add a LIMIT clause."
+)
+DIRECT_MOTHERDUCK_TIMEOUT_ERROR = "MotherDuck query timed out."
+
+# Functions that parse as a plain SELECT but touch the worker's environment or filesystem,
+# read back the connection's own credentials, or smuggle a second statement past the SELECT
+# gate. The connection is opened with `saas_mode=true` (no local filesystem, no extension
+# installs) and `read_only=True`, so the filesystem entries are defense in depth for the raw
+# passthrough path — HogQL-authored SQL never emits them. The credential entries are not:
+# `motherduck_token` travels in the DSN and lands as a readable DuckDB setting, so
+# `current_setting`/`duckdb_settings` would hand the source's token to anyone who can run
+# raw SQL, and `query()` would run `PRAGMA PRINT_MD_TOKEN` inside an outer SELECT.
+#
+# Only call positions are rejected, so a column or table legitimately named `query` or `glob`
+# still resolves. Quoting doesn't help an attacker either: DuckDB resolves `"glob"('/*')` to
+# the same function, so the check covers quoted identifiers in call position too.
+_RAW_MOTHERDUCK_BLOCKED_FUNCTIONS = frozenset(
+ {
+ "QUERY",
+ "QUERY_TABLE",
+ "CURRENT_SETTING",
+ "DUCKDB_SETTINGS",
+ "DUCKDB_SECRETS",
+ "READ_CSV",
+ "READ_CSV_AUTO",
+ "READ_JSON",
+ "READ_JSON_AUTO",
+ "READ_JSON_OBJECTS",
+ "READ_JSON_OBJECTS_AUTO",
+ "READ_NDJSON",
+ "READ_NDJSON_AUTO",
+ "READ_NDJSON_OBJECTS",
+ "READ_PARQUET",
+ "PARQUET_SCAN",
+ "READ_TEXT",
+ "READ_BLOB",
+ "READ_XLSX",
+ "GLOB",
+ "GETENV",
+ "SNIFF_CSV",
+ }
+)
+
+# `%(name)s` placeholders as the Postgres-family printers emit them. Printed constants can
+# never contain a stray `%` (the printer rejects it), so every match is a real placeholder.
+_PYFORMAT_PLACEHOLDER_RE = re.compile(r"%\((?P<name>[A-Za-z0-9_]+)\)s")
+
+
+def convert_pyformat_placeholders(sql: str, values: dict[str, object] | None) -> tuple[str, dict[str, object]]:
+ """Rewrite psycopg-style `%(name)s` placeholders to DuckDB's `$name` form.
+
+ The DuckDB printer inherits the Postgres printer's value binding, but the duckdb Python
+ API only understands `$name`/`?` parameters.
+ """
+ if not values:
+ return sql, {}
+ converted = _PYFORMAT_PLACEHOLDER_RE.sub(lambda match: f"${match.group('name')}", sql)
+ return converted, dict(values)
+
+
+def duckdb_type_to_clickhouse_type(duckdb_type: object | None) -> str:
+ # Function-local: keeps warehouse_sources model imports off this module's import path.
+ from products.warehouse_sources.backend.models.util import duckdb_to_clickhouse_type # noqa: PLC0415
+
+ if duckdb_type is None:
+ return "String"
+ return duckdb_to_clickhouse_type(str(duckdb_type))
+
+
+def motherduck_error_to_message(error: Exception) -> str:
+ # Deferred so the module imports without the driver loaded.
+ from products.warehouse_sources.backend.facade.source_management import translate_motherduck_error # noqa: PLC0415
+
+ return translate_motherduck_error(error)
+
+
+def _blocked_function_name(token: Token) -> str | None:
+ """The blocked-function name this token could resolve to, or None."""
+ if token.ttype in sqlparse_tokens.Name:
+ name = token.value.upper()
+ elif token.ttype in sqlparse_tokens.String.Symbol and len(token.value) >= 2:
+ # DuckDB resolves `"glob"(...)` to the same function as `glob(...)`.
+ name = token.value[1:-1].upper()
+ else:
+ return None
+ return name if name in _RAW_MOTHERDUCK_BLOCKED_FUNCTIONS else None
+
+
+def _opens_call(tokens: list[Token], index: int) -> bool:
+ """Whether the token at `index` is immediately followed by `(`, i.e. invoked as a function."""
+ for token in tokens[index + 1 :]:
+ if token.ttype in sqlparse_tokens.Whitespace or token.ttype in sqlparse_tokens.Comment:
+ continue
+ return token.ttype is sqlparse_tokens.Punctuation and token.value == "("
+ return False
+
+
+def ensure_read_only_raw_motherduck_statement(sql: str) -> str:
+ sql = ensure_single_direct_statement(sql)
+ statements = [statement for statement in sqlparse.parse(sql) if str(statement).strip(" \t\r\n;")]
+ if len(statements) != 1 or statements[0].get_type() != "SELECT":
+ raise ExposedHogQLError(RAW_MOTHERDUCK_READ_ONLY_ERROR)
+ # The connection itself is read-only (DuckDB rejects writes engine-side) and runs in
+ # MotherDuck's SaaS mode, so this gate is defense in depth for the raw passthrough path:
+ # reject DDL, any DML other than SELECT, and calls to the blocked functions above.
+ tokens = list(statements[0].flatten())
+ for index, token in enumerate(tokens):
+ if token.ttype in sqlparse_tokens.DDL:
+ raise ExposedHogQLError(RAW_MOTHERDUCK_READ_ONLY_ERROR)
+ if token.ttype in sqlparse_tokens.DML and token.value.upper() != "SELECT":
+ raise ExposedHogQLError(RAW_MOTHERDUCK_READ_ONLY_ERROR)
+ if _blocked_function_name(token) is not None and _opens_call(tokens, index):
+ raise ExposedHogQLError(RAW_MOTHERDUCK_BLOCKED_FUNCTION_ERROR)
+ return sql
+
+
+def _fetch_capped_motherduck_rows(connection: duckdb.DuckDBPyConnection) -> list:
+ """Fetch up to the row cap, raising if the result would exceed it.
+
+ Reads one row past the cap so the limit can be enforced without materializing the
+ entire result set first.
+ """
+ rows = connection.fetchmany(DIRECT_MOTHERDUCK_MAX_ROWS + 1)
+ if len(rows) > DIRECT_MOTHERDUCK_MAX_ROWS:
+ DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL.labels(dialect="motherduck").inc()
+ raise ExposedHogQLError(DIRECT_MOTHERDUCK_ROW_CAP_ERROR)
+ return list(rows)
+
+
+class _InterruptWatchdog:
+ """Cancel a running DuckDB query after a deadline.
+
+ DuckDB has no statement-timeout setting; `connection.interrupt()` is the supported way
+ to cancel from another thread, surfacing in the query thread as an InterruptException.
+ """
+
+ def __init__(self, connection: duckdb.DuckDBPyConnection, timeout_seconds: float) -> None:
+ self._fired = threading.Event()
+
+ def _interrupt() -> None:
+ self._fired.set()
+ try:
+ connection.interrupt()
+ except Exception:
+ pass
+
+ self._timer = threading.Timer(timeout_seconds, _interrupt)
+ self._timer.daemon = True
+
+ def __enter__(self) -> _InterruptWatchdog:
+ self._timer.start()
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ self._timer.cancel()
+
+ @property
+ def fired(self) -> bool:
+ return self._fired.is_set()
+
+
+class MotherDuckAdapter:
+ engine = "motherduck"
+ dialect: HogQLDialect | None = "duckdb"
+
+ def validate_source_config(
+ self, source: ExternalDataSource, team: Team
+ ) -> tuple[MotherduckSource, MotherduckSourceConfig]:
+ from products.warehouse_sources.backend.facade.source_management import SourceRegistry
+ from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
+
+ # Capability, not access_method: a synced source with the direct-query toggle on is valid too.
+ if not (is_direct_capable(source) and source.direct_engine == self.engine):
+ raise ExposedHogQLError("Invalid direct MotherDuck connection.")
+
+ motherduck_source = cast("MotherduckSource", SourceRegistry.get_source(ExternalDataSourceType.MOTHERDUCK))
+ config = motherduck_source.parse_config(source.job_inputs or {})
+
+ # No host/SSH-tunnel config to validate: the driver always dials MotherDuck's fixed
+ # SaaS endpoint, so there is no SSRF surface equivalent to the Postgres/MySQL hosts.
+ if not (config.access_token or "").strip():
+ raise ExposedHogQLError("This MotherDuck connection has no access token configured.")
+
+ return motherduck_source, config
+
+ def prepare_raw_sql(self, sql: str) -> str:
+ return ensure_read_only_raw_motherduck_statement(sql)
+
+ def execute(self, request: DirectQueryRequest) -> DirectQueryResult:
+ """Execute a single read-only statement against the source's MotherDuck account.
+
+ Read-only is enforced engine-side: the connection is opened with `read_only=True`
+ (DuckDB rejects every write statement) and `saas_mode=true` (no local filesystem, no
+ extension installs). `prepare_raw_sql` additionally gates raw SQL to a single SELECT.
+ """
+ import duckdb # noqa: PLC0415 — keeps the heavy dep off the import path
+
+ from products.warehouse_sources.backend.facade.source_management import ( # noqa: PLC0415
+ MotherDuckConnectionError,
+ )
+
+ source = request.source
+ motherduck_source, source_config = self.validate_source_config(source, request.team)
+ settings = request.settings
+ statement_timeout_seconds = max(
+ settings.max_execution_time or DIRECT_MOTHERDUCK_DEFAULT_STATEMENT_TIMEOUT_SECONDS, 1
+ )
+
+ span = trace.get_current_span()
+ span.set_attribute("team_id", request.team.pk)
+ span.set_attribute("query_type", request.query_type)
+ span.set_attribute("source_id", str(source.id))
+
+ sql, values = convert_pyformat_placeholders(request.sql, request.values)
+
+ try:
+ with request.timings.measure("motherduck_execute"), observe_direct_query("motherduck"):
+ # Reuse a per-thread connection across queries — the extension load + WebSocket
+ # handshake is the dominant cost for interactive use.
+ with cached_motherduck_connection(motherduck_source, source_config) as connection:
+ with _InterruptWatchdog(connection, statement_timeout_seconds) as watchdog:
+ try:
+ connection.execute(sql, values or None)
+ results = _fetch_capped_motherduck_rows(connection)
+ except duckdb.InterruptException:
+ if watchdog.fired:
+ raise ExposedHogQLError(DIRECT_MOTHERDUCK_TIMEOUT_ERROR) from None
+ raise
+ description = connection.description or []
+ except (duckdb.Error, MotherDuckConnectionError, ExposedHogQLError) as error:
+ span.set_attribute("error_type", error.__class__.__name__)
+ # A failed cold connect already arrives translated; only raw driver errors need it.
+ message = str(error) if isinstance(error, MotherDuckConnectionError) else motherduck_error_to_message(error)
+ if request.debug:
+ return DirectQueryResult(results=[], types=[], print_columns=[], error=message)
+ if isinstance(error, ExposedHogQLError):
+ raise
+ raise ExposedHogQLError(message) from error
+
+ span.set_attribute("row_count", len(results))
+ types: list[tuple[str, str]] = [
+ (column[0], duckdb_type_to_clickhouse_type(column[1])) for column in description
+ ]
+ print_columns = [column[0] for column in description]
+ return DirectQueryResult(results=results, types=types, print_columns=print_columns)
diff --git a/posthog/hogql/direct_sql/test/test_motherduck_adapter.py b/posthog/hogql/direct_sql/test/test_motherduck_adapter.py
new file mode 100644
index 000000000000..022b7fdc2160
--- /dev/null
+++ b/posthog/hogql/direct_sql/test/test_motherduck_adapter.py
@@ -0,0 +1,301 @@
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+import duckdb
+from parameterized import parameterized
+
+from posthog.hogql.constants import HogQLDialect
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
+from posthog.hogql.database.direct_motherduck_table import DirectMotherDuckTable
+from posthog.hogql.database.models import StringDatabaseField, TableNode
+from posthog.hogql.direct_sql.motherduck_adapter import (
+ _fetch_capped_motherduck_rows,
+ convert_pyformat_placeholders,
+ duckdb_type_to_clickhouse_type,
+ ensure_read_only_raw_motherduck_statement,
+)
+from posthog.hogql.errors import ExposedHogQLError, QueryError
+from posthog.hogql.parser import parse_select
+from posthog.hogql.printer.utils import prepare_and_print_ast
+
+
+def _table(**overrides) -> DirectMotherDuckTable:
+ kwargs = {
+ "name": "taxi",
+ "fields": {},
+ "motherduck_database": "sample_data",
+ "motherduck_schema": "nyc",
+ "motherduck_table_name": "taxi",
+ "external_data_source_id": "src",
+ **overrides,
+ }
+ return DirectMotherDuckTable(**kwargs)
+
+
+class TestDirectMotherDuckTable(SimpleTestCase):
+ def test_renders_quoted_three_part_name(self):
+ # Safe lowercase identifiers stay bare (the escaper quotes only when needed).
+ self.assertEqual(_table().to_printed_duckdb(None), "sample_data.nyc.taxi")
+
+ def test_escapes_special_identifiers(self):
+ table = _table(motherduck_database='my"db', motherduck_table_name="weird.name")
+ self.assertEqual(table.to_printed_duckdb(None), '"my""db".nyc."weird.name"')
+
+ def test_requires_database_and_schema(self):
+ with self.assertRaises(QueryError):
+ _table(motherduck_database=" ").to_printed_duckdb(None)
+ with self.assertRaises(QueryError):
+ _table(motherduck_schema="").to_printed_duckdb(None)
+
+ def test_refuses_other_dialects(self):
+ with self.assertRaises(QueryError):
+ _table().to_printed_postgres(None)
+ with self.assertRaises(QueryError):
+ _table().to_printed_clickhouse(None)
+
+ def test_resolves_fields_case_insensitively(self):
+ # DuckDB resolves identifiers case-insensitively while preserving stored case; a HogQL
+ # query typing `VendorID` as `vendorid` must resolve to the stored column.
+ table = _table(fields={"VendorID": StringDatabaseField(name="VendorID")})
+ self.assertTrue(table.has_field("vendorid"))
+ field = table.get_field("VENDORID")
+ assert isinstance(field, StringDatabaseField)
+ self.assertEqual(field.name, "VendorID")
+
+
+class TestDirectMotherDuckPrinting(BaseTest):
+ def _print(self, *, is_direct_query: bool, dialect: HogQLDialect = "duckdb") -> str:
+ table = _table(fields={"fare_amount": StringDatabaseField(name="fare_amount")})
+ database = Database()
+ root = TableNode()
+ root.add_child(TableNode(name="taxi", table=table))
+ database._add_warehouse_tables(root)
+ context = HogQLContext(
+ team_id=self.team.pk,
+ enable_select_queries=True,
+ database=database,
+ is_direct_query=is_direct_query,
+ )
+ return prepare_and_print_ast(parse_select("SELECT fare_amount FROM taxi"), context, dialect)[0]
+
+ def test_direct_query_prints_qualified_table_in_duckdb_dialect(self):
+ printed = self._print(is_direct_query=True)
+ self.assertIn("sample_data.nyc.taxi", printed)
+ self.assertNotIn("team_id", printed)
+
+ def test_refuses_external_table_in_clickhouse_dialect(self):
+ # Our own cluster must never be asked to resolve a customer's MotherDuck table.
+ with self.assertRaises(QueryError):
+ self._print(is_direct_query=False, dialect="clickhouse")
+
+
+class TestMotherDuckReadOnlyGuard(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("select", "SELECT * FROM sample_data.nyc.taxi"),
+ ("with_cte", "WITH x AS (SELECT 1) SELECT * FROM x"),
+ ("lowercase", "select count(*) from taxi"),
+ ("leading_comment", "-- hi\nSELECT 1"),
+ # A column named like a blocked function is an identifier in quotes — allowed.
+ ("quoted_column_named_glob", 'SELECT "glob" FROM taxi'),
+ ("string_literal", "SELECT 'read_csv' AS label"),
+ # Blocked names are only rejected in call position, so these stay usable as columns.
+ ("column_named_query", "SELECT query FROM request_log"),
+ ("qualified_column_named_query", "SELECT t.query, t.duration FROM request_log t"),
+ ]
+ )
+ def test_allows_read_only(self, _name, sql):
+ self.assertEqual(ensure_read_only_raw_motherduck_statement(sql), sql)
+
+ @parameterized.expand(
+ [
+ ("insert", "INSERT INTO taxi VALUES (1)"),
+ ("update", "UPDATE taxi SET fare_amount = 0"),
+ ("delete", "DELETE FROM taxi"),
+ ("drop", "DROP TABLE taxi"),
+ ("create", "CREATE TABLE t (x INT)"),
+ ("attach", "ATTACH 'md:other_db'"),
+ ("copy", "COPY taxi TO 'out.parquet'"),
+ ("install", "INSTALL httpfs"),
+ ("pragma", "PRAGMA database_list"),
+ ("multi_statement", "SELECT 1; DROP TABLE taxi"),
+ ("with_prefixed_insert", "WITH x AS (SELECT 1) INSERT INTO taxi SELECT * FROM x"),
+ ]
+ )
+ def test_rejects_writes_and_non_selects(self, _name, sql):
+ with self.assertRaises(ExposedHogQLError):
+ ensure_read_only_raw_motherduck_statement(sql)
+
+ @parameterized.expand(
+ [
+ ("read_csv", "SELECT * FROM read_csv('/etc/passwd')"),
+ ("read_parquet", "SELECT * FROM read_parquet('secrets.parquet')"),
+ ("read_text", "SELECT * FROM read_text('/etc/hosts')"),
+ ("glob", "SELECT * FROM glob('/*')"),
+ ("getenv", "SELECT getenv('AWS_SECRET_ACCESS_KEY')"),
+ ("uppercase", "SELECT * FROM READ_CSV('/etc/passwd')"),
+ ("nested", "SELECT * FROM (SELECT * FROM read_json_auto('x.json'))"),
+ # DuckDB resolves a quoted identifier to the same function.
+ ("quoted_call", "SELECT * FROM \"read_csv\"('/etc/passwd')"),
+ ]
+ )
+ def test_rejects_environment_reading_functions(self, _name, sql):
+ with self.assertRaises(ExposedHogQLError):
+ ensure_read_only_raw_motherduck_statement(sql)
+
+ @parameterized.expand(
+ [
+ # `query()` runs its string argument as a statement, so the outer SELECT gate alone
+ # would let `PRAGMA PRINT_MD_TOKEN` return the source's MotherDuck token.
+ ("query_pragma_token", "SELECT * FROM query('PRAGMA PRINT_MD_TOKEN')"),
+ ("query_table", "SELECT * FROM query_table('taxi')"),
+ # The token travels in the DSN and lands as a readable DuckDB setting.
+ ("current_setting", "SELECT current_setting('motherduck_token')"),
+ ("duckdb_settings", "SELECT value FROM duckdb_settings() WHERE name = 'motherduck_token'"),
+ ("duckdb_secrets", "SELECT * FROM duckdb_secrets()"),
+ ]
+ )
+ def test_rejects_credential_revealing_functions(self, _name, sql):
+ with self.assertRaises(ExposedHogQLError):
+ ensure_read_only_raw_motherduck_statement(sql)
+
+
+class TestPlaceholderConversion(SimpleTestCase):
+ def test_converts_named_placeholders(self):
+ sql, values = convert_pyformat_placeholders(
+ "SELECT * FROM t WHERE a = %(hogql_val_0)s AND b = %(hogql_val_1)s",
+ {"hogql_val_0": "x", "hogql_val_1": 2},
+ )
+ self.assertEqual(sql, "SELECT * FROM t WHERE a = $hogql_val_0 AND b = $hogql_val_1")
+ self.assertEqual(values, {"hogql_val_0": "x", "hogql_val_1": 2})
+
+ def test_leaves_sql_untouched_without_values(self):
+ # Raw passthrough SQL runs with no bound values; a literal `%(` in a string constant
+ # must survive verbatim.
+ sql, values = convert_pyformat_placeholders("SELECT '%(not_a_param)s'", None)
+ self.assertEqual(sql, "SELECT '%(not_a_param)s'")
+ self.assertEqual(values, {})
+
+
+class TestDuckDBTypeMapping(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("BIGINT", "Int64"),
+ ("INTEGER", "Int32"),
+ ("UBIGINT", "UInt64"),
+ ("DOUBLE", "Float64"),
+ ("DECIMAL(10,2)", "Decimal"),
+ ("VARCHAR", "String"),
+ ("BOOLEAN", "Bool"),
+ ("DATE", "Date32"),
+ ("TIMESTAMP", "DateTime64(6)"),
+ ("TIMESTAMP WITH TIME ZONE", "DateTime64(6, 'UTC')"),
+ ("UUID", "UUID"),
+ # Nested / exotic types round-trip as strings, including arrays whose element
+ # type would otherwise match the scalar decimal/timestamp fallbacks.
+ ("STRUCT(a INTEGER)", "String"),
+ ("INTEGER[]", "String"),
+ ("DECIMAL(18,3)[]", "String"),
+ ("TIMESTAMP[]", "String"),
+ ("JSON", "String"),
+ (None, "String"),
+ ]
+ )
+ def test_maps_duckdb_types(self, duckdb_type, expected):
+ self.assertEqual(duckdb_type_to_clickhouse_type(duckdb_type), expected)
+
+
+class TestMotherDuckRowCap(SimpleTestCase):
+ def test_returns_rows_under_cap(self):
+ connection = duckdb.connect(":memory:")
+ connection.execute("SELECT * FROM range(3)")
+ self.assertEqual(_fetch_capped_motherduck_rows(connection), [(0,), (1,), (2,)])
+
+ def test_raises_when_result_exceeds_cap(self):
+ connection = duckdb.connect(":memory:")
+ connection.execute("SELECT * FROM range(10)")
+ with patch("posthog.hogql.direct_sql.motherduck_adapter.DIRECT_MOTHERDUCK_MAX_ROWS", 3):
+ with self.assertRaisesRegex(ExposedHogQLError, "Add a LIMIT clause"):
+ _fetch_capped_motherduck_rows(connection)
+
+
+class TestMotherDuckAdapterExecute(BaseTest):
+ def _request(self, sql: str, values: dict | None = None):
+ from posthog.hogql.constants import HogQLGlobalSettings
+ from posthog.hogql.direct_sql.adapter import DirectQueryRequest
+ from posthog.hogql.timings import HogQLTimings
+
+ from products.warehouse_sources.backend.facade.models import ExternalDataSource
+
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_type="Motherduck",
+ access_method=ExternalDataSource.AccessMethod.DIRECT,
+ job_inputs={"access_token": "test-token", "database": "memory"},
+ source_id="motherduck-test",
+ connection_id="motherduck-test",
+ )
+ return DirectQueryRequest(
+ source=source,
+ team=self.team,
+ sql=sql,
+ values=values,
+ settings=HogQLGlobalSettings(max_execution_time=60),
+ timings=HogQLTimings(),
+ query_type="HogQLQuery",
+ debug=False,
+ )
+
+ def test_executes_with_placeholder_conversion_and_typed_results(self):
+ from contextlib import contextmanager
+
+ from posthog.hogql.direct_sql.motherduck_adapter import MotherDuckAdapter
+
+ connection = duckdb.connect(":memory:")
+ connection.execute("CREATE TABLE t (n BIGINT, label VARCHAR, created TIMESTAMP)")
+ connection.execute("INSERT INTO t VALUES (1, 'a', '2026-01-01'), (2, 'b', '2026-01-02')")
+
+ @contextmanager
+ def fake_cache(token, database):
+ yield connection
+
+ request = self._request("SELECT n, label, created FROM t WHERE label = %(hogql_val_0)s", {"hogql_val_0": "b"})
+ with patch("posthog.hogql.direct_sql.motherduck_adapter.cached_motherduck_connection", fake_cache):
+ result = MotherDuckAdapter().execute(request)
+
+ self.assertEqual(len(result.results), 1)
+ self.assertEqual(result.results[0][0], 2)
+ self.assertEqual(result.print_columns, ["n", "label", "created"])
+ self.assertEqual(result.types, [("n", "Int64"), ("label", "String"), ("created", "DateTime64(6)")])
+
+ def test_sql_errors_surface_as_exposed_errors(self):
+ from contextlib import contextmanager
+
+ from posthog.hogql.direct_sql.motherduck_adapter import MotherDuckAdapter
+
+ connection = duckdb.connect(":memory:")
+
+ @contextmanager
+ def fake_cache(token, database):
+ yield connection
+
+ request = self._request("SELECT * FROM missing_table")
+ with patch("posthog.hogql.direct_sql.motherduck_adapter.cached_motherduck_connection", fake_cache):
+ with self.assertRaises(ExposedHogQLError):
+ MotherDuckAdapter().execute(request)
+
+ def test_failed_connect_surfaces_its_translated_message(self):
+ from posthog.hogql.direct_sql.motherduck_adapter import MotherDuckAdapter
+
+ from products.warehouse_sources.backend.facade.source_management import MotherDuckConnectionError
+
+ request = self._request("SELECT 1")
+ with patch(
+ "posthog.hogql.direct_sql.motherduck_adapter.cached_motherduck_connection",
+ side_effect=MotherDuckConnectionError("Invalid MotherDuck token."),
+ ):
+ with self.assertRaisesRegex(ExposedHogQLError, "Invalid MotherDuck token."):
+ MotherDuckAdapter().execute(request)
diff --git a/posthog/hogql/direct_sql/test/test_registry_and_capability.py b/posthog/hogql/direct_sql/test/test_registry_and_capability.py
index f337adf872f2..8ba6a2b093df 100644
--- a/posthog/hogql/direct_sql/test/test_registry_and_capability.py
+++ b/posthog/hogql/direct_sql/test/test_registry_and_capability.py
@@ -26,7 +26,9 @@ class TestDirectSQLRegistry(SimpleTestCase):
self.assertIsNone(get_adapter(engine))
def test_registered_engines_includes_all_engines(self):
- self.assertEqual({"postgres", "mysql", "snowflake", "redshift", "clickhouse"}, set(registered_engines()))
+ self.assertEqual(
+ {"postgres", "mysql", "snowflake", "redshift", "clickhouse", "motherduck"}, set(registered_engines())
+ )
def test_clickhouse_adapter_compiles_hogql(self):
adapter = get_adapter("clickhouse")
@@ -58,6 +60,8 @@ class TestDirectSQLCapability(SimpleTestCase):
("clickhouse_synced_enabled", ExternalDataSourceType.CLICKHOUSE, "warehouse", True, True),
("clickhouse_synced_disabled", ExternalDataSourceType.CLICKHOUSE, "warehouse", False, False),
("clickhousecloud_direct", ExternalDataSourceType.CLICKHOUSECLOUD, "direct", False, True),
+ ("motherduck_direct_ignores_toggle", ExternalDataSourceType.MOTHERDUCK, "direct", False, True),
+ ("motherduck_synced_enabled", ExternalDataSourceType.MOTHERDUCK, "warehouse", True, True),
("unmapped_engine_synced", ExternalDataSourceType.STRIPE, "warehouse", True, False),
("unmapped_engine_direct", ExternalDataSourceType.STRIPE, "direct", True, False),
]
@@ -79,6 +83,7 @@ class TestDirectSQLCapability(SimpleTestCase):
ExternalDataSourceType.REDSHIFT,
ExternalDataSourceType.CLICKHOUSE,
ExternalDataSourceType.CLICKHOUSECLOUD,
+ ExternalDataSourceType.MOTHERDUCK,
},
set(direct_capable_source_types()),
)
diff --git a/posthog/hogql/motherduck_connection_cache.py b/posthog/hogql/motherduck_connection_cache.py
new file mode 100644
index 000000000000..d0745b195019
--- /dev/null
+++ b/posthog/hogql/motherduck_connection_cache.py
@@ -0,0 +1,160 @@
+"""Thread-local connection cache for direct MotherDuck queries.
+
+Opening a MotherDuck connection loads the `motherduck` DuckDB extension and completes a
+WebSocket handshake — routinely seconds — which dominates latency for the interactive SQL
+editor where a user issues many small queries in sequence. This caches one open connection
+per (token + database) per worker thread, reusing it across queries and reopening lazily
+when it expires, dies, or is evicted.
+
+Same scope choices as the Snowflake cache: direct-query path only (the data-import
+pipeline opens its own short-lived connections per sync), and thread-local because a
+DuckDB connection must not be shared across threads mid-query.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import threading
+from collections import OrderedDict
+from collections.abc import Iterator
+from contextlib import AbstractContextManager, contextmanager
+from time import monotonic
+from typing import TYPE_CHECKING
+
+from posthog.hogql.direct_query_metrics import DIRECT_CONNECTION_CACHE_TOTAL
+
+from posthog.dataclasses import frozen
+
+if TYPE_CHECKING:
+ import duckdb
+
+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.motherduck import (
+ MotherduckSourceConfig,
+ )
+ from products.warehouse_sources.backend.temporal.data_imports.sources.motherduck.source import MotherduckSource
+
+
+MOTHERDUCK_CONNECTION_CACHE_TTL_SECONDS = 1800
+# Bound per-thread connection count so a worker that touches many distinct sources
+# can't accumulate open sessions without limit.
+MOTHERDUCK_CONNECTION_CACHE_MAX_PER_THREAD = 4
+# On a warm connection the probe is a single round trip, so a couple of seconds means the
+# session is gone; anything slower should read as dead rather than block the request thread.
+MOTHERDUCK_LIVENESS_PROBE_TIMEOUT_SECONDS = 5
+
+
+@frozen
+class _Entry:
+ cm: AbstractContextManager[duckdb.DuckDBPyConnection]
+ connection: duckdb.DuckDBPyConnection
+ opened_at: float
+
+
+_thread_local = threading.local()
+
+
+def _cache() -> OrderedDict[str, _Entry]:
+ cache = getattr(_thread_local, "cache", None)
+ if cache is None:
+ cache = OrderedDict()
+ _thread_local.cache = cache
+ return cache
+
+
+def _config_key(token: str, database: str | None) -> str:
+ # Hash the token rather than carry it in the key. Keying on the credential means a
+ # rotation routes to a fresh connection automatically (the old entry just expires).
+ token_digest = hashlib.sha256(token.encode("utf-8")).hexdigest()
+ return hashlib.sha256(f"{token_digest}\x00{database or ''}".encode()).hexdigest()
+
+
+def _close_entry(entry: _Entry) -> None:
+ try:
+ entry.cm.__exit__(None, None, None)
+ except Exception:
+ pass
+
+
+def _evict(key: str) -> None:
+ entry = _cache().pop(key, None)
+ if entry is not None:
+ _close_entry(entry)
+
+
+def _interrupt_quietly(connection: duckdb.DuckDBPyConnection) -> None:
+ try:
+ connection.interrupt()
+ except Exception:
+ pass
+
+
+def _is_reusable(entry: _Entry, now: float) -> bool:
+ if now - entry.opened_at >= MOTHERDUCK_CONNECTION_CACHE_TTL_SECONDS:
+ return False
+ # Cheap liveness probe. A cleanly-closed socket raises immediately, but a half-open one
+ # (remote gone without FIN/RST) can block the read until an OS-level timeout, so a timer
+ # interrupts the probe after a short deadline and the connection reads as dead.
+ timer = threading.Timer(MOTHERDUCK_LIVENESS_PROBE_TIMEOUT_SECONDS, _interrupt_quietly, args=(entry.connection,))
+ timer.daemon = True
+ timer.start()
+ try:
+ entry.connection.execute("SELECT 1")
+ return True
+ except Exception:
+ return False
+ finally:
+ timer.cancel()
+
+
+@contextmanager
+def cached_motherduck_connection(
+ source: MotherduckSource,
+ config: MotherduckSourceConfig,
+) -> Iterator[duckdb.DuckDBPyConnection]:
+ """Yield a cached open read-only MotherDuck connection for this thread.
+
+ The connection is kept open after the block exits so the next query on the same thread
+ can reuse it. It is dropped (and reopened next time) on expiry, when found dead, on LRU
+ eviction, or when the block raises a connection-level error.
+ """
+ # Function-local: keeps the duckdb driver off the django.setup() path.
+ import duckdb # noqa: PLC0415
+
+ key = _config_key(config.access_token, source.normalized_database(config))
+ cache = _cache()
+ now = monotonic()
+
+ entry = cache.get(key)
+ if entry is not None and _is_reusable(entry, now):
+ cache.move_to_end(key)
+ connection = entry.connection
+ DIRECT_CONNECTION_CACHE_TOTAL.labels(engine="motherduck", result="reused").inc()
+ else:
+ if entry is not None:
+ _evict(key)
+ # Drive the source's own connection contextmanager but keep it entered, so the
+ # read-only/SaaS-mode connection settings stay owned by the source.
+ cm = source.direct_query_connection(config)
+ connection = cm.__enter__()
+ cache[key] = _Entry(cm=cm, connection=connection, opened_at=now)
+ DIRECT_CONNECTION_CACHE_TOTAL.labels(engine="motherduck", result="opened").inc()
+ while len(cache) > MOTHERDUCK_CONNECTION_CACHE_MAX_PER_THREAD:
+ _old_key, old_entry = cache.popitem(last=False)
+ _close_entry(old_entry)
+
+ try:
+ yield connection
+ except duckdb.Error as error:
+ # SQL-level errors (Binder, Catalog, Parser) leave the connection healthy; anything
+ # transport-shaped means the cached session is suspect.
+ if isinstance(error, duckdb.IOException | duckdb.ConnectionException | duckdb.FatalException):
+ _evict(key)
+ raise
+
+
+def clear_thread_local_motherduck_connections() -> None:
+ """Close and drop every cached connection for the current thread (tests, shutdown)."""
+ cache = _cache()
+ for entry in list(cache.values()):
+ _close_entry(entry)
+ cache.clear()
diff --git a/posthog/hogql/printer/duckdb.py b/posthog/hogql/printer/duckdb.py
index 5a914cb5d7be..32a27070b445 100644
--- a/posthog/hogql/printer/duckdb.py
+++ b/posthog/hogql/printer/duckdb.py
@@ -48,6 +48,18 @@ class DuckDBPrinter(PostgresPrinter):
}
self._jsonpath_placeholders: dict[str, str] = {}
+ def _print_table_sql(self, table) -> str:
+ # Direct MotherDuck tables render as `db.schema.table`; everything else keeps the
+ # inherited Postgres-wire rendering (DuckDB shares its quoting rules).
+ if hasattr(table, "to_printed_duckdb"):
+ return table.to_printed_duckdb(self.context)
+ return super()._print_table_sql(table)
+
+ def _print_table(self, table) -> str:
+ if hasattr(table, "to_printed_duckdb"):
+ return table.to_printed_duckdb(self.context)
+ return super()._print_table(table)
+
def _print_identifier(self, name: str) -> str:
# DuckDB has no practical identifier length limit, so skip the Postgres
# 63-character truncation (which introduces SHA-suffixed names that are
diff --git a/posthog/hogql/test/test_direct_motherduck_query.py b/posthog/hogql/test/test_direct_motherduck_query.py
new file mode 100644
index 000000000000..00766117bdcf
--- /dev/null
+++ b/posthog/hogql/test/test_direct_motherduck_query.py
@@ -0,0 +1,204 @@
+from uuid import uuid4
+
+import unittest
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+import duckdb
+from parameterized import parameterized
+
+from posthog.hogql.errors import ExposedHogQLError
+from posthog.hogql.motherduck_connection_cache import (
+ cached_motherduck_connection,
+ clear_thread_local_motherduck_connections,
+)
+from posthog.hogql.query import HogQLQueryExecutor
+
+from products.data_warehouse.backend.facade.api import DIRECT_MOTHERDUCK_URL_PATTERN
+from products.data_warehouse.backend.facade.sources import (
+ DIRECT_MOTHERDUCK_CATALOG_OPTION,
+ DIRECT_MOTHERDUCK_SCHEMA_OPTION,
+ DIRECT_MOTHERDUCK_TABLE_OPTION,
+)
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource
+from products.warehouse_sources.backend.facade.source_management import SourceRegistry
+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
+
+# Patched where it is used: the direct-query path reaches the driver through the name
+# `source.py` binds, so patching the transport module it came from would not intercept.
+_TRANSPORT_CONNECT = "products.warehouse_sources.backend.temporal.data_imports.sources.motherduck.source.connect"
+
+
+def _source_and_config(token: str = "token", database: str = "db"):
+ """The (source, config) pair the adapter hands the cache, built the same way it does."""
+ source = SourceRegistry.get_source(ExternalDataSourceType.MOTHERDUCK)
+ return source, source.parse_config({"access_token": token, "database": database})
+
+
+def _local_duckdb(*_args, **_kwargs) -> duckdb.DuckDBPyConnection:
+ connection = duckdb.connect(":memory:")
+ connection.execute("CREATE SCHEMA nyc")
+ connection.execute("CREATE TABLE nyc.taxi (trip_id BIGINT, fare DOUBLE, city VARCHAR)")
+ connection.execute("INSERT INTO nyc.taxi VALUES (1, 10.5, 'ny'), (2, 20.0, 'sf'), (3, 30.0, 'ny')")
+ return connection
+
+
+class TestDirectMotherDuckQuery(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ # The connection cache is thread-local module state; isolate each test.
+ clear_thread_local_motherduck_connections()
+ self.addCleanup(clear_thread_local_motherduck_connections)
+
+ def _create_source(self) -> ExternalDataSource:
+ return ExternalDataSource.objects.create(
+ team=self.team,
+ source_id=str(uuid4()),
+ connection_id=str(uuid4()),
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type="Motherduck",
+ access_method=ExternalDataSource.AccessMethod.DIRECT,
+ prefix="md",
+ connection_metadata={"engine": "motherduck", "database": "memory"},
+ job_inputs={"access_token": "test-token", "database": "memory"},
+ )
+
+ def _create_direct_table(self, source: ExternalDataSource) -> DataWarehouseTable:
+ return DataWarehouseTable.objects.create(
+ name="nyc.taxi",
+ team=self.team,
+ format=DataWarehouseTable.TableFormat.Parquet,
+ url_pattern=DIRECT_MOTHERDUCK_URL_PATTERN,
+ external_data_source=source,
+ columns={
+ "trip_id": {"clickhouse": "Int64", "hogql": "IntegerDatabaseField", "valid": True},
+ "fare": {"clickhouse": "Float64", "hogql": "FloatDatabaseField", "valid": True},
+ "city": {"clickhouse": "String", "hogql": "StringDatabaseField", "valid": True},
+ },
+ options={
+ DIRECT_MOTHERDUCK_CATALOG_OPTION: "memory",
+ DIRECT_MOTHERDUCK_SCHEMA_OPTION: "nyc",
+ DIRECT_MOTHERDUCK_TABLE_OPTION: "taxi",
+ },
+ )
+
+ def test_hogql_query_compiles_to_duckdb_and_executes(self):
+ source = self._create_source()
+ self._create_direct_table(source)
+
+ executor = HogQLQueryExecutor(
+ query="SELECT trip_id, fare FROM `nyc.taxi` WHERE city = 'ny' ORDER BY trip_id",
+ team=self.team,
+ connection_id=str(source.id),
+ )
+ with patch(_TRANSPORT_CONNECT, side_effect=_local_duckdb):
+ response = executor.execute()
+
+ self.assertEqual(executor.direct_dialect, "duckdb")
+ # The compiled SQL targets the physical three-part location, with the constant bound
+ # as a converted `$name` parameter rather than inlined.
+ self.assertIn("nyc.taxi", executor.direct_sql or "")
+ self.assertEqual(response.results, [(1, 10.5), (3, 30.0)])
+ self.assertEqual(response.types, [("trip_id", "Int64"), ("fare", "Float64")])
+
+ def test_raw_query_executes_against_duckdb(self):
+ source = self._create_source()
+
+ executor = HogQLQueryExecutor(
+ query="SELECT count(*) AS n, min(city) AS c FROM memory.nyc.taxi",
+ team=self.team,
+ connection_id=str(source.id),
+ send_raw_query=True,
+ )
+ with patch(_TRANSPORT_CONNECT, side_effect=_local_duckdb):
+ with patch.object(HogQLQueryExecutor, "_capture_send_raw_query_translation_error"):
+ response = executor.execute()
+
+ self.assertEqual(response.results, [(3, "ny")])
+ self.assertEqual(response.types, [("n", "Int64"), ("c", "String")])
+
+ @parameterized.expand(
+ [
+ ("insert", "INSERT INTO nyc.taxi VALUES (9, 1.0, 'x')"),
+ ("attach", "ATTACH 'md:other_db'"),
+ ("read_csv", "SELECT * FROM read_csv('/etc/passwd')"),
+ ("multi_statement", "SELECT 1; DROP TABLE nyc.taxi"),
+ ]
+ )
+ def test_raw_query_rejects_unsafe_statements_before_connecting(self, _name: str, query: str):
+ source = self._create_source()
+
+ executor = HogQLQueryExecutor(
+ query=query,
+ team=self.team,
+ connection_id=str(source.id),
+ send_raw_query=True,
+ )
+
+ with patch(
+ "posthog.hogql.direct_sql.motherduck_adapter.MotherDuckAdapter.validate_source_config"
+ ) as mock_validate:
+ with self.assertRaises(ExposedHogQLError):
+ executor.execute()
+
+ # The statement is rejected before any connection is opened.
+ mock_validate.assert_not_called()
+ self.assertIsNone(executor.direct_sql)
+
+
+class TestMotherDuckConnectionCache(unittest.TestCase):
+ def setUp(self):
+ clear_thread_local_motherduck_connections()
+ self.addCleanup(clear_thread_local_motherduck_connections)
+
+ def test_reuses_connection_across_calls(self):
+ with patch(_TRANSPORT_CONNECT, side_effect=lambda *a, **k: duckdb.connect(":memory:")) as mock_connect:
+ with cached_motherduck_connection(*_source_and_config()) as first:
+ pass
+ with cached_motherduck_connection(*_source_and_config()) as second:
+ pass
+ self.assertIs(first, second)
+ mock_connect.assert_called_once()
+
+ def test_reopens_after_ttl(self):
+ with patch(_TRANSPORT_CONNECT, side_effect=lambda *a, **k: duckdb.connect(":memory:")) as mock_connect:
+ with patch("posthog.hogql.motherduck_connection_cache.MOTHERDUCK_CONNECTION_CACHE_TTL_SECONDS", 0):
+ with cached_motherduck_connection(*_source_and_config()):
+ pass
+ with cached_motherduck_connection(*_source_and_config()):
+ pass
+ self.assertEqual(mock_connect.call_count, 2)
+
+ def test_reopens_when_connection_found_dead(self):
+ with patch(_TRANSPORT_CONNECT, side_effect=lambda *a, **k: duckdb.connect(":memory:")) as mock_connect:
+ with cached_motherduck_connection(*_source_and_config()) as connection:
+ pass
+ connection.close()
+ with cached_motherduck_connection(*_source_and_config()):
+ pass
+ self.assertEqual(mock_connect.call_count, 2)
+
+ def test_evicts_on_transport_error_keeps_on_sql_error(self):
+ with patch(_TRANSPORT_CONNECT, side_effect=lambda *a, **k: duckdb.connect(":memory:")) as mock_connect:
+ # A SQL-level error (bad table) leaves the connection cached...
+ with self.assertRaises(duckdb.Error):
+ with cached_motherduck_connection(*_source_and_config()) as connection:
+ connection.execute("SELECT * FROM missing_table")
+ with cached_motherduck_connection(*_source_and_config()):
+ pass
+ self.assertEqual(mock_connect.call_count, 1)
+ # ...while a transport-shaped error evicts it.
+ with self.assertRaises(duckdb.IOException):
+ with cached_motherduck_connection(*_source_and_config()):
+ raise duckdb.IOException("socket closed")
+ with cached_motherduck_connection(*_source_and_config()):
+ pass
+ self.assertEqual(mock_connect.call_count, 2)
+
+ def test_different_tokens_use_separate_connections(self):
+ with patch(_TRANSPORT_CONNECT, side_effect=lambda *a, **k: duckdb.connect(":memory:")) as mock_connect:
+ with cached_motherduck_connection(*_source_and_config("token-a")):
+ pass
+ with cached_motherduck_connection(*_source_and_config("token-b")):
+ pass
+ self.assertEqual(mock_connect.call_count, 2)
diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.py
index d57f13e61736..9b109032269b 100644
--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py
+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py
@@ -18,6 +18,7 @@ if TYPE_CHECKING:
from posthog.hogql import ast
from posthog.hogql.database.database import Database
from posthog.hogql.database.direct_clickhouse_table import DirectClickHouseTable
+from posthog.hogql.database.direct_motherduck_table import DirectMotherDuckTable
from posthog.hogql.database.direct_mysql_table import DirectMySQLTable
from posthog.hogql.database.direct_postgres_table import DirectPostgresTable
from posthog.hogql.database.direct_redshift_table import DirectRedshiftTable
@@ -480,6 +481,7 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,
DirectSnowflakeTable,
DirectRedshiftTable,
DirectClickHouseTable,
+ DirectMotherDuckTable,
]:
if self.table is not None and self.is_materialized and modifiers is not None and modifiers.useMaterializedViews:
return self.table.hogql_definition(modifiers)
diff --git a/products/data_warehouse/backend/direct_motherduck.py b/products/data_warehouse/backend/direct_motherduck.py
new file mode 100644
index 000000000000..63000a97799b
--- /dev/null
+++ b/products/data_warehouse/backend/direct_motherduck.py
@@ -0,0 +1,87 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+from products.warehouse_sources.backend.facade.models import ExternalDataSource
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.models.table import DataWarehouseTable
+
+type DirectMotherDuckColumns = dict[str, dict[str, Any]]
+
+
+DIRECT_MOTHERDUCK_URL_PATTERN = "direct://motherduck"
+DIRECT_MOTHERDUCK_CATALOG_OPTION = "direct_motherduck_catalog"
+DIRECT_MOTHERDUCK_SCHEMA_OPTION = "direct_motherduck_schema"
+DIRECT_MOTHERDUCK_TABLE_OPTION = "direct_motherduck_table"
+
+
+def get_direct_motherduck_table_options(
+ *, source_catalog: str | None = None, source_schema: str, source_table_name: str
+) -> dict[str, str]:
+ options = {
+ DIRECT_MOTHERDUCK_SCHEMA_OPTION: source_schema,
+ DIRECT_MOTHERDUCK_TABLE_OPTION: source_table_name,
+ }
+ if source_catalog:
+ options[DIRECT_MOTHERDUCK_CATALOG_OPTION] = source_catalog
+ return options
+
+
+def upsert_direct_motherduck_table(
+ existing_table: DataWarehouseTable | None,
+ *,
+ schema_name: str,
+ source: ExternalDataSource,
+ columns: DirectMotherDuckColumns,
+ source_catalog: str | None = None,
+ source_schema: str,
+ source_table_name: str,
+) -> DataWarehouseTable:
+ from products.warehouse_sources.backend.facade.models import DataWarehouseTable
+
+ options = {
+ **(existing_table.options if existing_table is not None and isinstance(existing_table.options, dict) else {}),
+ **get_direct_motherduck_table_options(
+ source_catalog=source_catalog,
+ source_schema=source_schema,
+ source_table_name=source_table_name,
+ ),
+ }
+
+ if existing_table is None:
+ return DataWarehouseTable.objects.create(
+ name=schema_name,
+ format=DataWarehouseTable.TableFormat.Parquet,
+ team_id=source.team_id,
+ url_pattern=DIRECT_MOTHERDUCK_URL_PATTERN,
+ external_data_source=source,
+ columns=columns,
+ options=options,
+ )
+
+ existing_table.name = schema_name
+ existing_table.url_pattern = DIRECT_MOTHERDUCK_URL_PATTERN
+ existing_table.external_data_source = source
+ existing_table.columns = columns
+ existing_table.options = options
+ existing_table.deleted = False
+ existing_table.deleted_at = None
+ existing_table.save(
+ update_fields=[
+ "name",
+ "url_pattern",
+ "external_data_source",
+ "columns",
+ "options",
+ "deleted",
+ "deleted_at",
+ "updated_at",
+ ]
+ )
+ return existing_table
+
+
+def hide_direct_motherduck_table(table: DataWarehouseTable | None) -> None:
+ if table is not None and not table.deleted:
+ table.soft_delete()
diff --git a/products/data_warehouse/backend/direct_query_engines.py b/products/data_warehouse/backend/direct_query_engines.py
index 230abfea3671..a0c89a3b7d9e 100644
--- a/products/data_warehouse/backend/direct_query_engines.py
+++ b/products/data_warehouse/backend/direct_query_engines.py
@@ -21,10 +21,19 @@ from products.data_warehouse.backend.direct_clickhouse import (
hide_direct_clickhouse_table,
upsert_direct_clickhouse_table,
)
+from products.data_warehouse.backend.direct_motherduck import (
+ hide_direct_motherduck_table,
+ upsert_direct_motherduck_table,
+)
from products.data_warehouse.backend.direct_mysql import hide_direct_mysql_table, upsert_direct_mysql_table
from products.data_warehouse.backend.direct_postgres import hide_direct_postgres_table, upsert_direct_postgres_table
from products.data_warehouse.backend.direct_redshift import hide_direct_redshift_table, upsert_direct_redshift_table
from products.data_warehouse.backend.direct_snowflake import hide_direct_snowflake_table, upsert_direct_snowflake_table
+from products.data_warehouse.backend.motherduck_helpers import (
+ get_motherduck_source_location,
+ reconcile_motherduck_schemas,
+ reproject_direct_motherduck_table,
+)
from products.data_warehouse.backend.mysql_helpers import (
get_mysql_source_location,
reconcile_mysql_schemas,
@@ -47,6 +56,7 @@ from products.data_warehouse.backend.snowflake_helpers import (
)
from products.warehouse_sources.backend.facade.api import (
clickhouse_columns_to_dwh_columns,
+ motherduck_columns_to_dwh_columns,
mysql_columns_to_dwh_columns,
postgres_columns_to_dwh_columns,
snowflake_columns_to_dwh_columns,
@@ -326,9 +336,53 @@ class _ClickHouseEngine(DirectQueryEngine):
# bespoke legacy-row remapping (only Postgres does), so it falls through to the generic path.
+class _MotherDuckEngine(DirectQueryEngine):
+ engine = "motherduck"
+
+ def source_table_location(self, *, schema_name, source_schema, default_schema, default_catalog=None):
+ return get_motherduck_source_location(
+ schema_name=schema_name,
+ schema_metadata=_location_metadata(source_schema),
+ default_catalog=default_catalog,
+ default_schema=default_schema,
+ )
+
+ def columns_to_dwh_columns(self, source_columns):
+ return motherduck_columns_to_dwh_columns(source_columns)
+
+ def upsert_table(
+ self, existing_table, *, schema_name, source, columns, source_catalog, source_schema, source_table_name
+ ):
+ return upsert_direct_motherduck_table(
+ existing_table,
+ schema_name=schema_name,
+ source=source,
+ columns=columns,
+ source_catalog=source_catalog,
+ source_schema=source_schema,
+ source_table_name=source_table_name,
+ )
+
+ def reproject_table(self, schema_row, *, source, enabled_columns):
+ return reproject_direct_motherduck_table(schema_row, source=source, enabled_columns=enabled_columns)
+
+ def hide_table(self, table):
+ hide_direct_motherduck_table(table)
+
+ def reconcile_schemas(self, *, source, source_schemas, team_id):
+ return reconcile_motherduck_schemas(source=source, source_schemas=source_schemas, team_id=team_id)
+
+
_ENGINES: dict[str, DirectQueryEngine] = {
engine.engine: engine
- for engine in (_PostgresEngine(), _MySQLEngine(), _SnowflakeEngine(), _RedshiftEngine(), _ClickHouseEngine())
+ for engine in (
+ _PostgresEngine(),
+ _MySQLEngine(),
+ _SnowflakeEngine(),
+ _RedshiftEngine(),
+ _ClickHouseEngine(),
+ _MotherDuckEngine(),
+ )
}
diff --git a/products/data_warehouse/backend/direct_virtual_tables.py b/products/data_warehouse/backend/direct_virtual_tables.py
index d9008daa044a..09c8a994cb0c 100644
--- a/products/data_warehouse/backend/direct_virtual_tables.py
+++ b/products/data_warehouse/backend/direct_virtual_tables.py
@@ -10,6 +10,7 @@ objects the pure-direct path derives from physical rows, but from each
from typing import TYPE_CHECKING
from posthog.hogql.database.direct_clickhouse_table import DirectClickHouseTable
+from posthog.hogql.database.direct_motherduck_table import DirectMotherDuckTable
from posthog.hogql.database.direct_mysql_table import DirectMySQLTable
from posthog.hogql.database.direct_postgres_table import DirectPostgresTable
from posthog.hogql.database.direct_redshift_table import DirectRedshiftTable
@@ -20,6 +21,11 @@ from products.data_warehouse.backend.clickhouse_helpers import (
clickhouse_schema_metadata_to_dwh_columns,
get_clickhouse_source_location,
)
+from products.data_warehouse.backend.motherduck_helpers import (
+ get_default_motherduck_catalog,
+ get_motherduck_source_location,
+ motherduck_schema_metadata_to_dwh_columns,
+)
from products.data_warehouse.backend.mysql_helpers import (
get_default_mysql_schema,
get_mysql_source_location,
@@ -232,4 +238,37 @@ def build_direct_table_for_schema(schema: "ExternalDataSchema", source: "Externa
has_complete_columns=schema.enabled_columns is None,
)
+ if engine == "motherduck":
+ columns = motherduck_schema_metadata_to_dwh_columns(metadata)
+ if not columns:
+ return None
+ columns = filter_dwh_columns_by_enabled_columns(
+ columns,
+ schema.enabled_columns,
+ schema.primary_key_columns,
+ schema.incremental_field,
+ # Direct-MotherDuck columns are keyed by raw, case-sensitive source names.
+ normalize=False,
+ )
+ fields, _ = hogql_fields_and_structure_for_columns(columns)
+ catalog, motherduck_schema, table_name = get_motherduck_source_location(
+ schema_name=schema.name,
+ schema_metadata=metadata,
+ default_catalog=get_default_motherduck_catalog(source),
+ )
+ if not catalog:
+ return None
+ return DirectMotherDuckTable(
+ name=schema.name,
+ fields=fields,
+ motherduck_database=catalog,
+ motherduck_schema=motherduck_schema,
+ motherduck_table_name=table_name,
+ external_data_source_id=str(source.id),
+ connection_metadata=source.connection_metadata,
+ # No column-picker restriction → these fields are the complete physical schema, so a
+ # `SELECT *` can pass through to the server literally.
+ has_complete_columns=schema.enabled_columns is None,
+ )
+
return None
diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.py
index 490b3b654817..7a07ecfcf3a1 100644
--- a/products/data_warehouse/backend/facade/api.py
+++ b/products/data_warehouse/backend/facade/api.py
@@ -76,6 +76,7 @@ _LAZY = {
"HogQLQueryFixerTool": "max_tools",
"hide_direct_mysql_table": "direct_mysql",
"upsert_direct_mysql_table": "direct_mysql",
+ "DIRECT_MOTHERDUCK_URL_PATTERN": "direct_motherduck",
"DIRECT_POSTGRES_URL_PATTERN": "direct_postgres",
"hide_direct_postgres_table": "direct_postgres",
"upsert_direct_postgres_table": "direct_postgres",
diff --git a/products/data_warehouse/backend/facade/sources.py b/products/data_warehouse/backend/facade/sources.py
index 6c1c6e58fda7..9e51abc6f03c 100644
--- a/products/data_warehouse/backend/facade/sources.py
+++ b/products/data_warehouse/backend/facade/sources.py
@@ -10,6 +10,11 @@ from products.data_warehouse.backend.direct_clickhouse import (
DIRECT_CLICKHOUSE_DATABASE_OPTION,
DIRECT_CLICKHOUSE_TABLE_OPTION,
)
+from products.data_warehouse.backend.direct_motherduck import (
+ DIRECT_MOTHERDUCK_CATALOG_OPTION,
+ DIRECT_MOTHERDUCK_SCHEMA_OPTION,
+ DIRECT_MOTHERDUCK_TABLE_OPTION,
+)
from products.data_warehouse.backend.direct_mysql import DIRECT_MYSQL_SCHEMA_OPTION, DIRECT_MYSQL_TABLE_OPTION
from products.data_warehouse.backend.direct_postgres import (
DIRECT_POSTGRES_CATALOG_OPTION,
@@ -30,6 +35,9 @@ from products.data_warehouse.backend.direct_snowflake import (
__all__ = [
"DIRECT_CLICKHOUSE_DATABASE_OPTION",
"DIRECT_CLICKHOUSE_TABLE_OPTION",
+ "DIRECT_MOTHERDUCK_CATALOG_OPTION",
+ "DIRECT_MOTHERDUCK_SCHEMA_OPTION",
+ "DIRECT_MOTHERDUCK_TABLE_OPTION",
"DIRECT_MYSQL_SCHEMA_OPTION",
"DIRECT_MYSQL_TABLE_OPTION",
"DIRECT_POSTGRES_CATALOG_OPTION",
diff --git a/products/data_warehouse/backend/motherduck_helpers.py b/products/data_warehouse/backend/motherduck_helpers.py
new file mode 100644
index 000000000000..8d5d78f354f9
--- /dev/null
+++ b/products/data_warehouse/backend/motherduck_helpers.py
@@ -0,0 +1,297 @@
+"""MotherDuck source helpers shared between warehouse and direct-query modes.
+
+Direct-query-only utilities (DataWarehouseTable upserts, the `direct://motherduck`
+url_pattern, the option keys that encode source location on a direct table) live in
+`direct_motherduck.py`.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+from django.db.models import Q
+
+import structlog
+
+from products.data_warehouse.backend.direct_motherduck import (
+ DIRECT_MOTHERDUCK_CATALOG_OPTION,
+ DIRECT_MOTHERDUCK_SCHEMA_OPTION,
+ DIRECT_MOTHERDUCK_TABLE_OPTION,
+ hide_direct_motherduck_table,
+ upsert_direct_motherduck_table,
+)
+from products.warehouse_sources.backend.facade.models import (
+ ExternalDataSource,
+ motherduck_column_to_dwh_column,
+ motherduck_columns_to_dwh_columns,
+)
+from products.warehouse_sources.backend.facade.source_management import (
+ SourceSchema,
+ extract_available_column_names,
+ filter_dwh_columns_by_enabled_columns,
+ normalize_namespace,
+ prune_enabled_columns,
+ sql_schema_metadata,
+)
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+log = structlog.get_logger(__name__)
+
+type MotherDuckSourceLocation = tuple[str | None, str, str] # (database, schema, table_name)
+
+
+def get_default_motherduck_catalog(source: ExternalDataSource) -> str | None:
+ database = (source.job_inputs or {}).get("database")
+ return database if isinstance(database, str) and database.strip() else None
+
+
+def motherduck_schema_metadata_to_dwh_columns(schema_metadata: dict[str, Any] | None) -> dict[str, dict[str, Any]]:
+ resolved: dict[str, dict[str, Any]] = {}
+ if not schema_metadata:
+ return resolved
+ columns = schema_metadata.get("columns")
+ if not isinstance(columns, list):
+ return resolved
+ for column in columns:
+ if not isinstance(column, dict):
+ continue
+ column_name = column.get("name")
+ duckdb_type = column.get("data_type")
+ nullable = bool(column.get("is_nullable"))
+ if not isinstance(column_name, str) or not isinstance(duckdb_type, str):
+ continue
+ resolved[column_name] = motherduck_column_to_dwh_column(column_name, duckdb_type, nullable)
+ return resolved
+
+
+def reproject_direct_motherduck_table(
+ schema_row: Any,
+ *,
+ source: ExternalDataSource,
+ enabled_columns: list[str] | None,
+) -> Any:
+ """Rebuild the direct-query `DataWarehouseTable` with a fresh column projection — used on
+ column-picker save and on `should_sync` False → True. No re-sync needed in direct mode."""
+ source_catalog, source_schema, source_table_name = get_motherduck_source_location(
+ schema_name=schema_row.name,
+ schema_metadata=schema_row.schema_metadata,
+ default_catalog=get_default_motherduck_catalog(source),
+ )
+ return upsert_direct_motherduck_table(
+ schema_row.table,
+ schema_name=schema_row.name,
+ source=source,
+ columns=filter_dwh_columns_by_enabled_columns(
+ motherduck_schema_metadata_to_dwh_columns(schema_row.schema_metadata),
+ enabled_columns,
+ schema_row.primary_key_columns,
+ schema_row.incremental_field,
+ # Direct-MotherDuck columns are keyed by raw, case-sensitive source names.
+ normalize=False,
+ ),
+ source_catalog=source_catalog,
+ source_schema=source_schema,
+ source_table_name=source_table_name,
+ )
+
+
+def get_motherduck_source_location(
+ *,
+ schema_name: str,
+ schema_metadata: dict[str, Any] | None = None,
+ default_catalog: str | None = None,
+ default_schema: str | None = None,
+) -> MotherDuckSourceLocation:
+ """Resolve (database, schema, table_name) for a MotherDuck source.
+
+ Discovery always stamps the full location into `schema_metadata`; name parsing exists
+ only for rows created without it (`db.schema.table` or `schema.table` display names).
+ """
+ source_catalog = schema_metadata.get("source_catalog") if isinstance(schema_metadata, dict) else None
+ source_schema = schema_metadata.get("source_schema") if isinstance(schema_metadata, dict) else None
+ source_table_name = schema_metadata.get("source_table_name") if isinstance(schema_metadata, dict) else None
+ normalized_default_schema = normalize_namespace(default_schema)
+
+ catalog = source_catalog if isinstance(source_catalog, str) and source_catalog.strip() else default_catalog
+ if isinstance(source_schema, str) and isinstance(source_table_name, str):
+ return catalog, source_schema, source_table_name
+
+ parts = schema_name.split(".")
+ if len(parts) == 3:
+ return parts[0], parts[1], parts[2]
+ if len(parts) == 2:
+ return catalog, parts[0], parts[1]
+
+ return catalog, normalized_default_schema or "main", schema_name
+
+
+def get_motherduck_source_location_for_schema_model(
+ *,
+ schema_name: str,
+ sync_type_config: dict[str, Any] | None = None,
+ table_options: dict[str, Any] | None = None,
+ default_catalog: str | None = None,
+) -> MotherDuckSourceLocation:
+ schema_metadata = (
+ sync_type_config.get("schema_metadata")
+ if isinstance(sync_type_config, dict) and isinstance(sync_type_config.get("schema_metadata"), dict)
+ else None
+ )
+ if schema_metadata is not None:
+ return get_motherduck_source_location(
+ schema_name=schema_name,
+ schema_metadata=schema_metadata,
+ default_catalog=default_catalog,
+ )
+
+ opts = table_options if isinstance(table_options, dict) else {}
+ table_source_catalog = opts.get(DIRECT_MOTHERDUCK_CATALOG_OPTION)
+ table_source_schema = opts.get(DIRECT_MOTHERDUCK_SCHEMA_OPTION)
+ table_source_table_name = opts.get(DIRECT_MOTHERDUCK_TABLE_OPTION)
+
+ if isinstance(table_source_schema, str) and isinstance(table_source_table_name, str):
+ return (
+ table_source_catalog if isinstance(table_source_catalog, str) else default_catalog,
+ table_source_schema,
+ table_source_table_name,
+ )
+
+ return get_motherduck_source_location(
+ schema_name=schema_name,
+ schema_metadata=None,
+ default_catalog=default_catalog,
+ )
+
+
+def reconcile_motherduck_schemas(
+ *,
+ source: ExternalDataSource,
+ source_schemas: list[SourceSchema],
+ team_id: int,
+) -> list[str]:
+ """Persist `schema_metadata` on every MotherDuck row + (direct mode only) upsert its
+ live-query `DataWarehouseTable`. Returns stale schema names that got soft-deleted (direct
+ only)."""
+ from products.warehouse_sources.backend.facade.models import ExternalDataSchema
+
+ is_direct = source.is_direct_query
+ source_schema_names = [s.name for s in source_schemas]
+ default_catalog = get_default_motherduck_catalog(source)
+ schema_models = {
+ s.name: s
+ for s in ExternalDataSchema.objects.filter(team_id=team_id, source_id=source.id, deleted=False).select_related(
+ "table"
+ )
+ }
+
+ schema_models_by_location: dict[MotherDuckSourceLocation, ExternalDataSchema] = {}
+ for schema_model in schema_models.values():
+ location = get_motherduck_source_location_for_schema_model(
+ schema_name=schema_model.name,
+ sync_type_config=schema_model.sync_type_config,
+ table_options=schema_model.table.options if schema_model.table is not None else None,
+ default_catalog=default_catalog,
+ )
+ schema_models_by_location.setdefault(location, schema_model)
+
+ for source_schema in source_schemas:
+ resolved = get_motherduck_source_location(
+ schema_name=source_schema.name,
+ schema_metadata={
+ "source_catalog": source_schema.source_catalog,
+ "source_schema": source_schema.source_schema,
+ "source_table_name": source_schema.source_table_name,
+ },
+ default_catalog=default_catalog,
+ )
+ matched: ExternalDataSchema | None = schema_models.get(source_schema.name)
+ if matched is None:
+ matched = schema_models_by_location.get(resolved)
+ if matched is None:
+ continue
+
+ resolved_catalog, resolved_schema, resolved_table = resolved
+
+ # Metadata holds the full column list (column-picker UI); projection lives on `enabled_columns`.
+ schema_metadata = sql_schema_metadata(
+ source_schema.columns,
+ source_schema.foreign_keys,
+ source_catalog=resolved_catalog,
+ source_schema=resolved_schema,
+ source_table_name=resolved_table,
+ )
+ new_sync_type_config = {**(matched.sync_type_config or {}), "schema_metadata": schema_metadata}
+ # Persist the detected primary key without clobbering a value already stored — e.g. an
+ # explicit override set during creation or a prior refresh.
+ if source_schema.detected_primary_keys and not new_sync_type_config.get("primary_key_columns"):
+ new_sync_type_config["primary_key_columns"] = source_schema.detected_primary_keys
+ matched.sync_type_config = new_sync_type_config
+ update_fields = ["sync_type_config", "updated_at"]
+
+ # Drop dead columns so the next projection doesn't reference `missing_col`.
+ available_names = extract_available_column_names(schema_metadata)
+ pruned_enabled_columns, removed_columns = prune_enabled_columns(matched.enabled_columns, available_names)
+ if removed_columns:
+ log.info(
+ "motherduck.reconcile_schemas.pruned_enabled_columns",
+ source_id=str(source.id),
+ schema_id=str(matched.id),
+ schema_name=matched.name,
+ removed_columns=removed_columns,
+ )
+ matched.enabled_columns = pruned_enabled_columns
+ update_fields.append("enabled_columns")
+ matched.save(update_fields=update_fields)
+
+ if not is_direct:
+ # Warehouse mode: the ingestion workflow manages `DataWarehouseTable` itself.
+ continue
+
+ if not matched.should_sync:
+ hide_direct_motherduck_table(matched.table)
+ continue
+
+ projected_columns = filter_dwh_columns_by_enabled_columns(
+ motherduck_columns_to_dwh_columns(source_schema.columns),
+ matched.enabled_columns,
+ source_schema.detected_primary_keys,
+ matched.incremental_field,
+ # Direct-MotherDuck columns are keyed by raw, case-sensitive source names. The
+ # guarded helper falls back to all columns when a projection would empty out,
+ # so a stale selection can't leave the live table unqueryable.
+ normalize=False,
+ )
+ table_model = upsert_direct_motherduck_table(
+ matched.table,
+ schema_name=source_schema.name,
+ source=source,
+ columns=projected_columns,
+ source_catalog=resolved_catalog,
+ source_schema=resolved_schema,
+ source_table_name=resolved_table,
+ )
+ if matched.table_id != table_model.id:
+ matched.table = table_model
+ matched.save(update_fields=["table"])
+
+ if not is_direct:
+ # Warehouse mode delegates add/delete to `sync_old_schemas_with_new_schemas`.
+ return []
+
+ stale_names: list[str] = []
+ stale = (
+ ExternalDataSchema.objects.filter(
+ Q(team_id=team_id, source_id=source.id),
+ Q(deleted=False) | Q(table__deleted=False),
+ )
+ .exclude(name__in=source_schema_names)
+ .select_related("table")
+ )
+ for s in stale:
+ hide_direct_motherduck_table(s.table)
+ if not s.deleted:
+ s.soft_delete()
+ stale_names.append(s.name)
+ return stale_names
diff --git a/products/data_warehouse/backend/test/test_direct_query_engines.py b/products/data_warehouse/backend/test/test_direct_query_engines.py
index df78ce9c58df..a121208be56c 100644
--- a/products/data_warehouse/backend/test/test_direct_query_engines.py
+++ b/products/data_warehouse/backend/test/test_direct_query_engines.py
@@ -10,7 +10,7 @@ def _source_schema(*, catalog=None, schema=None, table=None):
class TestDirectQueryEngineRegistry:
- @parameterized.expand(["postgres", "mysql", "snowflake", "redshift", "clickhouse"])
+ @parameterized.expand(["postgres", "mysql", "snowflake", "redshift", "clickhouse", "motherduck"])
def test_known_engine_resolves(self, engine: str):
adapter = get_direct_query_engine(engine)
assert adapter is not None
@@ -29,6 +29,7 @@ class TestDirectQueryEngineRegistry:
("snowflake", False),
("redshift", False),
("clickhouse", False),
+ ("motherduck", False),
]
)
def test_resolves_location_in_warehouse_mode(self, engine: str, expected: bool):
@@ -43,6 +44,7 @@ class TestDirectQueryEngineRegistry:
("postgres", ("db", "public", "users")),
("snowflake", ("db", "public", "users")),
("redshift", ("db", "public", "users")),
+ ("motherduck", ("db", "public", "users")),
("mysql", (None, "public", "users")),
# ClickHouse has no catalog level — the database occupies the "schema" slot.
("clickhouse", (None, "public", "users")),
@@ -85,7 +87,7 @@ class TestDirectQueryEngineRegistry:
)
assert location == ("WAREHOUSE", "analytics", "events")
- @parameterized.expand(["mysql", "snowflake", "redshift", "clickhouse"])
+ @parameterized.expand(["mysql", "snowflake", "redshift", "clickhouse", "motherduck"])
def test_non_postgres_engines_return_no_name_substitutions(self, engine: str):
# Returning None (not {}) is the sentinel that makes the view fall through to the generic
# multi-schema migration path; only Postgres has bespoke legacy-row remapping.
@@ -93,6 +95,19 @@ class TestDirectQueryEngineRegistry:
assert adapter is not None
assert adapter.refresh_name_substitutions(source=None, source_schemas=[], team_id=1) is None
+ def test_motherduck_splits_three_part_dotted_name(self):
+ # Blank-database MotherDuck sources name rows `db.schema.table`; the split must recover
+ # the database too, not fold it into the schema.
+ adapter = get_direct_query_engine("motherduck")
+ assert adapter is not None
+ location = adapter.source_table_location(
+ schema_name="sample_data.nyc.taxi",
+ source_schema=None,
+ default_schema=None,
+ default_catalog=None,
+ )
+ assert location == ("sample_data", "nyc", "taxi")
+
def test_snowflake_default_schema_takes_precedence_over_dot_split(self):
adapter = get_direct_query_engine("snowflake")
assert adapter is not None
diff --git a/products/data_warehouse/backend/test/test_direct_virtual_tables.py b/products/data_warehouse/backend/test/test_direct_virtual_tables.py
index 35d1d69ee713..fd1998598af3 100644
--- a/products/data_warehouse/backend/test/test_direct_virtual_tables.py
+++ b/products/data_warehouse/backend/test/test_direct_virtual_tables.py
@@ -1,5 +1,7 @@
from posthog.test.base import APIBaseTest
+from posthog.hogql.database.direct_motherduck_table import DirectMotherDuckTable
+
from products.data_warehouse.backend.direct_virtual_tables import build_direct_table_for_schema
from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
@@ -50,3 +52,39 @@ class TestBuildDirectTableForSchema(APIBaseTest):
assert table is not None
assert set(table.fields) == {"id", "email", "secret"}
+
+ def test_motherduck_virtual_table_resolves_location_and_columns(self):
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_type=ExternalDataSourceType.MOTHERDUCK,
+ access_method=ExternalDataSource.AccessMethod.WAREHOUSE,
+ direct_query_enabled=True,
+ job_inputs={"access_token": "t", "database": "my_db"},
+ )
+ schema = ExternalDataSchema.objects.create(
+ name="nyc.taxi",
+ team=self.team,
+ source=source,
+ enabled_columns=None,
+ sync_type_config={
+ "schema_metadata": {
+ "source_catalog": "my_db",
+ "source_schema": "nyc",
+ "source_table_name": "taxi",
+ "columns": [
+ {"name": "id", "data_type": "BIGINT", "is_nullable": False},
+ {"name": "fare", "data_type": "DOUBLE", "is_nullable": True},
+ ],
+ },
+ },
+ )
+
+ table = build_direct_table_for_schema(schema, source)
+
+ assert isinstance(table, DirectMotherDuckTable)
+ assert (table.motherduck_database, table.motherduck_schema, table.motherduck_table_name) == (
+ "my_db",
+ "nyc",
+ "taxi",
+ )
+ assert set(table.fields) == {"id", "fare"}
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceWizard.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceWizard.test.ts
index 4976263ed348..94f83656ce5c 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceWizard.test.ts
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceWizard.test.ts
@@ -17,6 +17,7 @@ describe('NewSourceWizard', () => {
['synced direct-capable source defaults to enabled', {}, 'Postgres', true],
['toggle switched off is respected', { direct_query_enabled: false }, 'Postgres', false],
['pure direct source omits the flag', { access_method: 'direct' }, 'Postgres', undefined],
+ ['motherduck is direct-capable', { access_method: 'direct' }, 'Motherduck', undefined],
['non-direct-capable source omits the flag', {}, 'Stripe', undefined],
])('%s', (_description, sourceValues, connectorName, expected) => {
expect(resolveCreateDirectQueryEnabled(sourceValues, connectorName)).toEqual(expected)
diff --git a/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts b/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts
index 306edbcf6584..1e4d8c2668ba 100644
--- a/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts
+++ b/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts
@@ -1,7 +1,14 @@
import { groupBy } from 'lib/utils/arrays'
/** Source types that support `access_method: 'direct'` (live querying without syncing to the warehouse). */
-export const DIRECT_QUERY_SOURCE_TYPES = ['Postgres', 'MySQL', 'Snowflake', 'Redshift', 'ClickHouse'] as const
+export const DIRECT_QUERY_SOURCE_TYPES = [
+ 'Postgres',
+ 'MySQL',
+ 'Snowflake',
+ 'Redshift',
+ 'ClickHouse',
+ 'Motherduck',
+] as const
export function supportsDirectQuery(sourceType: string | null | undefined): boolean {
return !!sourceType && DIRECT_QUERY_SOURCE_TYPES.includes(sourceType as (typeof DIRECT_QUERY_SOURCE_TYPES)[number])
diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.py
index 396dc14afb5a..027dec55a585 100644
--- a/products/warehouse_sources/backend/facade/api.py
+++ b/products/warehouse_sources/backend/facade/api.py
@@ -37,6 +37,7 @@ from products.warehouse_sources.backend.models.table import DataWarehouseTable a
# Framework-free helper transforms — re-exported as the public helper surface.
from products.warehouse_sources.backend.models.util import (
clickhouse_columns_to_dwh_columns,
+ motherduck_columns_to_dwh_columns,
mysql_column_to_dwh_column,
mysql_columns_to_dwh_columns,
postgres_column_to_dwh_column,
@@ -60,6 +61,7 @@ __all__ = [
"list_jobs_for_source",
# framework-free helper transforms
"clickhouse_columns_to_dwh_columns",
+ "motherduck_columns_to_dwh_columns",
"mysql_column_to_dwh_column",
"mysql_columns_to_dwh_columns",
"postgres_column_to_dwh_column",
diff --git a/products/warehouse_sources/backend/facade/models.py b/products/warehouse_sources/backend/facade/models.py
index 2d1aea36acbe..4a8ca5b2a778 100644
--- a/products/warehouse_sources/backend/facade/models.py
+++ b/products/warehouse_sources/backend/facade/models.py
@@ -50,6 +50,8 @@ from products.warehouse_sources.backend.models.table import (
from products.warehouse_sources.backend.models.util import (
clickhouse_column_to_dwh_column,
clickhouse_columns_to_dwh_columns,
+ motherduck_column_to_dwh_column,
+ motherduck_columns_to_dwh_columns,
mysql_column_to_dwh_column,
mysql_columns_to_dwh_columns,
postgres_column_to_dwh_column,
@@ -85,6 +87,8 @@ __all__ = [
"get_or_create_datawarehouse_credential",
"clickhouse_column_to_dwh_column",
"clickhouse_columns_to_dwh_columns",
+ "motherduck_column_to_dwh_column",
+ "motherduck_columns_to_dwh_columns",
"mysql_column_to_dwh_column",
"mysql_columns_to_dwh_columns",
"postgres_column_to_dwh_column",
diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.py
index b9438c9872cc..93b97a0de3e0 100644
--- a/products/warehouse_sources/backend/facade/source_management.py
+++ b/products/warehouse_sources/backend/facade/source_management.py
@@ -58,6 +58,10 @@ _LAZY = {
"CustomSourceConfig": "sources.generated_configs.custom",
"GithubSource": "sources.github.source",
"GithubSourceConfig": "sources.generated_configs.github",
+ "MotherDuckConnectionError": "sources.motherduck.motherduck",
+ "MotherduckSource": "sources.motherduck.source",
+ "MotherduckSourceConfig": "sources.generated_configs.motherduck",
+ "translate_motherduck_error": "sources.motherduck.motherduck",
"MySQLSourceConfig": "sources.generated_configs.mysql",
"PostgresSourceConfig": "sources.generated_configs.postgres",
"SnowflakeSourceConfig": "sources.generated_configs.snowflake",
diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.py
index 4b1a20640894..7dc8fafb53e9 100644
--- a/products/warehouse_sources/backend/models/table.py
+++ b/products/warehouse_sources/backend/models/table.py
@@ -19,6 +19,7 @@ from posthog.hogql import ast
from posthog.hogql.constants import HogQLQuerySettings
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.direct_clickhouse_table import DirectClickHouseTable
+from posthog.hogql.database.direct_motherduck_table import DirectMotherDuckTable
from posthog.hogql.database.direct_mysql_table import DirectMySQLTable
from posthog.hogql.database.direct_postgres_table import DirectPostgresTable
from posthog.hogql.database.direct_redshift_table import DirectRedshiftTable
@@ -695,6 +696,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
| DirectSnowflakeTable
| DirectRedshiftTable
| DirectClickHouseTable
+ | DirectMotherDuckTable
):
# Deferred: importing data_warehouse's facade at module scope creates an import cycle
# (data_warehouse models -> this model package -> data_warehouse.facade.sources -> ...).
@@ -702,6 +704,9 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
from products.data_warehouse.backend.facade.sources import ( # noqa: PLC0415 — breaks an import cycle
DIRECT_CLICKHOUSE_DATABASE_OPTION,
DIRECT_CLICKHOUSE_TABLE_OPTION,
+ DIRECT_MOTHERDUCK_CATALOG_OPTION,
+ DIRECT_MOTHERDUCK_SCHEMA_OPTION,
+ DIRECT_MOTHERDUCK_TABLE_OPTION,
DIRECT_MYSQL_SCHEMA_OPTION,
DIRECT_MYSQL_TABLE_OPTION,
DIRECT_POSTGRES_CATALOG_OPTION,
@@ -823,6 +828,40 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
connection_metadata=self.external_data_source.connection_metadata,
)
+ # Engine-keyed like ClickHouse (no is_direct_motherduck) to satisfy the source-agnostic
+ # guard; the is_direct_query check keeps synced sources' tables S3-backed.
+ if (
+ self.external_data_source
+ and self.external_data_source.is_direct_query
+ and self.external_data_source.direct_engine == "motherduck"
+ ):
+ job_inputs = self.external_data_source.job_inputs or {}
+ motherduck_database = (
+ self.options.get(DIRECT_MOTHERDUCK_CATALOG_OPTION)
+ if isinstance(self.options.get(DIRECT_MOTHERDUCK_CATALOG_OPTION), str)
+ else job_inputs.get("database", "")
+ )
+ motherduck_schema = (
+ self.options.get(DIRECT_MOTHERDUCK_SCHEMA_OPTION)
+ if isinstance(self.options.get(DIRECT_MOTHERDUCK_SCHEMA_OPTION), str)
+ else "main"
+ )
+ motherduck_table_name = (
+ self.options.get(DIRECT_MOTHERDUCK_TABLE_OPTION)
+ if isinstance(self.options.get(DIRECT_MOTHERDUCK_TABLE_OPTION), str)
+ else self.name
+ )
+ return DirectMotherDuckTable(
+ name=self.name,
+ fields=fields,
+ motherduck_database=motherduck_database,
+ motherduck_schema=motherduck_schema,
+ motherduck_table_name=motherduck_table_name,
+ external_data_source_id=str(self.external_data_source_id),
+ connection_metadata=self.external_data_source.connection_metadata,
+ has_complete_columns=self._direct_columns_are_complete(),
+ )
+
# Engine-keyed (no is_direct_clickhouse) to satisfy the source-agnostic guard. The
# is_direct_query check is load-bearing: direct_engine ignores access_method, and a synced
# source's tables must stay S3-backed — as a direct table, every ordinary query against
diff --git a/products/warehouse_sources/backend/models/util.py b/products/warehouse_sources/backend/models/util.py
index b1a7621a8c9b..dddddc92d127 100644
--- a/products/warehouse_sources/backend/models/util.py
+++ b/products/warehouse_sources/backend/models/util.py
@@ -326,14 +326,21 @@ CLICKHOUSE_TYPE_TO_HOGQL_LABEL = {
"Int16": "integer",
"Int32": "integer",
"Int64": "integer",
+ "Int128": "integer",
+ "UInt8": "integer",
+ "UInt16": "integer",
+ "UInt32": "integer",
"UInt64": "integer",
+ "UInt128": "integer",
"Float32": "float",
"Float64": "float",
"Bool": "boolean",
"Date": "date",
+ "Date32": "date",
"DateTime": "datetime",
"DateTime64": "datetime",
"String": "string",
+ "UUID": "string",
"Decimal": "numeric",
}
@@ -581,6 +588,86 @@ def clickhouse_columns_to_dwh_columns(columns: list[tuple[str, str, bool]]) -> d
}
+# DuckDB base type name (lowercased, parenthesized args stripped) -> ClickHouse type.
+# Anything absent maps to String, which round-trips every remaining DuckDB type
+# (JSON, INTERVAL, BLOB, ENUM, nested LIST/STRUCT/MAP/UNION renderings).
+DUCKDB_TO_CLICKHOUSE_TYPE: dict[str, str] = {
+ "tinyint": "Int8",
+ "smallint": "Int16",
+ "integer": "Int32",
+ "int": "Int32",
+ "bigint": "Int64",
+ "hugeint": "Int128",
+ "utinyint": "UInt8",
+ "usmallint": "UInt16",
+ "uinteger": "UInt32",
+ "ubigint": "UInt64",
+ "uhugeint": "UInt128",
+ "float": "Float32",
+ "real": "Float32",
+ "double": "Float64",
+ "decimal": "Decimal",
+ "numeric": "Decimal",
+ "boolean": "Bool",
+ "date": "Date32",
+ "timestamp": "DateTime64(6)",
+ "datetime": "DateTime64(6)",
+ "timestamp with time zone": "DateTime64(6, 'UTC')",
+ "timestamptz": "DateTime64(6, 'UTC')",
+ "timestamp_s": "DateTime64(0)",
+ "timestamp_ms": "DateTime64(3)",
+ "timestamp_ns": "DateTime64(9)",
+ "uuid": "UUID",
+}
+
+
+def normalize_duckdb_type(duckdb_type: str) -> str:
+ """Lowercased base type name: `DECIMAL(10,2)` -> `decimal`, `INTEGER[]` -> `integer[]`."""
+ base = duckdb_type.strip().lower()
+ if "(" in base and base.endswith(")"):
+ open_index = base.index("(")
+ close_index = base.rindex(")")
+ base = (base[:open_index] + base[close_index + 1 :]).strip()
+ return base
+
+
+def duckdb_to_clickhouse_type(duckdb_type: str) -> str:
+ normalized_type = normalize_duckdb_type(duckdb_type)
+ clickhouse_type = DUCKDB_TO_CLICKHOUSE_TYPE.get(normalized_type)
+ if clickhouse_type is not None:
+ return clickhouse_type
+ # Arrays keep their `[]` suffix through normalization, so check before the scalar
+ # prefix fallbacks below or `DECIMAL(18,3)[]` would come out as a scalar Decimal.
+ if normalized_type.endswith("]"):
+ return "String"
+ if normalized_type.startswith(("decimal", "numeric")):
+ return "Decimal"
+ if normalized_type.startswith("timestamp"):
+ return "DateTime64(6)"
+ # JSON/INTERVAL/BLOB/ENUM and nested LIST/STRUCT/MAP/UNION render as String.
+ return "String"
+
+
+def motherduck_column_to_dwh_column(_column_name: str, duckdb_type: str, nullable: bool) -> dict[str, Any]:
+ clickhouse_type = duckdb_to_clickhouse_type(duckdb_type)
+ if nullable:
+ clickhouse_type = f"Nullable({clickhouse_type})"
+
+ raw_clickhouse_type = clean_type(clickhouse_type)
+ return {
+ "clickhouse": clickhouse_type,
+ "hogql": CLICKHOUSE_TYPE_TO_HOGQL_LABEL.get(raw_clickhouse_type, "string"),
+ "valid": True,
+ }
+
+
+def motherduck_columns_to_dwh_columns(columns: list[tuple[str, str, bool]]) -> dict[str, dict[str, Any]]:
+ return {
+ column_name: motherduck_column_to_dwh_column(column_name, duckdb_type, nullable)
+ for column_name, duckdb_type, nullable in columns
+ }
+
+
# Used by mixins.resolve_host for direct SQL-source connections (its own IP-pinning check).
# validate_warehouse_table_url_pattern below calls posthog.security.url_validation instead.
def _is_safe_public_ip(host: str) -> bool:
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.py
index cc8f88e307d5..f968a1d5c77e 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py
@@ -477,7 +477,7 @@ DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE = (
"Direct query mode is currently supported only for Postgres, MySQL, Snowflake, Redshift, and ClickHouse sources."
)
# Engines surfaced on a direct connection's `connection_metadata.engine` (duckdb backs direct Postgres).
-DIRECT_CONNECTION_ENGINE_CHOICES = ["duckdb", "postgres", "mysql", "snowflake", "redshift", "clickhouse"]
+DIRECT_CONNECTION_ENGINE_CHOICES = ["duckdb", "postgres", "mysql", "snowflake", "redshift", "clickhouse", "motherduck"]
def count_active_sources(team_id: int, source_type: str) -> int:
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 a7cd01d45cb5..68e4f29a0000 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
@@ -7,5 +7,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class MotherduckSourceConfig(config.Config):
access_token: str
- database: str
+ database: str | None = None
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
index 330842455419..036ecc35e5d4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/motherduck.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/motherduck.py
@@ -7,6 +7,13 @@ 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.
+The database name is optional. Left blank, the connection is account-wide
+(`md:`) and discovery spans every catalog the token can see, qualifying tables
+as `catalog.schema.table`; set, the connection pins that one catalog and tables
+stay `schema.table`. Either way a query runs against exactly one catalog: the
+pipeline issues `USE "<catalog>"` before it reads, so every catalog-scoped
+discovery query stays written against `current_database()`.
+
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).
@@ -18,6 +25,7 @@ import os
import re
import tempfile
import collections
+import dataclasses
from collections.abc import Iterator
from contextlib import contextmanager
from typing import Any, Optional
@@ -37,6 +45,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
IncrementalFieldFilter,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.location import (
+ ResolvedSourceLocation,
normalize_namespace,
resolve_source_location,
)
@@ -51,9 +60,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.types import IncrementalFieldType
__all__ = [
+ "MotherDuckConnectionError",
"MotherDuckImplementation",
"build_motherduck_connection_string",
+ "connect",
"filter_motherduck_incremental_fields",
+ "translate_motherduck_error",
]
_IDENTIFIER_QUOTER = AnsiIdentifierQuoter()
@@ -67,6 +79,18 @@ 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")
+# Catalogs MotherDuck and the client attach for their own bookkeeping — never user data. Only
+# consulted for an account-wide connection; pinning a database scopes discovery on its own.
+MOTHERDUCK_SYSTEM_DATABASES = ("md_information_schema", "system", "temp", "memory", "_duckdb_ui")
+
+# 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.
+MOTHERDUCK_ERROR_CLASSES = {
+ "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.",
+}
+
# Rows materialized per Arrow batch. Bounds resident memory: DuckDB shares this process.
DEFAULT_MOTHERDUCK_FETCH_SIZE = 5_000
@@ -86,20 +110,60 @@ DUCKDB_LOCAL_CONFIG: dict[str, Any] = {
_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.
+class MotherDuckConnectionError(Exception):
+ """A MotherDuck connection could not be opened, carrying a user-facing message."""
- 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.
+
+def build_motherduck_connection_string(database: Optional[str], access_token: str) -> str:
+ """Assemble the `md:[<database>]?motherduck_token=…` DSN duckdb expects.
+
+ A blank database yields the account-wide `md:` form, which attaches every database
+ the token can see. 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):
+ name = (database or "").strip()
+ if name and 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})}"
+ # `saas_mode` denies local filesystem access and extension installs. DuckDB runs in-process
+ # here, so without it a query could read the worker's disk.
+ params = urlencode({"motherduck_token": access_token, "saas_mode": "true"})
+ return f"md:{name}?{params}"
+
+
+def connect(access_token: str, database: Optional[str] = None, *, read_only: bool = True) -> duckdb.DuckDBPyConnection:
+ """Open a MotherDuck connection, translating driver errors to `MotherDuckConnectionError`.
+
+ Read-only by default: neither imports nor direct queries write, so DuckDB rejects every
+ write statement engine-side regardless of what the token is granted.
+ """
+ connection_string = build_motherduck_connection_string(database, access_token)
+ log_connection_open(db_host=MOTHERDUCK_SERVICE_HOST, via="vendor_https")
+ try:
+ return duckdb.connect(connection_string, read_only=read_only, config=dict(DUCKDB_LOCAL_CONFIG))
+ except duckdb.Error as e:
+ raise MotherDuckConnectionError(translate_motherduck_error(e)) from e
+
+
+def translate_motherduck_error(error: Exception) -> str:
+ """Turn a driver error into a message we can show the source's owner."""
+ message = str(error)
+ lowered = message.lower()
+ if "unauthenticated" in lowered or "invalid token" in lowered or "jwt" in lowered or "authenticat" in lowered:
+ return "Invalid MotherDuck token. Generate a new access token in MotherDuck settings and try again."
+ if "database" in lowered and ("not found" in lowered or "does not exist" in lowered):
+ return "Database not found. Check the database name, or leave it blank to connect to all databases."
+ if "compute limit" in lowered or "out of compute" in lowered:
+ return (
+ "Your MotherDuck plan has reached its compute limit. Queries may be slow or fail until the "
+ "limit resets. Upgrade your MotherDuck plan for more capacity."
+ )
+ for key, value in MOTHERDUCK_ERROR_CLASSES.items():
+ if key in message:
+ return value
+ # First line only: DuckDB appends multi-line candidate/hint blocks.
+ return message.splitlines()[0] if message.strip() else "Could not connect to MotherDuck."
def filter_motherduck_incremental_fields(
@@ -130,26 +194,54 @@ def filter_motherduck_incremental_fields(
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)`.
+def _default_catalog(config: MotherduckSourceConfig) -> Optional[str]:
+ """The catalog every table belongs to, or None when the source spans the account."""
+ return (config.database or "").strip() or None
+
+
+def _name_suffixes(name: str) -> list[str]:
+ """Progressively less-qualified forms of a dotted name, most qualified first.
+
+ `a.b.c` yields `b.c` then `c`, so a stored name can still be matched against a
+ discovery key that carries fewer qualifiers than it did when the row was created.
+ """
+ parts = name.split(".")
+ return [".".join(parts[i:]) for i in range(1, len(parts))]
+
+
+def _split_display_name(
+ display_name: str,
+ default_catalog: Optional[str],
+ default_schema: Optional[str],
+) -> tuple[Optional[str], Optional[str], str]:
+ """Split a discovery display name into `(catalog, 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.
+ Discovery qualifies a name with exactly the parts the config leaves open: an
+ account-wide source gets `catalog.schema.table`, a pinned database `schema.table`,
+ and a pinned database and schema a bare `table`. 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
+ parts = display_name.split(".", 2)
+ if len(parts) == 3:
+ catalog, schema, table = parts
+ return (
+ normalize_namespace(catalog) or default_catalog,
+ normalize_namespace(schema) or default_schema,
+ table,
+ )
+ if len(parts) == 2:
+ schema, table = parts
+ return default_catalog, (normalize_namespace(schema) or default_schema), table
+ return default_catalog, 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.
+ `duckdb_tables()` catalog functions. With a database pinned they stay scoped to
+ `current_database()`, so the client's own `memory`, `system` and `temp` catalogs
+ never surface as tables; account-wide they span every catalog except those.
Partition sizing is deliberately not implemented: DuckDB's catalog exposes an
estimated row count but no on-disk byte size for an attached MotherDuck
@@ -162,16 +254,33 @@ class MotherDuckImplementation(SQLSourceImplementation[MotherduckSourceConfig, A
# ------------------------------------------------------------------
@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))
+ def connect(self, config: MotherduckSourceConfig, catalog: Optional[str] = None) -> Iterator[Any]:
+ """Open a MotherDuck-backed DuckDB connection for the duration of the context.
+
+ `catalog` pins the connection's current database, so a caller reading one table
+ out of an account-wide source can keep using `current_database()`-scoped SQL.
+ """
+ connection = connect(config.access_token, config.database)
try:
+ # A pinned database is already the connection's current catalog, so switching is
+ # only needed when an account-wide source reaches into a specific one.
+ if catalog and catalog != _default_catalog(config):
+ connection.execute(f"USE {_IDENTIFIER_QUOTER.quote(catalog)}")
yield connection
finally:
connection.close()
+ def _catalog_predicate(self, config: MotherduckSourceConfig, column: str) -> tuple[str, list[str]]:
+ """Restrict a catalog-metadata query to the catalogs this source may read.
+
+ A pinned database narrows to `current_database()`; account-wide, every catalog
+ is in scope except MotherDuck's and the client's own bookkeeping ones.
+ """
+ if (config.database or "").strip():
+ return f"{column} = current_database()", []
+ placeholders = ", ".join("?" for _ in MOTHERDUCK_SYSTEM_DATABASES)
+ return f"{column} NOT IN ({placeholders})", list(MOTHERDUCK_SYSTEM_DATABASES)
+
# ------------------------------------------------------------------
# Listing — batch queries run once during `get_schemas`
# ------------------------------------------------------------------
@@ -183,7 +292,9 @@ class MotherDuckImplementation(SQLSourceImplementation[MotherduckSourceConfig, A
names: list[str] | None,
) -> dict[str, list[tuple[str, str, bool]]]:
selected_schema = normalize_namespace(config.schema)
- qualify = selected_schema is None
+ qualify_schema = selected_schema is None
+ qualify_catalog = not (config.database or "").strip()
+ catalog_clause, catalog_params = self._catalog_predicate(config, "c.table_catalog")
# 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
@@ -191,61 +302,77 @@ class MotherDuckImplementation(SQLSourceImplementation[MotherduckSourceConfig, A
# 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"
+ "SELECT c.table_catalog, 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()"
+ f" WHERE {catalog_clause}"
" AND t.table_type = 'BASE TABLE'"
)
- order = " ORDER BY c.table_schema ASC, c.table_name ASC, c.ordinal_position ASC"
+ order = " ORDER BY c.table_catalog ASC, 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()
+ result = conn.execute(
+ f"{select} AND c.table_schema = ?{order}", [*catalog_params, 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),
+ [*catalog_params, *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
+ for table_catalog, table_schema, table_name, column_name, data_type, is_nullable in result:
+ display_name = table_name
+ if qualify_schema:
+ display_name = f"{table_schema}.{display_name}"
+ if qualify_catalog:
+ display_name = f"{table_catalog}.{display_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.
+ # Match qualified (`[catalog.]schema.table`) and less-qualified names — a row requested
+ # by its qualified name can still map to a barer discovery key (or vice versa)
+ # mid-migration, e.g. after a source gains or drops its pinned database.
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]
+ continue
+ for suffix in _name_suffixes(name):
+ if suffix in available:
+ filtered[name] = available[suffix]
+ break
return filtered
return dict(schema_list)
- def _display_names_by_pair(
+ def _display_names_by_location(
self,
config: MotherduckSourceConfig,
tables: list[str],
- ) -> dict[tuple[str, str], str]:
- """Index the requested display names by their `(schema, table)` pair."""
+ ) -> dict[tuple[Optional[str], str, str], str]:
+ """Index the requested display names by their `(catalog, schema, table)` triple.
+
+ The catalog is left `None` when the source pins a database, because the catalog
+ functions are then already restricted to it and don't need to disambiguate.
+ """
+ default_catalog = _default_catalog(config)
default_schema = normalize_namespace(config.schema)
- pairs: dict[tuple[str, str], str] = {}
+ # Only an account-wide source sees more than one catalog, so only it needs the catalog
+ # to tell two same-named tables apart.
+ key_by_catalog = default_catalog is None
+ locations: dict[tuple[Optional[str], str, str], str] = {}
for display_name in tables:
- schema, table = _split_display_name(display_name, default_schema)
+ catalog, schema, table = _split_display_name(display_name, default_catalog, default_schema)
if schema is None:
continue
- pairs[(schema, table)] = display_name
- return pairs
+ locations[(catalog if key_by_catalog else None, schema, table)] = display_name
+ return locations
def get_primary_keys(
self,
@@ -264,20 +391,23 @@ class MotherDuckImplementation(SQLSourceImplementation[MotherduckSourceConfig, A
if not tables:
return result
- display_by_pair = self._display_names_by_pair(config, tables)
+ display_by_location = self._display_names_by_location(config, tables)
+ key_by_catalog = _default_catalog(config) is None
+ catalog_clause, catalog_params = self._catalog_predicate(config, "database_name")
try:
rows = conn.execute(
- "SELECT schema_name, table_name, constraint_column_names"
+ "SELECT database_name, schema_name, table_name, constraint_column_names"
" FROM duckdb_constraints()"
- " WHERE database_name = current_database() AND constraint_type = 'PRIMARY KEY'"
+ f" WHERE {catalog_clause} AND constraint_type = 'PRIMARY KEY'",
+ catalog_params,
).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))
+ for database_name, schema_name, table_name, columns in rows:
+ display_key = display_by_location.get((database_name if key_by_catalog else None, schema_name, table_name))
if display_key is None or not columns:
continue
result[display_key] = list(columns)
@@ -300,20 +430,23 @@ class MotherDuckImplementation(SQLSourceImplementation[MotherduckSourceConfig, A
if not tables:
return result
- display_by_pair = self._display_names_by_pair(config, tables)
+ display_by_location = self._display_names_by_location(config, tables)
+ key_by_catalog = _default_catalog(config) is None
+ catalog_clause, catalog_params = self._catalog_predicate(config, "database_name")
try:
rows = conn.execute(
- "SELECT schema_name, table_name, estimated_size"
+ "SELECT database_name, schema_name, table_name, estimated_size"
" FROM duckdb_tables()"
- " WHERE database_name = current_database()"
+ f" WHERE {catalog_clause}",
+ catalog_params,
).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))
+ for database_name, schema_name, table_name, estimated_size in rows:
+ display_key = display_by_location.get((database_name if key_by_catalog else None, schema_name, table_name))
if display_key is None or estimated_size is None:
continue
result[display_key] = int(estimated_size)
@@ -327,13 +460,14 @@ class MotherDuckImplementation(SQLSourceImplementation[MotherduckSourceConfig, A
tables: list[str],
) -> SourceMetadata:
"""Stamp catalog/schema/table per discovered table so per-row routing can pin a namespace."""
+ default_catalog = _default_catalog(config)
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
+ catalog, schema, table = _split_display_name(display_name, default_catalog, default_schema)
+ catalog_by_table[display_name] = catalog
schema_by_table[display_name] = schema
table_name_by_table[display_name] = table
return SourceMetadata(
@@ -387,22 +521,53 @@ class MotherDuckImplementation(SQLSourceImplementation[MotherduckSourceConfig, A
# Pipeline build — the `SourceResponse` for a single table
# ------------------------------------------------------------------
+ def _resolve_location(
+ self, config: MotherduckSourceConfig, inputs: SourceInputs
+ ) -> tuple[Optional[str], ResolvedSourceLocation]:
+ """Resolve `(catalog, location)` for one row.
+
+ The shared resolver splits a dotted name on its first dot, so it would read the
+ catalog of a three-part `catalog.schema.table` as the schema. The prefix is removed
+ before delegating, then `response_name` is taken from the untouched name so the Delta
+ folder stays unique across two catalogs holding the same `schema.table`.
+ """
+ metadata = inputs.schema_metadata if isinstance(inputs.schema_metadata, dict) else {}
+ source_catalog = metadata.get("source_catalog")
+ catalog = source_catalog if isinstance(source_catalog, str) and source_catalog else None
+
+ has_location = bool(metadata.get("source_schema")) and bool(metadata.get("source_table_name"))
+ resolver_inputs = inputs
+ if not has_location and inputs.schema_name.count(".") == 2:
+ prefix, _, remainder = inputs.schema_name.partition(".")
+ catalog = catalog or normalize_namespace(prefix)
+ resolver_inputs = dataclasses.replace(inputs, schema_name=remainder)
+
+ location = resolve_source_location(resolver_inputs, config_namespace=config.schema)
+ if resolver_inputs is not inputs:
+ location = location._replace(
+ response_name=resolve_source_location(inputs, config_namespace=config.schema).response_name
+ )
+ return catalog or _default_catalog(config), location
+
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)
+ # Per-row routing: a row pins its own namespace via `schema_metadata`, falling back to
+ # `config.schema` and the source's database. An account-wide source reaches several
+ # catalogs, so the catalog is per row too and the connection is pinned to it below.
+ catalog, location = self._resolve_location(config, inputs)
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")
+ if not catalog:
+ raise ValueError(f"Could not resolve the MotherDuck database for table '{inputs.schema_name}'")
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:
+ with self.connect(config, catalog=catalog) as connection:
primary_keys = self.get_primary_keys_for_table(connection, schema, table_name)
query = _QUERY_BUILDER.select_all(
schema=schema,
@@ -417,7 +582,7 @@ class MotherDuckImplementation(SQLSourceImplementation[MotherduckSourceConfig, A
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:
+ with self.connect(config, catalog=catalog) 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
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 3706871f88dd..5a09ee6be771 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,4 +1,6 @@
-from typing import Optional, cast
+from collections.abc import Iterator
+from contextlib import contextmanager
+from typing import TYPE_CHECKING, Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
@@ -18,19 +20,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
MotherduckSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.motherduck.motherduck import (
+ MOTHERDUCK_ERROR_CLASSES,
+ MotherDuckConnectionError,
MotherDuckImplementation,
+ connect,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
-_MOTHERDUCK_IMPLEMENTATION = MotherDuckImplementation()
+if TYPE_CHECKING:
+ import duckdb
-# 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.",
-}
+_MOTHERDUCK_IMPLEMENTATION = MotherDuckImplementation()
@SourceRegistry.register
@@ -52,10 +52,16 @@ class MotherduckSource(SQLSource[MotherduckSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.MOTHERDUCK,
category=DataWarehouseSourceCategory.DATABASES,
- keywords=["sql", "duckdb"],
+ keywords=["sql", "duckdb", "md"],
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.",
+ caption=(
+ "Enter your MotherDuck access token to query or pull your MotherDuck tables into the "
+ "PostHog Data warehouse. Create an access token in your MotherDuck account settings. "
+ "Leave the database blank to connect to every database in the account. Connections are "
+ "opened read-only, so PostHog never modifies your data."
+ ),
iconPath="/static/services/motherduck.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/motherduck",
releaseStatus=ReleaseStatus.ALPHA,
fields=cast(
list[FieldType],
@@ -70,10 +76,10 @@ class MotherduckSource(SQLSource[MotherduckSourceConfig]):
),
SourceFieldInputConfig(
name="database",
- label="Database",
+ label="Database (optional)",
type=SourceFieldInputConfigType.TEXT,
- required=True,
- placeholder="my_db",
+ required=False,
+ placeholder="Leave blank to connect to all databases",
secret=False,
),
SourceFieldInputConfig(
@@ -94,8 +100,28 @@ class MotherduckSource(SQLSource[MotherduckSourceConfig]):
"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.",
+ "Invalid MotherDuck token": None,
+ "UNAUTHENTICATED": "Your MotherDuck token is invalid or expired. Generate a new access token and reconnect.",
}
+ @staticmethod
+ def normalized_database(config: MotherduckSourceConfig) -> str | None:
+ """The configured database, or None when the source spans the whole account."""
+ return (config.database or "").strip() or None
+
+ @contextmanager
+ def direct_query_connection(self, config: MotherduckSourceConfig) -> Iterator["duckdb.DuckDBPyConnection"]:
+ """Open a read-only connection for a single direct (HogQL) query.
+
+ Connection construction is an internal detail of the source; the direct-SQL adapter
+ drives queries through this method rather than importing the driver helpers.
+ """
+ connection = connect(config.access_token, self.normalized_database(config))
+ try:
+ yield connection
+ finally:
+ connection.close()
+
def validate_credentials(
self,
config: MotherduckSourceConfig,
@@ -105,11 +131,11 @@ class MotherduckSource(SQLSource[MotherduckSourceConfig]):
) -> 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 MotherDuckConnectionError as e:
+ return False, str(e)
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.
@@ -121,7 +147,7 @@ class MotherduckSource(SQLSource[MotherduckSourceConfig]):
False,
"MotherDuck rejected the access token. Check that the token is correct and has not expired.",
)
- for key, value in MotherDuckErrors.items():
+ for key, value in MOTHERDUCK_ERROR_CLASSES.items():
if key in error_msg:
return False, value
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
index f23263704a5c..c6f891a48846 100644
--- 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
@@ -14,9 +14,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.temporal.data_imports.sources.motherduck.motherduck import (
DEFAULT_MOTHERDUCK_FETCH_SIZE,
DUCKDB_LOCAL_CONFIG,
+ MOTHERDUCK_SYSTEM_DATABASES,
MotherDuckImplementation,
build_motherduck_connection_string,
filter_motherduck_incremental_fields,
+ translate_motherduck_error,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.motherduck.source import MotherduckSource
from products.warehouse_sources.backend.types import IncrementalFieldType
@@ -69,13 +71,25 @@ class TestMotherDuck:
# ------------------------------------------------------------------
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"
+ assert (
+ build_motherduck_connection_string(" my_db ", "to ken/+=")
+ == "md:my_db?motherduck_token=to+ken%2F%2B%3D&saas_mode=true"
+ )
+
+ @pytest.mark.parametrize("database", ["", " ", None])
+ def test_connection_string_without_a_database_is_account_wide(self, database):
+ # A blank database attaches every database the token can see, rather than failing.
+ assert (
+ build_motherduck_connection_string(database, "md-token") == "md:?motherduck_token=md-token&saas_mode=true"
+ )
+
+ def test_connection_string_pins_saas_mode(self):
+ # DuckDB runs in-process here, so the DSN must deny local file access and extension installs.
+ assert "saas_mode=true" in build_motherduck_connection_string("my_db", "md-token")
@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",
@@ -92,6 +106,22 @@ class TestMotherDuck:
with pytest.raises(ValueError):
build_motherduck_connection_string("my_db", "")
+ @pytest.mark.parametrize(
+ "raw,expected_fragment",
+ [
+ ("UNAUTHENTICATED: jwt expired", "Invalid MotherDuck token"),
+ (
+ "Error: You've reached the daily compute limit for this plan. Upgrade to get more capacity.",
+ "reached its compute limit",
+ ),
+ ("Catalog Error: Table with name nope does not exist", "Can't find that database or schema"),
+ # Unmapped errors surface their first line only (DuckDB appends candidate/hint blocks).
+ ("Parser Error: syntax error at or near\nCandidate bindings: ...", "Parser Error: syntax error at or near"),
+ ],
+ )
+ def test_translate_error_maps_driver_failures_to_user_messages(self, raw, expected_fragment):
+ assert expected_fragment in translate_motherduck_error(Exception(raw))
+
# ------------------------------------------------------------------
# Incremental field types
# ------------------------------------------------------------------
@@ -127,9 +157,24 @@ class TestMotherDuck:
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"
+ assert mock_connect.call_args.args[0] == "md:my_db?motherduck_token=md-token&saas_mode=true"
# DuckDB shares this process, so it must not size itself against the whole host.
assert mock_connect.call_args.kwargs["config"] == DUCKDB_LOCAL_CONFIG
+ # Neither imports nor direct queries write, so writes are refused engine-side.
+ assert mock_connect.call_args.kwargs["read_only"] is True
+
+ def test_connect_pins_the_catalog_when_given_one(self, impl):
+ with patch(_CONNECT_PATH) as mock_connect:
+ with impl.connect(_make_config(database=None), catalog="other_db"):
+ pass
+ # `USE` lets every catalog-scoped discovery query stay written against current_database().
+ mock_connect.return_value.execute.assert_called_once_with('USE "other_db"')
+
+ def test_connect_without_a_catalog_does_not_switch_database(self, impl):
+ with patch(_CONNECT_PATH) as mock_connect:
+ with impl.connect(_make_config()):
+ pass
+ mock_connect.return_value.execute.assert_not_called()
def test_connect_uses_a_writable_home_directory(self):
# Regression: DuckDB defaults extension/secrets storage to `~/.duckdb`, which raised
@@ -159,9 +204,9 @@ class TestMotherDuck:
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"),
+ ("my_db", "analytics", "users", "id", "BIGINT", "NO"),
+ ("my_db", "analytics", "users", "email", "VARCHAR", "YES"),
+ ("my_db", "analytics", "orders", "id", "BIGINT", "NO"),
]
result = impl.get_columns(conn, _make_config(), names=None)
# Single-schema source keeps bare table names.
@@ -181,9 +226,9 @@ class TestMotherDuck:
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"),
+ ("my_db", "analytics", "users", "id", "BIGINT", "NO"),
+ ("my_db", "sales", "users", "id", "BIGINT", "NO"),
+ ("my_db", "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.
@@ -192,6 +237,25 @@ class TestMotherDuck:
assert "table_schema NOT IN (?, ?)" in sql
assert params == ["information_schema", "pg_catalog"]
+ @pytest.mark.parametrize("blank", ["", " ", None])
+ def test_get_columns_blank_database_spans_catalogs_fully_qualified(self, impl, blank):
+ conn = _conn()
+ conn.fetchall.return_value = [
+ ("warehouse", "sales", "users", "id", "BIGINT", "NO"),
+ ("staging", "sales", "users", "id", "BIGINT", "NO"),
+ ]
+ result = impl.get_columns(conn, _make_config(database=blank, schema=""), names=None)
+ # Same schema and table in two catalogs must stay distinct.
+ assert set(result.keys()) == {"warehouse.sales.users", "staging.sales.users"}
+
+ def test_get_columns_blank_database_excludes_bookkeeping_catalogs(self, impl):
+ # MotherDuck and the client attach `system`, `temp` and friends — never customer data.
+ conn = _conn()
+ impl.get_columns(conn, _make_config(database="", schema=""), names=None)
+ sql, params = conn.execute.call_args.args
+ assert "c.table_catalog NOT IN (" in sql
+ assert params[: len(MOTHERDUCK_SYSTEM_DATABASES)] == list(MOTHERDUCK_SYSTEM_DATABASES)
+
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
@@ -204,8 +268,8 @@ class TestMotherDuck:
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"),
+ ("my_db", "analytics", "users", "id", "BIGINT", "NO"),
+ ("my_db", "analytics", "orders", "id", "BIGINT", "NO"),
]
assert list(impl.get_columns(conn, _make_config(), names=["users"]).keys()) == ["users"]
@@ -213,13 +277,13 @@ class TestMotherDuck:
# 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")]
+ conn.fetchall.return_value = [("my_db", "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"])]
+ conn.fetchall.return_value = [("my_db", "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.
@@ -228,8 +292,8 @@ class TestMotherDuck:
def test_get_primary_keys_routes_to_qualified_display_names(self, impl):
conn = _conn()
conn.fetchall.return_value = [
- ("analytics", "users", ["id"]),
- ("sales", "users", ["uuid"]),
+ ("my_db", "analytics", "users", ["id"]),
+ ("my_db", "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"]}
@@ -243,9 +307,9 @@ class TestMotherDuck:
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),
+ ("my_db", "analytics", "users", 1_200),
+ ("my_db", "analytics", "orders", None),
+ ("my_db", "analytics", "unrequested", 5),
]
out = impl.get_row_counts(conn, _make_config(), tables=["users", "orders"])
assert out == {"users": 1_200, "orders": None}
@@ -266,6 +330,17 @@ class TestMotherDuck:
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_source_metadata_account_wide_stamps_each_rows_catalog(self, impl):
+ # Without a per-row catalog the pipeline could not tell which database to `USE`.
+ meta = impl.get_source_metadata(
+ MagicMock(),
+ _make_config(database="", schema=""),
+ tables=["warehouse.sales.users", "staging.sales.users"],
+ )
+ assert meta.catalog_by_table == {"warehouse.sales.users": "warehouse", "staging.sales.users": "staging"}
+ assert meta.schema_by_table == {"warehouse.sales.users": "sales", "staging.sales.users": "sales"}
+ assert meta.table_name_by_table == {"warehouse.sales.users": "users", "staging.sales.users": "users"}
+
def test_get_primary_keys_for_table_scopes_the_lookup(self, impl):
conn = _conn()
conn.fetchall.return_value = [(["id", "tenant_id"],)]
@@ -362,6 +437,49 @@ class TestMotherDuck:
# The PK probe targets the resolved namespace too.
assert metadata_conn.execute.call_args_list[0].args[1] == ["sales", "users"]
+ def test_build_pipeline_account_wide_row_switches_to_its_own_catalog(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(database="", schema=""), _make_inputs(schema_name="warehouse.sales.users")
+ )
+ assert response.name == "warehouse_sales_users"
+ list(response.items())
+
+ # The catalog is pinned per row, so the table reference itself stays two-part.
+ assert metadata_conn.execute.call_args_list[0].args[0] == 'USE "warehouse"'
+ assert 'FROM "sales"."users"' in streaming_conn.execute.call_args.args[0]
+
+ def test_build_pipeline_prefers_the_stamped_catalog_over_the_display_name(self, impl):
+ # Discovery stamps the real location; a renamed row must follow the stamp, not its label.
+ 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(database="", schema=""),
+ _make_inputs(
+ schema_name="stale.label.users",
+ schema_metadata={
+ "source_catalog": "warehouse",
+ "source_schema": "sales",
+ "source_table_name": "users",
+ },
+ ),
+ )
+ list(response.items())
+
+ assert metadata_conn.execute.call_args_list[0].args[0] == 'USE "warehouse"'
+ assert 'FROM "sales"."users"' in streaming_conn.execute.call_args.args[0]
+
+ def test_build_pipeline_rejects_an_unresolvable_catalog(self, impl):
+ # Account-wide with nothing naming a catalog: `USE` would be a guess, and the sync would
+ # silently read whichever database DuckDB happens to resolve to.
+ with patch(_CONNECT_PATH) as mock_connect:
+ with pytest.raises(ValueError):
+ impl.build_pipeline(_make_config(database=""), _make_inputs(schema_name="users"))
+ mock_connect.assert_not_called()
+
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.
@@ -409,17 +527,18 @@ class TestMotherDuck:
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)
+ def test_validate_credentials_requires_an_access_token(self, source):
+ ok, message = source.validate_credentials(_make_config(access_token=""), team_id=1)
assert ok is False
- assert message is not None and expected_fragment in message
+ assert message is not None and "access token" in message
+
+ @pytest.mark.parametrize("database", ["", " ", None])
+ def test_validate_credentials_accepts_a_blank_database(self, source, database):
+ # Blank means "every database in the account", so it must not be rejected up front.
+ with patch.object(MotherduckSource, "get_schemas", return_value=[]):
+ ok, message = source.validate_credentials(_make_config(database=database), team_id=1)
+ assert ok is True
+ assert message is None
@pytest.mark.parametrize(
"error,expected_fragment",
diff --git a/products/warehouse_sources/backend/types.py b/products/warehouse_sources/backend/types.py
index 772244a0826e..3b512da9fa21 100644
--- a/products/warehouse_sources/backend/types.py
+++ b/products/warehouse_sources/backend/types.py
@@ -1349,6 +1349,7 @@ DIRECT_ENGINE_BY_SOURCE_TYPE: dict[str, str] = {
ExternalDataSourceType.REDSHIFT: "redshift",
ExternalDataSourceType.CLICKHOUSE: "clickhouse",
ExternalDataSourceType.CLICKHOUSECLOUD: "clickhouse",
+ ExternalDataSourceType.MOTHERDUCK: "motherduck",
}
diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.ts
index 6ab374ac0b88..7a30847b2e9f 100644
--- a/products/warehouse_sources/frontend/generated/api.schemas.ts
+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts
@@ -3045,6 +3045,7 @@ export const AccessMethodEnumApi = {
* * `snowflake` - snowflake
* * `redshift` - redshift
* * `clickhouse` - clickhouse
+ * * `motherduck` - motherduck
*/
export type EngineEnumApi = (typeof EngineEnumApi)[keyof typeof EngineEnumApi]
@@ -3055,6 +3056,7 @@ export const EngineEnumApi = {
Snowflake: 'snowflake',
Redshift: 'redshift',
Clickhouse: 'clickhouse',
+ Motherduck: 'motherduck',
} as const
export interface ExternalDataSourceRevenueAnalyticsConfigApi {
@@ -3115,7 +3117,8 @@ export interface ExternalDataSourceSerializersApi {
* * `mysql` - mysql
* * `snowflake` - snowflake
* * `redshift` - redshift
- * * `clickhouse` - clickhouse */
+ * * `clickhouse` - clickhouse
+ * * `motherduck` - motherduck */
readonly engine: EngineEnumApi | null
/** @nullable */
readonly last_run_at: string | null
@@ -4553,7 +4556,8 @@ export interface PatchedExternalDataSourceSerializersApi {
* * `mysql` - mysql
* * `snowflake` - snowflake
* * `redshift` - redshift
- * * `clickhouse` - clickhouse */
+ * * `clickhouse` - clickhouse
+ * * `motherduck` - motherduck */
readonly engine?: EngineEnumApi | null
/** @nullable */
readonly last_run_at?: string | null
@@ -4680,7 +4684,8 @@ export interface ExternalDataSourceConnectionOptionApi {
* * `mysql` - mysql
* * `snowflake` - snowflake
* * `redshift` - redshift
- * * `clickhouse` - clickhouse */
+ * * `clickhouse` - clickhouse
+ * * `motherduck` - motherduck */
readonly engine: EngineEnumApi | null
/** The source type (e.g. 'Postgres', 'MySQL', 'Snowflake').
*
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 26da79d49c35..e2a5c4ff5f1b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -27312,6 +27312,7 @@ export namespace Schemas {
* * `snowflake` - snowflake
* * `redshift` - redshift
* * `clickhouse` - clickhouse
+ * * `motherduck` - motherduck
*/
export type EngineEnum = typeof EngineEnum[keyof typeof EngineEnum];
@@ -27323,6 +27324,7 @@ export namespace Schemas {
Snowflake: 'snowflake',
Redshift: 'redshift',
Clickhouse: 'clickhouse',
+ Motherduck: 'motherduck',
} as const;
export interface EngineeringAnalyticsCIBrokenDefaultBranchSignalExtra {
@@ -32193,7 +32195,8 @@ export namespace Schemas {
* * `mysql` - mysql
* * `snowflake` - snowflake
* * `redshift` - redshift
- * * `clickhouse` - clickhouse */
+ * * `clickhouse` - clickhouse
+ * * `motherduck` - motherduck */
readonly engine: EngineEnum | null;
/** The source type (e.g. 'Postgres', 'MySQL', 'Snowflake').
*
@@ -34962,7 +34965,8 @@ export namespace Schemas {
* * `mysql` - mysql
* * `snowflake` - snowflake
* * `redshift` - redshift
- * * `clickhouse` - clickhouse */
+ * * `clickhouse` - clickhouse
+ * * `motherduck` - motherduck */
readonly engine: EngineEnum | null;
/** @nullable */
readonly last_run_at: string | null;
@@ -55653,7 +55657,8 @@ export namespace Schemas {
* * `mysql` - mysql
* * `snowflake` - snowflake
* * `redshift` - redshift
- * * `clickhouse` - clickhouse */
+ * * `clickhouse` - clickhouse
+ * * `motherduck` - motherduck */
readonly engine?: EngineEnum | null;
/** @nullable */
readonly last_run_at?: string | null;