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): support import syncs for the trino source (#110681)

Tom Owers7daab300f5c8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/source.py
index 7683c2c24909..8acbf636060d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/source.py
@@ -12,13 +12,22 @@ from products.warehouse_sources.backend.facade.source_config import (
SourceFieldSelectConfigConverter,
SourceFieldSelectConfigOption,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import ValidateDatabaseHostMixin
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (
+ build_incremental_fields,
+ resolve_detected_primary_keys,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.base import SQLSource
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.trino import TrinoSourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.trino.trino import (
+ TRINO_COLUMN_NOT_FOUND_ERROR,
TRINO_KNOWN_ERROR_MESSAGES,
+ TRINO_SCHEMA_NOT_FOUND_ERROR,
+ TRINO_TABLE_NOT_FOUND_ERROR,
+ TrinoImplementation,
TrinoSchemaDiscoveryError,
connect_trino,
discover_trino_schemas,
@@ -27,13 +36,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.trino.trin
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+_TRINO_IMPLEMENTATION = TrinoImplementation()
+
@SourceRegistry.register
-class TrinoSource(SimpleSource[TrinoSourceConfig], ValidateDatabaseHostMixin):
- supports_column_selection = True
- supports_scheduled_sync = False
+class TrinoSource(SQLSource[TrinoSourceConfig], ValidateDatabaseHostMixin):
api_docs_url = "https://trino.io/docs/current/client/python.html"
+ @property
+ def get_implementation(self) -> TrinoImplementation:
+ return _TRINO_IMPLEMENTATION
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.TRINO
@@ -49,7 +62,6 @@ class TrinoSource(SimpleSource[TrinoSourceConfig], ValidateDatabaseHostMixin):
iconPath="/static/services/trino.svg",
docsUrl="https://posthog.com/docs/cdp/sources/trino",
releaseStatus=ReleaseStatus.ALPHA,
- unreleasedSource=True,
fields=cast(
list[FieldType],
[
@@ -215,18 +227,29 @@ class TrinoSource(SimpleSource[TrinoSourceConfig], ValidateDatabaseHostMixin):
raise ValueError(error or "Invalid Trino host.")
with trino_failures_as_discovery_error(), connect_trino(config) as connection:
discovered = discover_trino_schemas(connection.cursor(), config, names)
- return [
- SourceSchema(
- name=table.name if config.schema else f"{table.schema}.{table.name}",
- supports_incremental=False,
- supports_append=False,
- columns=[(column.name, column.data_type, column.nullable) for column in table.columns],
- source_catalog=table.catalog,
- source_schema=table.schema,
- source_table_name=table.name,
+
+ # Built from the discovered tables rather than through `SQLSource.get_schemas`, because a
+ # schema name can contain a dot (nested Iceberg namespaces), so the display name alone
+ # cannot be split back into its schema and table.
+ incremental_filter = self.get_implementation.get_incremental_filter()
+ schemas: list[SourceSchema] = []
+ for table in discovered:
+ columns = [(column.name, column.data_type, column.nullable) for column in table.columns]
+ incremental_fields = incremental_filter(columns)
+ schemas.append(
+ SourceSchema(
+ name=table.name if config.schema else f"{table.schema}.{table.name}",
+ supports_incremental=bool(incremental_fields),
+ supports_append=bool(incremental_fields),
+ incremental_fields=build_incremental_fields(incremental_fields),
+ columns=columns,
+ source_catalog=table.catalog,
+ source_schema=table.schema,
+ source_table_name=table.name,
+ detected_primary_keys=resolve_detected_primary_keys(None, columns),
+ )
)
- for table in discovered
- ]
+ return schemas
def get_non_retryable_errors(self) -> dict[str, str | None]:
# Schema discovery hands back Trino's own verdict, so the API must show it. The message keys
@@ -240,6 +263,13 @@ class TrinoSource(SimpleSource[TrinoSourceConfig], ValidateDatabaseHostMixin):
# filed. Closing that gap needs a shared classifier across the schema-discovery views, not a
# per-source key. Mirrors the note on the Stripe source.
return {
+ **self.default_non_retryable_errors(),
**{message: message for message in TRINO_KNOWN_ERROR_MESSAGES},
+ TRINO_TABLE_NOT_FOUND_ERROR: TRINO_TABLE_NOT_FOUND_ERROR,
+ # A query failure names its Trino error code in the text, for example
+ # `TrinoUserError(type=USER_ERROR, name=TABLE_NOT_FOUND, ...)`.
+ "name=TABLE_NOT_FOUND": TRINO_TABLE_NOT_FOUND_ERROR,
+ "name=SCHEMA_NOT_FOUND": TRINO_SCHEMA_NOT_FOUND_ERROR,
+ "name=COLUMN_NOT_FOUND": TRINO_COLUMN_NOT_FOUND_ERROR,
TrinoSchemaDiscoveryError.__name__: None,
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/tests/test_trino.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/tests/test_trino.py
index d7d0ecaefd06..471043e75eea 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/tests/test_trino.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/tests/test_trino.py
@@ -1,13 +1,23 @@
+import datetime as dt
+from collections.abc import Iterable
from contextlib import nullcontext
+from decimal import Decimal
+from typing import Any, cast
+from uuid import UUID
+from zoneinfo import ZoneInfo
import pytest
from unittest.mock import MagicMock, patch
-from trino.exceptions import TrinoExternalError
+import pyarrow as pa
+from trino.exceptions import HttpError, TrinoConnectionError, TrinoExternalError, TrinoUserError
+from trino.types import NamedRowTuple
from products.warehouse_sources.backend.presentation.views.external_data_source.helpers import (
_classify_refresh_schemas_error,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.trino import (
TrinoAuthTypeConfig,
TrinoSourceConfig,
@@ -20,11 +30,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.trino.trin
TRINO_CREDENTIALS_REQUIRE_TLS_VERIFICATION_ERROR,
DiscoveredTrinoTable,
TrinoColumn,
+ TrinoImplementation,
TrinoSchemaDiscoveryError,
+ build_trino_select,
connect_trino,
discover_trino_schemas,
+ filter_trino_incremental_fields,
trino_error_to_message,
+ trino_failures_as_sync_error,
)
+from products.warehouse_sources.backend.types import IncrementalFieldType
def _config(**overrides: object) -> TrinoSourceConfig:
@@ -309,8 +324,417 @@ def test_discover_trino_schemas_fetches_columns_in_bounded_batches() -> None:
assert all(len(call.args[1]) <= 101 for call in column_calls)
-def test_trino_source_is_direct_only() -> None:
+_TRINO_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.trino.trino"
+
+
+def _inputs(schema_name: str, **overrides: Any) -> SourceInputs:
+ values: dict[str, Any] = {
+ "schema_name": schema_name,
+ "schema_id": "schema-id",
+ "source_id": "source-id",
+ "team_id": 1,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-id",
+ "logger": MagicMock(),
+ "reset_pipeline": False,
+ }
+ values.update(overrides)
+ return SourceInputs(**values)
+
+
+class _FakeTrinoCursor:
+ def __init__(
+ self,
+ tables: dict[tuple[str, str], list[tuple[str, str, str]]],
+ rows: list[tuple[Any, ...]] | None = None,
+ ) -> None:
+ self.tables = tables
+ self.rows = list(rows or [])
+ self.executed: list[tuple[str, list[Any]]] = []
+ self.description: list[tuple[str]] | None = None
+ self._result: list[tuple[Any, ...]] = []
+
+ def execute(self, sql: str, params: list[Any] | None = None) -> None:
+ self.executed.append((sql, list(params or [])))
+ if "information_schema.columns" in sql:
+ schema, table = params or []
+ self._result = list(self.tables.get((schema, table), []))
+ elif sql.startswith("SELECT COUNT(*)"):
+ self._result = [(len(self.rows),)]
+ else:
+ columns = next(iter(self.tables.values()))
+ self.description = [(name,) for name, _, _ in columns]
+
+ def fetchall(self) -> list[tuple[Any, ...]]:
+ return self._result
+
+ def fetchone(self) -> tuple[Any, ...] | None:
+ return self._result[0] if self._result else None
+
+ def fetchmany(self, size: int) -> list[tuple[Any, ...]]:
+ page, self.rows = self.rows[:size], self.rows[size:]
+ return page
+
+ @property
+ def data_queries(self) -> list[tuple[str, list[Any]]]:
+ return [(sql, params) for sql, params in self.executed if sql.startswith("SELECT ") and 'FROM "hive".' in sql]
+
+
+def _run_pipeline(
+ config: TrinoSourceConfig, inputs: SourceInputs, cursor: _FakeTrinoCursor
+) -> tuple[Any, list[pa.Table]]:
+ connection = MagicMock()
+ connection.cursor.return_value = cursor
+ with (
+ patch(f"{_TRINO_MODULE}.connect_trino", side_effect=lambda *args, **kwargs: nullcontext(connection)),
+ patch.object(TrinoImplementation, "is_database_host_valid", return_value=(True, None)),
+ ):
+ response = TrinoImplementation().build_pipeline(config, inputs)
+ tables = list(cast(Iterable[pa.Table], response.items()))
+ return response, tables
+
+
+ ("config_schema", "schema_name", "schema_metadata", "expected_table", "expected_response_name"),
+ [
+ (
+ None,
+ "analytics.events",
+ {"source_schema": "analytics", "source_table_name": "events"},
+ '"analytics"."events"',
+ "analytics_events",
+ ),
+ (
+ None,
+ "sales.events",
+ {"source_schema": "sales", "source_table_name": "events"},
+ '"sales"."events"',
+ "sales_events",
+ ),
+ # A nested Iceberg namespace holds a dot, so only the stored metadata can split the name.
+ (
+ None,
+ "lake.raw.events",
+ {"source_schema": "lake.raw", "source_table_name": "events"},
+ '"lake.raw"."events"',
+ "lake_raw_events",
+ ),
+ (None, "analytics.events", None, '"analytics"."events"', "analytics_events"),
+ ("analytics", "events", None, '"analytics"."events"', "events"),
+ ],
+)
+def test_build_pipeline_reads_each_table_from_its_own_schema(
+ config_schema: str | None,
+ schema_name: str,
+ schema_metadata: dict[str, str] | None,
+ expected_table: str,
+ expected_response_name: str,
+) -> None:
+ location = (schema_metadata or {}).get("source_schema") or "analytics"
+ cursor = _FakeTrinoCursor({(location, "events"): [("id", "bigint", "NO")]}, rows=[(1,)])
+
+ response, _ = _run_pipeline(
+ _config(schema=config_schema), _inputs(schema_name, schema_metadata=schema_metadata), cursor
+ )
+
+ assert cursor.data_queries[-1][0] == f'SELECT "id" FROM "hive".{expected_table}'
+ assert response.name == expected_response_name
+ assert response.primary_keys == ["id"]
+
+
+ ("enabled_columns", "incremental", "expected_sql", "expected_params"),
+ [
+ (None, None, 'SELECT "id", "we""ird", "dotted.name", "updated_at" FROM "hive"."s"."t"', []),
+ (
+ ["dotted.name"],
+ None,
+ 'SELECT "dotted.name", "id" FROM "hive"."s"."t"',
+ [],
+ ),
+ (
+ ['we"ird'],
+ (
+ "updated_at",
+ IncrementalFieldType.Timestamp,
+ dt.datetime(2026, 1, 2, 3, 4, 5, tzinfo=ZoneInfo("Europe/Berlin")),
+ ),
+ 'SELECT "we""ird", "id", "updated_at" FROM "hive"."s"."t" WHERE "updated_at" > ? ORDER BY "updated_at" ASC',
+ # The column has no time zone, so the UTC watermark is compared as a plain timestamp.
+ [dt.datetime(2026, 1, 2, 2, 4, 5)],
+ ),
+ (
+ None,
+ ("id", IncrementalFieldType.Integer, 42),
+ 'SELECT "id", "we""ird", "dotted.name", "updated_at" FROM "hive"."s"."t" WHERE "id" > ? ORDER BY "id" ASC',
+ [42],
+ ),
+ ],
+ ids=["full_refresh", "projection_keeps_key", "incremental_watermark_to_utc", "integer"],
+)
+def test_build_pipeline_query(
+ enabled_columns: list[str] | None,
+ incremental: tuple[str, IncrementalFieldType, Any] | None,
+ expected_sql: str,
+ expected_params: list[Any],
+) -> None:
+ cursor = _FakeTrinoCursor(
+ {
+ ("s", "t"): [
+ ("id", "bigint", "NO"),
+ ('we"ird', "varchar", "YES"),
+ ("dotted.name", "varchar", "YES"),
+ ("updated_at", "timestamp(3)", "YES"),
+ ]
+ }
+ )
+ incremental_inputs: dict[str, Any] = {}
+ if incremental is not None:
+ field, field_type, last_value = incremental
+ incremental_inputs = {
+ "should_use_incremental_field": True,
+ "incremental_field": field,
+ "incremental_field_type": field_type,
+ "db_incremental_field_last_value": last_value,
+ }
+
+ _run_pipeline(_config(schema="s"), _inputs("t", enabled_columns=enabled_columns, **incremental_inputs), cursor)
+
+ assert cursor.data_queries[-1] == (expected_sql, expected_params)
+
+
+def test_build_pipeline_ignores_the_incremental_field_on_a_full_refresh() -> None:
+ cursor = _FakeTrinoCursor({("s", "t"): [("id", "bigint", "NO"), ("updated_at", "timestamp(3)", "YES")]})
+
+ _run_pipeline(
+ _config(schema="s"),
+ _inputs(
+ "t",
+ should_use_incremental_field=False,
+ incremental_field="updated_at",
+ incremental_field_type=IncrementalFieldType.Timestamp,
+ db_incremental_field_last_value=dt.datetime(2026, 1, 1),
+ ),
+ cursor,
+ )
+
+ assert cursor.data_queries[-1] == ('SELECT "id", "updated_at" FROM "hive"."s"."t"', [])
+
+
+def test_build_pipeline_quotes_the_catalog() -> None:
+ query = build_trino_select(
+ catalog='my"catalog',
+ schema="s",
+ table_name="t",
+ columns=[],
+ incremental_field=None,
+ incremental_field_type=None,
+ incremental_last_value=None,
+ enabled_columns=None,
+ primary_keys=None,
+ row_filters=None,
+ )
+
+ assert query.sql == 'SELECT * FROM "my""catalog"."s"."t"'
+
+
+ ("column_type", "last_value", "expected"),
+ [
+ ("timestamp(6) with time zone", dt.datetime(2026, 1, 1, 12), dt.datetime(2026, 1, 1, 12, tzinfo=dt.UTC)),
+ ("timestamp(6) with time zone", None, dt.datetime(1970, 1, 1, tzinfo=ZoneInfo("UTC"))),
+ ("timestamp(3)", dt.datetime(2026, 1, 1, 12, tzinfo=dt.UTC), dt.datetime(2026, 1, 1, 12)),
+ ("timestamp(3)", None, dt.datetime(1970, 1, 1)),
+ ],
+)
+def test_incremental_watermark_matches_the_column_time_zone(
+ column_type: str, last_value: dt.datetime | None, expected: dt.datetime
+) -> None:
+ cursor = _FakeTrinoCursor({("s", "t"): [("id", "bigint", "NO"), ("ts", column_type, "YES")]})
+
+ _run_pipeline(
+ _config(schema="s"),
+ _inputs(
+ "t",
+ should_use_incremental_field=True,
+ incremental_field="ts",
+ incremental_field_type=IncrementalFieldType.Timestamp,
+ db_incremental_field_last_value=last_value,
+ ),
+ cursor,
+ )
+
+ (param,) = cursor.data_queries[-1][1]
+ assert param == expected
+ assert (param.tzinfo is None) == (expected.tzinfo is None)
+
+
+def test_build_pipeline_converts_trino_values_to_arrow() -> None:
+ columns = [
+ ("id", "bigint", "NO"),
+ ("amount", "decimal(12,2)", "YES"),
+ ("created_at", "timestamp(3)", "YES"),
+ ("seen_at", "timestamp(3) with time zone", "YES"),
+ ("day", "date", "YES"),
+ ("payload", "row(a bigint, b varchar)", "YES"),
+ ("tags", "array(row(n bigint))", "YES"),
+ ("attrs", "map(varchar, decimal(4,1))", "YES"),
+ ("doc", "json", "YES"),
+ ("uid", "uuid", "YES"),
+ ("local_time", "time(3) with time zone", "YES"),
+ ]
+ row = (
+ 7,
+ Decimal("12.50"),
+ dt.datetime(2026, 3, 1, 8, 30),
+ dt.datetime(2026, 3, 1, 8, 30, tzinfo=ZoneInfo("America/New_York")),
+ dt.date(2026, 3, 1),
+ NamedRowTuple([1, "x"], ["a", "b"], ["bigint", "varchar"]),
+ [NamedRowTuple([2], ["n"], ["bigint"])],
+ {"k": Decimal("1.5")},
+ '{"already": "json"}',
+ UUID("12345678-1234-5678-1234-567812345678"),
+ dt.time(9, 15, tzinfo=dt.timezone(dt.timedelta(hours=2))),
+ )
+ cursor = _FakeTrinoCursor({("s", "t"): columns}, rows=[row])
+
+ _, tables = _run_pipeline(_config(schema="s"), _inputs("t"), cursor)
+
+ (table,) = tables
+ assert table.schema.field("amount").type == pa.decimal128(12, 2)
+ assert table.schema.field("created_at").type == pa.timestamp("us")
+ assert table.schema.field("seen_at").type == pa.timestamp("us", tz="UTC")
+ assert table.schema.field("day").type == pa.date32()
+ assert table.to_pylist() == [
+ {
+ "id": 7,
+ "amount": Decimal("12.50"),
+ "created_at": dt.datetime(2026, 3, 1, 8, 30),
+ "seen_at": dt.datetime(2026, 3, 1, 13, 30, tzinfo=dt.UTC),
+ "day": dt.date(2026, 3, 1),
+ "payload": '{"a": 1, "b": "x"}',
+ "tags": '[{"n": 2}]',
+ "attrs": '{"k": "1.5"}',
+ "doc": '{"already": "json"}',
+ "uid": "12345678-1234-5678-1234-567812345678",
+ "local_time": "09:15:00+02:00",
+ }
+ ]
+
+
+def test_build_pipeline_fails_permanently_when_the_table_is_gone() -> None:
+ cursor = _FakeTrinoCursor({})
+
+ with pytest.raises(ValueError) as raised:
+ _run_pipeline(_config(schema="s"), _inputs("t"), cursor)
+
+ assert error_message_matches(str(raised.value), TrinoSource().get_non_retryable_errors())
+
+
+def test_build_pipeline_refuses_a_disallowed_host_before_connecting() -> None:
+ with (
+ patch(f"{_TRINO_MODULE}.connect_trino") as mock_connect,
+ patch.object(TrinoImplementation, "is_database_host_valid", return_value=(False, "Host not allowed")),
+ pytest.raises(ValueError, match="Host not allowed"),
+ ):
+ TrinoImplementation().build_pipeline(_config(schema="s"), _inputs("t"))
+
+ mock_connect.assert_not_called()
+
+
+ ("data_type", "expected"),
+ [
+ ("timestamp(3)", IncrementalFieldType.Timestamp),
+ ("timestamp(6) with time zone", IncrementalFieldType.Timestamp),
+ ("date", IncrementalFieldType.Date),
+ ("bigint", IncrementalFieldType.Integer),
+ ("tinyint", IncrementalFieldType.Integer),
+ ("decimal(38,0)", IncrementalFieldType.Numeric),
+ ("array(timestamp(3))", None),
+ ("row(updated_at timestamp(3))", None),
+ ("varchar(255)", None),
+ ("double", None),
+ ("time(3)", None),
+ ],
+)
+def test_filter_trino_incremental_fields(data_type: str, expected: IncrementalFieldType | None) -> None:
+ result = filter_trino_incremental_fields([("column", data_type, True)])
+
+ assert result == ([("column", expected, True)] if expected is not None else [])
+
+
+def test_get_schemas_advertises_incremental_fields_per_table() -> None:
+ discovered = [
+ DiscoveredTrinoTable(
+ catalog="hive",
+ schema="analytics",
+ name="events",
+ columns=(
+ TrinoColumn(name="id", data_type="bigint", nullable=False),
+ TrinoColumn(name="updated_at", data_type="timestamp(3)", nullable=True),
+ ),
+ ),
+ DiscoveredTrinoTable(
+ catalog="hive",
+ schema="lake.raw",
+ name="events",
+ columns=(TrinoColumn(name="name", data_type="varchar", nullable=True),),
+ ),
+ ]
source = TrinoSource()
- assert source.supports_scheduled_sync is False
- assert source.get_source_config.unreleasedSource is True
+ with (
+ patch.object(TrinoSource, "is_database_host_valid", return_value=(True, None)),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.trino.source.connect_trino",
+ return_value=nullcontext(MagicMock()),
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.trino.source.discover_trino_schemas",
+ return_value=discovered,
+ ),
+ ):
+ schemas = source.get_schemas(_config(), team_id=1)
+
+ by_name = {schema.name: schema for schema in schemas}
+ assert set(by_name) == {"analytics.events", "lake.raw.events"}
+ assert [field["field"] for field in by_name["analytics.events"].incremental_fields] == ["id", "updated_at"]
+ assert by_name["analytics.events"].supports_incremental is True
+ assert by_name["analytics.events"].detected_primary_keys == ["id"]
+ assert by_name["lake.raw.events"].supports_incremental is False
+ assert (by_name["lake.raw.events"].source_schema, by_name["lake.raw.events"].source_table_name) == (
+ "lake.raw",
+ "events",
+ )
+
+
+def _trino_user_error(name: str, message: str) -> TrinoUserError:
+ return TrinoUserError(
+ {"message": message, "errorName": name, "errorCode": 1, "errorType": "USER_ERROR", "failureInfo": {}},
+ "20260902_120000_00000_abcde",
+ )
+
+
+ ("error", "is_permanent"),
+ [
+ (_trino_user_error("PERMISSION_DENIED", "Access Denied: Cannot select from table hive.s.t"), True),
+ (HttpError("error 401: b'Unauthorized'"), True),
+ (_trino_user_error("TABLE_NOT_FOUND", "line 1:15: Table 'hive.s.t' does not exist"), True),
+ (_trino_user_error("COLUMN_NOT_FOUND", "line 1:8: Column 'gone' cannot be resolved"), True),
+ (_trino_external_error("Failed to query OPA backend"), False),
+ (TrinoConnectionError("failed to execute: ('Connection aborted.', ConnectionResetError(104))"), False),
+ ],
+ ids=["access_denied", "unauthorized", "table_not_found", "column_not_found", "opa_unavailable", "connection_reset"],
+)
+def test_sync_failures_are_classified_for_retry(error: Exception, is_permanent: bool) -> None:
+ with pytest.raises(Exception) as raised:
+ with trino_failures_as_sync_error():
+ raise error
+
+ assert error_message_matches(str(raised.value), TrinoSource().get_non_retryable_errors()) is is_permanent
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py
index 7a2493b890c2..a55b24060889 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py
@@ -1,17 +1,56 @@
from __future__ import annotations
-from collections.abc import Iterator
+import re
+import json
+import datetime as dt
+from collections.abc import Callable, Iterator, Mapping
from contextlib import contextmanager
from itertools import batched
from typing import TYPE_CHECKING, Any
+import pyarrow as pa
from requests.exceptions import RequestException
from posthog.dataclasses import frozen
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
+ DEFAULT_NUMERIC_PRECISION,
+ DEFAULT_NUMERIC_SCALE,
+ BinaryColumnReporter,
+ build_pyarrow_decimal_type,
+ restrict_schema_to_columns,
+ table_from_iterator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import DEFAULT_CHUNK_SIZE
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_value
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import log_connection_open
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (
+ ValidateDatabaseHostMixin,
+ log_connection_open,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.primary_keys import resolve_merge_keys
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (
+ AnsiIdentifierQuoter,
+ Column,
+ Table,
+ resolve_table_projection,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.batching import fetch_row_batches
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.implementation import (
+ SQLSourceImplementation,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.incremental import (
+ IncrementalFieldFilter,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.location import resolve_source_location
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.query_builder import (
+ ParamStyle,
+ SafeSQL,
+ SelectQueryBuilder,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.trino import TrinoSourceConfig
+from products.warehouse_sources.backend.types import IncrementalFieldType
if TYPE_CHECKING:
from trino.dbapi import Connection, Cursor
@@ -36,6 +75,17 @@ TRINO_TLS_CERTIFICATE_ERROR = (
"Check the certificate or turn off certificate verification."
)
TRINO_CONNECTION_ERROR = "PostHog could not connect to Trino."
+TRINO_TABLE_NOT_FOUND_ERROR = (
+ "Trino could not find this table, or this user can no longer see its columns. "
+ "Check that the table still exists and that the user can read it, then resync."
+)
+TRINO_SCHEMA_NOT_FOUND_ERROR = (
+ "Trino could not find the schema for this table. Check that it still exists, then refresh the schemas."
+)
+TRINO_COLUMN_NOT_FOUND_ERROR = (
+ "A column this table syncs no longer exists in Trino. Refresh the schemas so PostHog picks up the new "
+ "columns, then resync."
+)
# Every message `trino_error_to_message` produces for a recognized failure. The source lists them as
# its own error patterns, so the API shows the message instead of a generic one.
@@ -48,6 +98,16 @@ TRINO_KNOWN_ERROR_MESSAGES = (
TRINO_TLS_CERTIFICATE_ERROR,
TRINO_CONNECTION_ERROR,
)
+# The subset of those failures that a retry of an import sync cannot fix. A broken connection, an
+# unreachable access control service and a TLS failure can all clear on their own, so a sync retries them.
+TRINO_PERMANENT_SYNC_ERROR_MESSAGES = frozenset(
+ {
+ TRINO_CREDENTIALS_REQUIRE_TLS_VERIFICATION_ERROR,
+ TRINO_AUTHENTICATION_ERROR,
+ TRINO_CATALOG_NOT_FOUND_ERROR,
+ TRINO_ACCESS_DENIED_ERROR,
+ }
+)
POSTHOG_MANAGED_TRINO_HOSTS = frozenset(
{
"trino.dw.dev.postwh.com",
@@ -147,7 +207,7 @@ def _authentication(config: TrinoSourceConfig) -> Any:
@contextmanager
-def connect_trino(config: TrinoSourceConfig) -> Iterator[Connection]:
+def connect_trino(config: TrinoSourceConfig, *, timezone: str | None = None) -> Iterator[Connection]:
from trino.dbapi import connect # noqa: PLC0415 — keeps the optional driver off startup paths
if config.auth_type.selection != "none":
@@ -177,6 +237,7 @@ def connect_trino(config: TrinoSourceConfig) -> Iterator[Connection]:
http_session=session,
request_timeout=60,
verify=config.verify_ssl,
+ timezone=timezone,
)
yield connection
finally:
@@ -241,3 +302,396 @@ def discover_trino_schemas(
)
for (schema_name, table_name), columns in tables.items()
]
+
+
+class TrinoSyncError(Exception):
+ """A Trino failure during an import sync that a retry cannot fix.
+
+ The message is one of `TRINO_PERMANENT_SYNC_ERROR_MESSAGES`, already worded for the person who
+ owns the source.
+ """
+
+
+@contextmanager
+def trino_failures_as_sync_error() -> Iterator[None]:
+ """Reword a permanent Trino failure so the sync stops retrying it.
+
+ Every other failure keeps its original type and text, so a transient one stays retryable.
+ """
+ from trino.exceptions import Error, HttpError # noqa: PLC0415 — keeps the optional driver off startup paths
+
+ try:
+ yield
+ except (Error, HttpError, TrinoConfigurationError) as exc:
+ message = trino_error_to_message(exc)
+ if message in TRINO_PERMANENT_SYNC_ERROR_MESSAGES:
+ raise TrinoSyncError(message) from exc
+ raise
+
+
+_TRINO_INTEGER_TYPES = frozenset({"tinyint", "smallint", "integer", "int", "bigint"})
+_TRINO_NESTED_TYPE_PREFIXES = ("array(", "map(", "row(")
+_TRINO_TYPE_PARAMETERS = re.compile(r"\(\s*\d+\s*(?:,\s*\d+\s*)?\)")
+_TRINO_DECIMAL_TYPE = re.compile(r"^(?:decimal|numeric)\(\s*(\d+)\s*(?:,\s*(\d+)\s*)?\)$")
+
+
+def _normalize_trino_type(data_type: str) -> str:
+ return " ".join(data_type.strip().lower().split())
+
+
+def _base_trino_type(data_type: str) -> str:
+ """`timestamp(3) with time zone` becomes `timestamp with time zone`, `varchar(255)` becomes `varchar`."""
+ return _TRINO_TYPE_PARAMETERS.sub("", _normalize_trino_type(data_type)).strip()
+
+
+def _is_nested_trino_type(data_type: str) -> bool:
+ normalized = _normalize_trino_type(data_type)
+ return normalized == "json" or normalized.startswith(_TRINO_NESTED_TYPE_PREFIXES)
+
+
+def trino_type_to_arrow(data_type: str) -> pa.DataType:
+ """Map a Trino `information_schema.columns.data_type` onto the Arrow type the import writes."""
+ if _is_nested_trino_type(data_type):
+ return pa.string()
+
+ decimal_match = _TRINO_DECIMAL_TYPE.match(_normalize_trino_type(data_type))
+ if decimal_match is not None:
+ precision = int(decimal_match.group(1))
+ scale = int(decimal_match.group(2) or 0)
+ return build_pyarrow_decimal_type(precision, scale)
+
+ match _base_trino_type(data_type):
+ case "boolean":
+ return pa.bool_()
+ case "tinyint":
+ return pa.int8()
+ case "smallint":
+ return pa.int16()
+ case "integer" | "int":
+ return pa.int32()
+ case "bigint":
+ return pa.int64()
+ case "real":
+ return pa.float32()
+ case "double":
+ return pa.float64()
+ case "decimal" | "numeric":
+ return build_pyarrow_decimal_type(DEFAULT_NUMERIC_PRECISION, DEFAULT_NUMERIC_SCALE)
+ case "date":
+ return pa.date32()
+ case "timestamp":
+ return pa.timestamp("us")
+ case "timestamp with time zone":
+ return pa.timestamp("us", tz="UTC")
+ case "time":
+ return pa.time64("us")
+ case "varbinary":
+ return pa.binary()
+ case _:
+ # varchar, char, uuid, ipaddress, intervals, `time with time zone` and any connector
+ # specific type. Text keeps every value readable.
+ return pa.string()
+
+
+def _json_default(value: Any) -> Any:
+ if isinstance(value, bytes | bytearray):
+ return value.hex()
+ if isinstance(value, dt.datetime | dt.date | dt.time):
+ return value.isoformat()
+ # Decimal, UUID, intervals and IP addresses keep their exact text form.
+ return str(value)
+
+
+def _jsonable(value: Any) -> Any:
+ # The driver returns a ROW value as a tuple that carries its field names in `_names`.
+ # `json.dumps` would write a plain list and lose them.
+ names = getattr(value, "_names", None)
+ if isinstance(value, tuple) and isinstance(names, list):
+ if all(isinstance(name, str) for name in names) and len(set(names)) == len(names):
+ return {name: _jsonable(item) for name, item in zip(names, value)}
+ return [_jsonable(item) for item in value]
+ if isinstance(value, list | tuple):
+ return [_jsonable(item) for item in value]
+ if isinstance(value, Mapping):
+ return {str(key): _jsonable(item) for key, item in value.items()}
+ return value
+
+
+def _to_json_text(value: Any) -> str:
+ # A `json` column already arrives as JSON text.
+ if isinstance(value, str):
+ return value
+ return json.dumps(_jsonable(value), default=_json_default)
+
+
+def _to_text(value: Any) -> str:
+ if isinstance(value, str):
+ return value
+ if isinstance(value, dt.time):
+ return value.isoformat()
+ return str(value)
+
+
+def trino_value_converter(data_type: str) -> Callable[[Any], Any] | None:
+ """Return the conversion a driver value needs to fit `trino_type_to_arrow(data_type)`, if any."""
+ if _is_nested_trino_type(data_type):
+ return _to_json_text
+ if pa.types.is_string(trino_type_to_arrow(data_type)):
+ return _to_text
+ return None
+
+
+class TrinoArrowColumn(Column):
+ """A Trino column as the import pipeline reads it."""
+
+ def __init__(self, name: str, data_type: str, nullable: bool) -> None:
+ self.name = name
+ self.data_type = data_type
+ self.nullable = nullable
+
+ def to_arrow_field(self) -> pa.Field[pa.DataType]:
+ return pa.field(self.name, trino_type_to_arrow(self.data_type), nullable=self.nullable)
+
+
+def filter_trino_incremental_fields(
+ columns: list[tuple[str, str, bool]],
+) -> list[tuple[str, IncrementalFieldType, bool]]: # nosemgrep: tuple-return-prefer-dataclass -- SQLSource protocol
+ results: list[tuple[str, IncrementalFieldType, bool]] = []
+ for column_name, data_type, nullable in columns:
+ if _is_nested_trino_type(data_type):
+ continue
+ base_type = _base_trino_type(data_type)
+ if base_type in ("timestamp", "timestamp with time zone"):
+ results.append((column_name, IncrementalFieldType.Timestamp, nullable))
+ elif base_type == "date":
+ results.append((column_name, IncrementalFieldType.Date, nullable))
+ elif base_type in _TRINO_INTEGER_TYPES:
+ results.append((column_name, IncrementalFieldType.Integer, nullable))
+ elif base_type in ("decimal", "numeric"):
+ results.append((column_name, IncrementalFieldType.Numeric, nullable))
+ return results
+
+
+class TrinoIdentifierQuoter(AnsiIdentifierQuoter):
+ """ANSI quoting that prefixes every table reference with the source's catalog.
+
+ The read then names `"catalog"."schema"."table"` and does not depend on the session catalog.
+ """
+
+ def __init__(self, catalog: str) -> None:
+ self.catalog = catalog
+
+ def quote_qualified(self, *parts: str) -> str:
+ return super().quote_qualified(self.catalog, *parts)
+
+
+def incremental_value_for_trino_column(
+ value: Any,
+ field_type: IncrementalFieldType,
+ column_type: str | None,
+) -> Any:
+ """Return the watermark in the same time zone form as the column it filters.
+
+ Trino compares a `timestamp` with a `timestamp with time zone` through the session time zone,
+ and that conversion can also stop the connector from pushing the filter down. The stored
+ watermark and the initial value are UTC, so the value is converted to the column's own form.
+ """
+ if value is None:
+ value = incremental_type_to_initial_value(field_type)
+ if not isinstance(value, dt.datetime) or column_type is None:
+ return value
+ base_type = _base_trino_type(column_type)
+ if base_type == "timestamp with time zone" and value.tzinfo is None:
+ return value.replace(tzinfo=dt.UTC)
+ if base_type == "timestamp" and value.tzinfo is not None:
+ return value.astimezone(dt.UTC).replace(tzinfo=None)
+ return value
+
+
+def build_trino_select(
+ *,
+ catalog: str,
+ schema: str,
+ table_name: str,
+ columns: list[TrinoArrowColumn],
+ incremental_field: str | None,
+ incremental_field_type: IncrementalFieldType | None,
+ incremental_last_value: Any,
+ enabled_columns: list[str] | None,
+ primary_keys: list[str] | None,
+ row_filters: Any,
+) -> SafeSQL:
+ last_value = incremental_last_value
+ if incremental_field is not None and incremental_field_type is not None:
+ column_type = next((column.data_type for column in columns if column.name == incremental_field), None)
+ last_value = incremental_value_for_trino_column(incremental_last_value, incremental_field_type, column_type)
+ builder = SelectQueryBuilder(quoter=TrinoIdentifierQuoter(catalog), param_style=ParamStyle.QMARK)
+ return builder.select_all(
+ schema=schema,
+ table_name=table_name,
+ incremental_field=incremental_field,
+ incremental_field_type=incremental_field_type,
+ incremental_last_value=last_value,
+ enabled_columns=enabled_columns,
+ primary_keys=primary_keys,
+ row_filters=row_filters,
+ )
+
+
+def _row_to_dict(column_names: list[str], converters: list[Callable[[Any], Any] | None], row: Any) -> dict[str, Any]:
+ return {
+ name: converter(value) if converter is not None and value is not None else value
+ for name, converter, value in zip(column_names, converters, row)
+ }
+
+
+@frozen
+class TrinoReadPlan:
+ query: SafeSQL
+ arrow_schema: pa.Schema
+ column_names: list[str]
+ converters: dict[str, Callable[[Any], Any] | None]
+
+
+class TrinoImplementation(SQLSourceImplementation[TrinoSourceConfig, Any, Any], ValidateDatabaseHostMixin):
+ """Trino driver implementation paired with `TrinoSource`.
+
+ Trino exposes no primary-key metadata for most connectors, so the merge key comes from the
+ schema's stored key or an `id` column. Partition sizing is not implemented: a cheap row and byte
+ estimate depends on the connector and can cost a table scan, so the base class falls back to
+ default partition settings.
+ """
+
+ @contextmanager
+ def connect(self, config: TrinoSourceConfig, *, team_id: int | None = None) -> Iterator[Any]:
+ if team_id is not None:
+ is_valid, error = self.is_database_host_valid(config.host, team_id)
+ if not is_valid:
+ raise ValueError(error or "Invalid Trino host.")
+ # A UTC session makes any time zone conversion Trino still does in a filter deterministic.
+ with connect_trino(config, timezone="UTC") as connection:
+ yield connection
+
+ def get_columns(
+ self,
+ conn: Any,
+ config: TrinoSourceConfig,
+ names: list[str] | None,
+ ) -> dict[str, list[tuple[str, str, bool]]]: # nosemgrep: tuple-return-prefer-dataclass -- SQLSource protocol
+ return {
+ table.name if config.schema else f"{table.schema}.{table.name}": [
+ (column.name, column.data_type, column.nullable) for column in table.columns
+ ]
+ for table in discover_trino_schemas(conn.cursor(), config, names)
+ }
+
+ def get_incremental_filter(self) -> IncrementalFieldFilter:
+ return filter_trino_incremental_fields
+
+ def get_trino_table(self, cursor: Any, catalog: str, schema: str, table_name: str) -> Table[TrinoArrowColumn]:
+ quoted_catalog = AnsiIdentifierQuoter().quote(catalog)
+ cursor.execute(
+ "SELECT column_name, data_type, is_nullable "
+ f"FROM {quoted_catalog}.information_schema.columns "
+ "WHERE table_schema = ? AND table_name = ? "
+ "ORDER BY ordinal_position",
+ [schema, table_name],
+ )
+ columns = [
+ TrinoArrowColumn(name=str(name), data_type=str(data_type), nullable=str(is_nullable).upper() == "YES")
+ for name, data_type, is_nullable in cursor.fetchall()
+ ]
+ if not columns:
+ raise ValueError(TRINO_TABLE_NOT_FOUND_ERROR)
+ return Table(name=table_name, parents=(catalog, schema), columns=columns)
+
+ def build_pipeline(self, config: TrinoSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ # The catalog is fixed per connection. The schema comes from the row's own metadata, so a
+ # source with a blank schema field reads each `schema.table` from its own namespace.
+ location = resolve_source_location(inputs, config_namespace=config.schema)
+ schema = location.schema
+ table_name = location.table_name
+ if not table_name:
+ raise ValueError("Table name is missing")
+ if not schema:
+ raise ValueError("Schema is missing")
+
+ catalog = config.catalog
+ 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
+
+ def plan_read(cursor: Any, primary_keys: list[str] | None) -> TrinoReadPlan:
+ full_table = self.get_trino_table(cursor, catalog, schema, table_name)
+ projection = resolve_table_projection(
+ full_table,
+ enabled_columns=inputs.enabled_columns,
+ primary_keys=primary_keys,
+ incremental_field=incremental_field,
+ )
+ query = build_trino_select(
+ catalog=catalog,
+ schema=schema,
+ table_name=table_name,
+ columns=full_table.columns,
+ incremental_field=incremental_field,
+ incremental_field_type=incremental_field_type,
+ incremental_last_value=inputs.db_incremental_field_last_value,
+ enabled_columns=projection.enabled_columns,
+ primary_keys=primary_keys,
+ row_filters=inputs.row_filters,
+ )
+ return TrinoReadPlan(
+ query=query,
+ arrow_schema=projection.table.to_arrow_schema(),
+ column_names=[column.name for column in projection.table.columns],
+ converters={
+ column.name: trino_value_converter(column.data_type) for column in projection.table.columns
+ },
+ )
+
+ with trino_failures_as_sync_error(), self.connect(config, team_id=inputs.team_id) as connection:
+ cursor = connection.cursor()
+ columns = self.get_trino_table(cursor, catalog, schema, table_name).columns
+ primary_keys = resolve_merge_keys(inputs.primary_keys, None, [column.name for column in columns])
+ setup_plan = plan_read(cursor, primary_keys)
+ rows_to_sync = self.get_rows_to_sync(cursor, setup_plan.query.sql, setup_plan.query.params, logger)
+
+ def get_rows() -> Iterator[pa.Table]:
+ binary_reporter = BinaryColumnReporter(logger)
+ with trino_failures_as_sync_error(), self.connect(config, team_id=inputs.team_id) as connection:
+ cursor = connection.cursor()
+ # Re-read the catalog right before the read, because the setup plan can be minutes
+ # old. See `resolve_table_projection`.
+ try:
+ read_plan = plan_read(cursor, primary_keys)
+ except Exception as e:
+ logger.debug(f"Could not re-read the Trino catalog before streaming: {e}", exc_info=e)
+ read_plan = setup_plan
+
+ logger.debug(f"Trino query: {read_plan.query.sql}")
+ cursor.execute(read_plan.query.sql, read_plan.query.params)
+ column_names = (
+ [str(description[0]) for description in cursor.description]
+ if cursor.description
+ else read_plan.column_names
+ )
+ arrow_schema = restrict_schema_to_columns(read_plan.arrow_schema, column_names)
+ converters = [read_plan.converters.get(name) for name in column_names]
+
+ for rows in fetch_row_batches(
+ cursor.fetchmany, max_rows=DEFAULT_CHUNK_SIZE, byte_bounded=inputs.byte_bounded_extraction
+ ):
+ yield table_from_iterator(
+ (_row_to_dict(column_names, converters, row) for row in rows),
+ arrow_schema,
+ primary_keys=primary_keys,
+ binary_reporter=binary_reporter,
+ )
+
+ return SourceResponse(
+ name=location.response_name,
+ items=get_rows,
+ primary_keys=primary_keys,
+ rows_to_sync=rows_to_sync,
+ )
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index 32dad1813ffd..cef4bd12c9a5 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -132,6 +132,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.set
)
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source import StripeSource
from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.utils import TikTokAdsAPIError
+from products.warehouse_sources.backend.temporal.data_imports.sources.trino.source import TrinoSource
def _configure_source_mock_versioning(mock_get_source) -> None:
@@ -723,17 +724,72 @@ class TestExternalDataSource(APIBaseTest):
"direct_trino_table": "events",
}
- def test_create_trino_rejects_warehouse_mode(self):
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.trino.source.TrinoSource.get_schemas",
+ return_value=[
+ SourceSchema(
+ name="analytics.events",
+ supports_incremental=True,
+ supports_append=True,
+ columns=[("id", "bigint", False), ("updated_at", "timestamp(3)", True)],
+ source_catalog="hive",
+ source_schema="analytics",
+ source_table_name="events",
+ detected_primary_keys=["id"],
+ )
+ ],
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.trino.source.TrinoSource.validate_credentials",
+ return_value=(True, None),
+ )
+ def test_create_warehouse_trino_source_syncs_incrementally(self, _mock_validate, _mock_get_schemas):
response = self.client.post(
f"/api/environments/{self.team.pk}/external_data_sources/",
data={
"source_type": "Trino",
"created_via": "web",
"access_method": "warehouse",
- "payload": {},
+ "payload": {
+ "host": "trino.example.com",
+ "port": 443,
+ "catalog": "hive",
+ "schema": "",
+ "auth_type": {"selection": "password", "user": "posthog", "password": "secret"},
+ "use_ssl": True,
+ "verify_ssl": True,
+ "schemas": [
+ {
+ "name": "analytics.events",
+ "should_sync": True,
+ "sync_type": "incremental",
+ "incremental_field": "updated_at",
+ "incremental_field_type": "timestamp",
+ }
+ ],
+ },
},
)
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ source = ExternalDataSource.objects.get(pk=response.json()["id"])
+ schema = ExternalDataSchema.objects.get(source=source, name="analytics.events")
+ assert source.access_method == ExternalDataSource.AccessMethod.WAREHOUSE
+ assert schema.sync_type == ExternalDataSchema.SyncType.INCREMENTAL
+ assert schema.incremental_field == "updated_at"
+
+ def test_create_rejects_warehouse_mode_for_a_direct_only_source(self):
+ with patch.object(TrinoSource, "supports_scheduled_sync", False):
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/",
+ data={
+ "source_type": "Trino",
+ "created_via": "web",
+ "access_method": "warehouse",
+ "payload": {},
+ },
+ )
+
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json() == {"message": "Trino is available only as a direct connection."}