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 Select Star import source (#84451)

Tom Owers7276a3107f8a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/selectstar.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/selectstar.py
index 70570488047c..84275da2db4c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/selectstar.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/selectstar.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class SelectStarSourceConfig(config.Config):
- pass
+ api_token: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/canonical_descriptions.py
new file mode 100644
index 000000000000..7984380af028
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/canonical_descriptions.py
@@ -0,0 +1,97 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://docs.selectstar.com/select-star-api/overview"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Tables": {
+ "description": "A table or view discovered in a connected data source, with its ownership, "
+ "documentation, and usage metadata.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "guid": "Select Star's unique identifier for the table.",
+ "database": "The database this table belongs to.",
+ "schema": "The schema this table belongs to, if the data source has schemas.",
+ "name": "The table's name.",
+ "search_name": "Full path for the table, e.g. DATABASE.SCHEMA.TABLE.",
+ "description": "The active description shown in Select Star (user, ingested, or AI-generated).",
+ "updated_on": "When this table's metadata was last updated in Select Star.",
+ "created_on": "When this table's metadata record was created in Select Star.",
+ "db_created_on": "When this table was created in the underlying data source.",
+ "last_updated_on": "When this table was last modified in the data source, per its information schema.",
+ "last_queried_on": "When this table was last queried.",
+ "last_refreshed_on": "When this table was last modified in the data source (excluding SELECT queries).",
+ },
+ },
+ "Columns": {
+ "description": "A column on a table, with its data type, key/constraint flags, and documentation.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "guid": "Select Star's unique identifier for the column.",
+ "table": "The table this column belongs to.",
+ "search_name": "Full path for the column, e.g. DATABASE.SCHEMA.TABLE.COLUMN.",
+ "name": "The column's name.",
+ "is_primary_key": "Whether this column is part of the table's primary key.",
+ "is_foreign_key": "Whether this column is a foreign key.",
+ "is_unique": "Whether the column's values are unique, where determinable.",
+ "is_nullable": "Whether the column's values are nullable, where determinable.",
+ "data_type": "The column's type, mapped to a Select Star type.",
+ "external_type": "The column's native type as reported by the data source.",
+ "ordinal": "The column's position within the table.",
+ "description": "The active description shown in Select Star.",
+ },
+ },
+ "Databases": {
+ "description": "A database (or catalog) within a connected data source.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "guid": "Select Star's unique identifier for the database.",
+ "name": "The database's name.",
+ "search_name": "Full path for the database, which is just its name.",
+ "description": "The active description shown in Select Star.",
+ },
+ },
+ "Schemas": {
+ "description": "A schema within a database in a connected data source.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "guid": "Select Star's unique identifier for the schema.",
+ "database": "The database this schema belongs to.",
+ "name": "The schema's name.",
+ "search_name": "Full path for the schema, e.g. DATABASE.SCHEMA.",
+ "description": "The active description shown in Select Star.",
+ },
+ },
+ "Tags": {
+ "description": "A tag applied to tables, columns, or other assets for classification and governance.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "guid": "Select Star's unique identifier for the tag.",
+ "type": "The tag's type (e.g. category or status tag).",
+ "name": "The tag's display name.",
+ "description": "The active description shown in Select Star.",
+ "parent": "The GUID of the parent tag, for hierarchical tags.",
+ "visible": "Whether the tag is visible in the Select Star UI.",
+ "count": "How many assets carry this tag.",
+ "updated_on": "When the tag was last updated.",
+ "is_auto_generated": "Whether the tag was auto-generated by Select Star rather than a user.",
+ },
+ },
+ "Dashboards": {
+ "description": "A BI dashboard (Looker, Tableau, and similar tools) discovered by Select Star, "
+ "with its ownership and usage metadata.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "guid": "Select Star's unique identifier for the dashboard.",
+ "name": "The dashboard's name.",
+ "description": "The active description shown in Select Star.",
+ "url": "The full URL of the dashboard in its source BI tool.",
+ "dashboard_created_at": "When the dashboard was created, per the BI tool.",
+ "dashboard_updated_at": "When the dashboard was last updated, per the BI tool.",
+ "last_successful_run": "When the dashboard last ran successfully.",
+ "query_count": "How many queries the dashboard has issued.",
+ "view_count": "How many times the dashboard has been viewed.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/select_star.py b/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/select_star.py
new file mode 100644
index 000000000000..463c9e604682
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/select_star.py
@@ -0,0 +1,142 @@
+from typing import Any, Optional
+
+from posthog.dataclasses import frozen
+
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponsePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.select_star.settings import (
+ PAGE_SIZE,
+ SELECTSTAR_BASE_URL,
+ SELECTSTAR_ENDPOINTS,
+)
+
+
+@frozen
+class SelectStarResumeConfig:
+ next_url: str
+
+
+def _auth_header_value(api_token: str) -> str:
+ # Select Star requires the "Token" scheme, not "Bearer".
+ return f"Token {api_token}"
+
+
+def _incremental_param(field: str) -> dict[str, Any]:
+ return {"type": "incremental", "cursor_path": field, "initial_value": None}
+
+
+def select_star_source(
+ api_token: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[SelectStarResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
+) -> SourceResponse:
+ config = SELECTSTAR_ENDPOINTS[endpoint]
+
+ # inputs.incremental_field is the user's chosen cursor (menu = config.incremental_fields);
+ # fall back to the first advertised option so a schema saved before the user picks stays usable.
+ filter_field = incremental_field or (config.incremental_fields[0]["field"] if config.incremental_fields else None)
+ use_incremental = should_use_incremental_field and filter_field is not None
+
+ params: dict[str, Any] = {"page_size": PAGE_SIZE}
+ if filter_field:
+ params[f"{filter_field}__gte"] = _incremental_param(filter_field) if use_incremental else None
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": SELECTSTAR_BASE_URL,
+ "auth": {
+ "type": "api_key",
+ "api_key": _auth_header_value(api_token),
+ "name": "Authorization",
+ "location": "header",
+ },
+ "paginator": JSONResponsePaginator(next_url_path="next"),
+ # Pagination follows the absolute `next` URL straight out of the response body, and
+ # the API token is replayed on every request via the Authorization header, so pin
+ # follow-up requests to the API host and refuse redirects: a tampered `next` link must
+ # not be able to retarget the token off-host (SSRF).
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ },
+ "resource_defaults": {
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_incremental else "replace",
+ },
+ "resources": [
+ {
+ "name": endpoint,
+ "endpoint": {
+ "path": config.path,
+ "params": params,
+ "data_selector": "results",
+ },
+ "table_format": "delta",
+ }
+ ],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None:
+ initial_paginator_state = {"next_url": resume.next_url}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only while a next page remains; save AFTER a page is yielded so a crash
+ # re-fetches the last in-flight page (merge dedupes on the primary key) rather than
+ # skipping it.
+ if state and state.get("next_url"):
+ resumable_source_manager.save_state(SelectStarResumeConfig(next_url=str(state["next_url"])))
+
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value if use_incremental else None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=resource.name,
+ items=lambda: resource,
+ primary_keys=config.primary_keys,
+ sort_mode="asc",
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ column_hints=resource.column_hints,
+ )
+
+
+def validate_credentials(api_token: str) -> tuple[bool, Optional[str]]:
+ """Cheap probe against the tables list endpoint to confirm the token is genuine."""
+ ok, status = validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_token,)),
+ f"{SELECTSTAR_BASE_URL}/v1/tables/?page_size=1",
+ headers={"Authorization": _auth_header_value(api_token)},
+ )
+ if ok:
+ return True, None
+ if status == 401:
+ return False, "Select Star rejected the API token. Generate a new token in Account Settings and reconnect."
+ if status == 403:
+ return (
+ False,
+ "This Select Star token doesn't have permission to read the catalog. Check the user's "
+ "role in Account Settings and reconnect.",
+ )
+ return False, "Could not verify the Select Star API token. Check your network and try again."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/settings.py
new file mode 100644
index 000000000000..2d9c75a780c2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/settings.py
@@ -0,0 +1,80 @@
+from dataclasses import field
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+SELECTSTAR_BASE_URL = "https://api.production.selectstar.com"
+
+# Select Star's DRF-style list endpoints default to 100 rows per page; this is well within
+# their documented burst limit (1000 requests/60s) for organizations with large catalogs.
+PAGE_SIZE = 100
+
+
+@frozen
+class SelectStarEndpointConfig:
+ path: str
+ primary_keys: list[str]
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable "created" field to partition by. None when the response carries no field that
+ # never changes after creation (never partition on a field that can be edited later).
+ partition_key: str | None = None
+
+
+def _datetime_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+SELECTSTAR_ENDPOINTS: dict[str, SelectStarEndpointConfig] = {
+ "Tables": SelectStarEndpointConfig(
+ path="/v1/tables/",
+ primary_keys=["guid"],
+ # Both filters are server-side (`<field>__gte`); the row also carries the field back,
+ # so either can drive the watermark. updated_on tracks metadata edits, last_queried_on
+ # tracks query activity — the user picks which recency matters to them.
+ incremental_fields=[_datetime_field("updated_on"), _datetime_field("last_queried_on")],
+ partition_key="db_created_on",
+ ),
+ "Columns": SelectStarEndpointConfig(
+ path="/v1/columns/",
+ primary_keys=["guid"],
+ # The endpoint accepts an `updated_on__gte` filter, but the Column object itself never
+ # returns an `updated_on` (or any other timestamp) field, so there is nothing to read
+ # back as a watermark. Full refresh only.
+ incremental_fields=[],
+ ),
+ "Databases": SelectStarEndpointConfig(
+ path="/v1/databases/",
+ primary_keys=["guid"],
+ # Same gap as Columns: `updated_on__gte` filters, but no timestamp comes back on the row.
+ incremental_fields=[],
+ ),
+ "Schemas": SelectStarEndpointConfig(
+ path="/v1/schemas/",
+ primary_keys=["guid"],
+ incremental_fields=[],
+ ),
+ "Tags": SelectStarEndpointConfig(
+ path="/v1/tags/",
+ primary_keys=["guid"],
+ incremental_fields=[_datetime_field("updated_on")],
+ ),
+ "Dashboards": SelectStarEndpointConfig(
+ path="/v1/bi/dashboards/",
+ primary_keys=["guid"],
+ # No `updated_on`-style filter param on this endpoint, so full refresh only.
+ incremental_fields=[],
+ partition_key="dashboard_created_at",
+ ),
+}
+
+ENDPOINTS = tuple(SELECTSTAR_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in SELECTSTAR_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/source.py
index 0f97354d8ed8..2f79edfab03f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/source.py
@@ -1,32 +1,132 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+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.selectstar import (
SelectStarSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.select_star.select_star import (
+ SelectStarResumeConfig,
+ select_star_source,
+ validate_credentials as validate_selectstar_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.select_star.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SelectStarSource(SimpleSource[SelectStarSourceConfig]):
+class SelectStarSource(ResumableSource[SelectStarSourceConfig, SelectStarResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://docs.selectstar.com/select-star-api/overview"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SELECTSTAR
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized": "Select Star rejected the API token. Generate a new token in "
+ "Account Settings and reconnect.",
+ "403 Client Error: Forbidden": "This Select Star token doesn't have permission to read the catalog. "
+ "Check the user's role in Account Settings and reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.select_star.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: SelectStarSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: SelectStarSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_selectstar_credentials(config.api_token)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SelectStarResumeConfig]:
+ return ResumableSourceManager[SelectStarResumeConfig](inputs, SelectStarResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SelectStarSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SelectStarResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return select_star_source(
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.SELECT_STAR,
category=DataWarehouseSourceCategory.ANALYTICS,
label="Select Star",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption=(
+ "Enter your Select Star API token to pull your data catalog into the PostHog Data warehouse.\n\n"
+ "Create a token in Select Star under **Account Settings > Client API Token > Manage API Tokens "
+ "> Create**. The token never expires and inherits the creating user's role. **Viewer** access "
+ "is enough to read tables, columns, databases, schemas, tags, and BI dashboards."
+ ),
+ docsUrl="https://posthog.com/docs/cdp/sources/select-star",
iconPath="/static/services/select_star.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/tests/test_select_star.py b/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/tests/test_select_star.py
new file mode 100644
index 000000000000..43b518a183b3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/tests/test_select_star.py
@@ -0,0 +1,277 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, datetime
+from typing import Any, Optional, cast
+
+from unittest import mock
+
+from parameterized import parameterized
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.select_star.select_star import (
+ SelectStarResumeConfig,
+ select_star_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.select_star.settings import (
+ ENDPOINTS,
+ SELECTSTAR_BASE_URL,
+ SELECTSTAR_ENDPOINTS,
+)
+
+# RESTClient builds its session via make_tracked_session in the rest_client module.
+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+# validate_credentials builds its own tracked session in the select_star module.
+SELECT_STAR_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.select_star.select_star.make_tracked_session"
+)
+
+TABLES_URL = f"{SELECTSTAR_BASE_URL}/v1/tables/"
+TAGS_URL = f"{SELECTSTAR_BASE_URL}/v1/tags/"
+
+
+def _json_response(body: Any, status: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
+def _page(results: list[dict[str, Any]], *, next_url: Optional[str] = None) -> Response:
+ return _json_response({"count": len(results), "next": next_url, "previous": None, "results": results})
+
+
+def _make_manager(resume_state: SelectStarResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+ """Wire a mock session and capture each request's (url, params, auth) at send time."""
+ session.headers = {}
+ snapshots: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> Any:
+ snapshots.append({"url": request.url, "params": request.params, "auth": request.auth})
+ # Return the request itself rather than a bare MagicMock: RESTClient now checks
+ # `prepared.url` against the allowed-hosts pin before sending (see select_star.py's
+ # `allowed_hosts`), and `urlsplit()` on an unconfigured MagicMock attribute raises
+ # TypeError. A real `Request` carries a real `.url` string, matching the pattern used
+ # by ably/conekta's tests for the same allowed-hosts-pinned client.
+ return request
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return snapshots
+
+
+def _rows(source_response: Any) -> list[dict[str, Any]]:
+ return [row for page in cast("Iterable[Any]", source_response.items()) for row in page]
+
+
+class TestPagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_single_page_yields_and_stops(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_page([{"guid": "ta_1"}, {"guid": "ta_2"}])])
+
+ manager = _make_manager()
+ rows = _rows(select_star_source("tok", "Tables", team_id=1, job_id="j", resumable_source_manager=manager))
+
+ assert rows == [{"guid": "ta_1"}, {"guid": "ta_2"}]
+ assert session.send.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_follows_next_url_until_null(self, MockSession) -> None:
+ session = MockSession.return_value
+ second = f"{TABLES_URL}?page=2"
+ snapshots = _wire(session, [_page([{"guid": "a"}], next_url=second), _page([{"guid": "b"}])])
+
+ manager = _make_manager()
+ rows = _rows(select_star_source("tok", "Tables", team_id=1, job_id="j", resumable_source_manager=manager))
+
+ assert rows == [{"guid": "a"}, {"guid": "b"}]
+ assert snapshots[0]["url"] == TABLES_URL
+ assert snapshots[1]["url"] == second
+ manager.save_state.assert_called_once_with(SelectStarResumeConfig(next_url=second))
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_from_saved_cursor(self, MockSession) -> None:
+ session = MockSession.return_value
+ second = f"{TABLES_URL}?page=2"
+ snapshots = _wire(session, [_page([{"guid": "b"}])])
+
+ manager = _make_manager(SelectStarResumeConfig(next_url=second))
+ rows = _rows(select_star_source("tok", "Tables", team_id=1, job_id="j", resumable_source_manager=manager))
+
+ assert rows == [{"guid": "b"}]
+ assert session.send.call_count == 1
+ assert snapshots[0]["url"] == second
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_empty_first_page_yields_nothing(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_page([])])
+
+ manager = _make_manager()
+ rows = _rows(select_star_source("tok", "Tables", team_id=1, job_id="j", resumable_source_manager=manager))
+
+ assert rows == []
+ manager.save_state.assert_not_called()
+
+
+class TestAuth:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_uses_token_scheme_not_bearer(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_page([])])
+
+ _rows(select_star_source("tok-123", "Tables", team_id=1, job_id="j", resumable_source_manager=_make_manager()))
+
+ # Auth is applied by `requests` when the session actually prepares the request; assert on
+ # the auth callable's effect directly rather than depending on that internal prepare step.
+ prepared = mock.MagicMock()
+ prepared.headers = {}
+ snapshots[0]["auth"](prepared)
+ assert prepared.headers["Authorization"] == "Token tok-123"
+
+
+class TestIncrementalFilter:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_no_filter_when_not_incremental(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_page([])])
+
+ _rows(select_star_source("tok", "Tables", team_id=1, job_id="j", resumable_source_manager=_make_manager()))
+
+ assert "updated_on__gte" not in snapshots[0]["params"]
+ assert "last_queried_on__gte" not in snapshots[0]["params"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_default_incremental_field_used_when_none_selected(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_page([])])
+
+ _rows(
+ select_star_source(
+ "tok",
+ "Tables",
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=_make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+ )
+
+ assert snapshots[0]["params"]["updated_on__gte"] == datetime(2026, 1, 1, tzinfo=UTC)
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_honors_user_selected_incremental_field(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_page([])])
+
+ _rows(
+ select_star_source(
+ "tok",
+ "Tables",
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=_make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ incremental_field="last_queried_on",
+ )
+ )
+
+ assert "updated_on__gte" not in snapshots[0]["params"]
+ assert snapshots[0]["params"]["last_queried_on__gte"] == datetime(2026, 1, 1, tzinfo=UTC)
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_no_filter_param_for_endpoint_without_incremental_fields(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_page([])])
+
+ _rows(
+ select_star_source(
+ "tok",
+ "Columns",
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=_make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+ )
+
+ assert not any(key.endswith("__gte") for key in snapshots[0]["params"])
+
+
+class TestValidateCredentials:
+ @mock.patch(SELECT_STAR_SESSION_PATCH)
+ def test_ok(self, mock_session) -> None:
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
+ assert validate_credentials("tok") == (True, None)
+
+ @parameterized.expand(
+ [
+ ("unauthorized", 401),
+ ("forbidden", 403),
+ ("server_error", 500),
+ ]
+ )
+ @mock.patch(SELECT_STAR_SESSION_PATCH)
+ def test_status_mapping_is_a_failure(self, _name: str, status: int, mock_session) -> None:
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status)
+ ok, message = validate_credentials("tok")
+ assert ok is False
+ assert message
+
+ def test_401_and_403_messages_differ(self) -> None:
+ with mock.patch(SELECT_STAR_SESSION_PATCH) as mock_session:
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=401)
+ _, unauthorized_message = validate_credentials("tok")
+ with mock.patch(SELECT_STAR_SESSION_PATCH) as mock_session:
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=403)
+ _, forbidden_message = validate_credentials("tok")
+ assert unauthorized_message != forbidden_message
+
+ @mock.patch(SELECT_STAR_SESSION_PATCH)
+ def test_connection_error_maps_to_generic_message(self, mock_session) -> None:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ ok, message = validate_credentials("tok")
+ assert ok is False
+ assert message
+
+
+class TestSelectStarSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ # Construction does no I/O (items is a lazy generator), so no session patch is needed.
+ response = select_star_source("tok", endpoint, team_id=1, job_id="j", resumable_source_manager=mock.MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == ["guid"]
+ assert response.sort_mode == "asc"
+
+ def test_tables_and_dashboards_are_partitioned(self) -> None:
+ for endpoint in ("Tables", "Dashboards"):
+ response = select_star_source(
+ "tok", endpoint, team_id=1, job_id="j", resumable_source_manager=mock.MagicMock()
+ )
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [SELECTSTAR_ENDPOINTS[endpoint].partition_key]
+
+ def test_endpoints_without_a_stable_created_field_are_not_partitioned(self) -> None:
+ for endpoint in ("Columns", "Databases", "Schemas", "Tags"):
+ response = select_star_source(
+ "tok", endpoint, team_id=1, job_id="j", resumable_source_manager=mock.MagicMock()
+ )
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ def test_every_endpoint_uses_guid_primary_key(self) -> None:
+ assert all(config.primary_keys == ["guid"] for config in SELECTSTAR_ENDPOINTS.values())
+ assert set(SELECTSTAR_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/tests/test_select_star_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/tests/test_select_star_source.py
new file mode 100644
index 000000000000..cd521e6a796a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/select_star/tests/test_select_star_source.py
@@ -0,0 +1,141 @@
+from unittest import mock
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.selectstar import (
+ SelectStarSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.select_star.select_star import (
+ SelectStarResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.select_star.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.select_star.source import SelectStarSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestSelectStarSource:
+ def setup_method(self):
+ self.source = SelectStarSource()
+ self.team_id = 42
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.SELECTSTAR
+
+ def test_source_is_released(self):
+ # A finished source must be visible: no unreleasedSource flag, soft ALPHA label.
+ config = self.source.get_source_config
+ assert getattr(config, "unreleasedSource", None) in (None, False)
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ def test_source_config_basics(self):
+ config = self.source.get_source_config
+ assert config.label == "Select Star"
+ assert config.category == DataWarehouseSourceCategory.ANALYTICS
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/select-star"
+ assert config.iconPath == "/static/services/select_star.png"
+
+ def test_source_config_fields(self):
+ fields = {f.name: f for f in self.source.get_source_config.fields}
+ assert set(fields) == {"api_token"}
+
+ token = fields["api_token"]
+ assert isinstance(token, SourceFieldInputConfig)
+ assert token.type == SourceFieldInputConfigType.PASSWORD
+ assert token.required is True
+ assert token.secret is True
+
+ def test_lists_tables_without_credentials(self):
+ # get_schemas is a static catalog with no I/O, so public docs may render the table list.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_returns_all_endpoints(self):
+ schemas = self.source.get_schemas(mock.MagicMock(), self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_only_tables_and_tags_are_incremental(self):
+ schemas = {s.name: s for s in self.source.get_schemas(mock.MagicMock(), self.team_id)}
+ assert schemas["Tables"].supports_incremental is True
+ assert [f["field"] for f in schemas["Tables"].incremental_fields] == ["updated_on", "last_queried_on"]
+ assert schemas["Tags"].supports_incremental is True
+ assert [f["field"] for f in schemas["Tags"].incremental_fields] == ["updated_on"]
+ for name in ("Columns", "Databases", "Schemas", "Dashboards"):
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].incremental_fields == []
+
+ def test_get_schemas_filters_by_name(self):
+ schemas = self.source.get_schemas(mock.MagicMock(), self.team_id, names=["Tables"])
+ assert [s.name for s in schemas] == ["Tables"]
+
+ def test_validate_credentials_delegates(self):
+ config = SelectStarSourceConfig(api_token="tok")
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.select_star.source.validate_selectstar_credentials",
+ return_value=(True, None),
+ ) as mock_validate:
+ assert self.source.validate_credentials(config, self.team_id) == (True, None)
+ mock_validate.assert_called_once_with("tok")
+
+ def test_non_retryable_errors_cover_auth(self):
+ errors = self.source.get_non_retryable_errors()
+ assert "401 Client Error: Unauthorized" in errors
+ assert "403 Client Error: Forbidden" in errors
+
+ def test_canonical_descriptions_present(self):
+ canonical = self.source.get_canonical_descriptions()
+ assert set(ENDPOINTS).issubset(set(canonical))
+ assert "guid" in canonical["Tables"]["columns"]
+
+ def test_resumable_manager_bound_to_data_class(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is SelectStarResumeConfig
+
+ def test_source_for_pipeline_plumbs_config(self):
+ config = SelectStarSourceConfig(api_token="tok")
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Tables"
+ inputs.team_id = 7
+ inputs.job_id = "job-1"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ inputs.incremental_field = "updated_on"
+ manager = mock.MagicMock()
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.select_star.source.select_star_source"
+ ) as mock_select_star_source:
+ self.source.source_for_pipeline(config, manager, inputs)
+
+ mock_select_star_source.assert_called_once_with(
+ api_token="tok",
+ endpoint="Tables",
+ team_id=7,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ incremental_field="updated_on",
+ )
+
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self):
+ config = SelectStarSourceConfig(api_token="tok")
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Columns"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "should-be-ignored"
+ inputs.incremental_field = None
+ manager = mock.MagicMock()
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.select_star.source.select_star_source"
+ ) as mock_select_star_source:
+ self.source.source_for_pipeline(config, manager, inputs)
+
+ assert mock_select_star_source.call_args.kwargs["db_incremental_field_last_value"] is None