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): implement airtable import source (#62931)

Tom Owers1c649aa027eb
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 68ad8b217b3a..c71de80eb8b7 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -45,6 +45,7 @@ the row lists both.
| Source | Comm method | Primary library | Tracked transport |
| ---------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- |
| aircall | HTTP | requests | ✅ |
+| airtable | HTTP | requests | ✅ |
| amplitude | HTTP | requests | ✅ |
| asana | HTTP | requests | ✅ |
| ashby | HTTP | requests | ✅ |
@@ -204,7 +205,6 @@ doesn't conflict with concurrent PRs.
- adp_workforce_now
- adroll
- adyen
-- airtable
- amazon_ads
- amazon_s3
- amazon_selling_partner
diff --git a/posthog/temporal/data_imports/sources/airtable/airtable.py b/posthog/temporal/data_imports/sources/airtable/airtable.py
new file mode 100644
index 000000000000..12e9ab330cf1
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/airtable/airtable.py
@@ -0,0 +1,171 @@
+import time
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import quote, urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.airtable.settings import AIRTABLE_ENDPOINTS
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+
+AIRTABLE_BASE_URL = "https://api.airtable.com/v0"
+# Record list pages cap at 100.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+# Airtable allows 5 req/s per base and imposes a 30s cooldown after a 429, so
+# requests are proactively spaced and backoff starts above the cooldown.
+REQUEST_INTERVAL_SECONDS = 0.21
+MAX_RETRY_ATTEMPTS = 5
+
+
+class AirtableRetryableError(Exception):
+ pass
+
+
+def _get_session(personal_access_token: str) -> requests.Session:
+ return make_tracked_session(
+ headers={"Authorization": f"Bearer {personal_access_token}"}, redact_values=(personal_access_token,)
+ )
+
+
+def _format_created_time(value: Any) -> str:
+ """Format an incremental cursor for an IS_AFTER(CREATED_TIME(), ...) formula (ISO 8601 UTC)."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.000Z")
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%dT00:00:00.000Z")
+ return str(value)
+
+
+def validate_credentials(personal_access_token: str) -> bool:
+ """Confirm the PAT is valid with a cheap one-base meta probe."""
+ try:
+ response = _get_session(personal_access_token).get(
+ f"{AIRTABLE_BASE_URL}/meta/bases",
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def get_rows(
+ personal_access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ session = _get_session(personal_access_token)
+
+ @retry(
+ retry=retry_if_exception_type((AirtableRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ # First retry waits out Airtable's 30s post-429 cooldown.
+ wait=wait_exponential_jitter(initial=31, max=120),
+ reraise=True,
+ )
+ def fetch(path: str, params: dict[str, Any]) -> dict[str, Any]:
+ # Stay under the 5 req/s per-base budget.
+ time.sleep(REQUEST_INTERVAL_SECONDS)
+ url = f"{AIRTABLE_BASE_URL}{path}"
+ if params:
+ url = f"{url}?{urlencode(params)}"
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise AirtableRetryableError(f"Airtable API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Airtable API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ def iterate_bases() -> Iterator[list[dict[str, Any]]]:
+ # List-page offsets expire after a few minutes of inactivity, so page
+ # chains are never persisted — a retried sync restarts the chain.
+ offset: Optional[str] = None
+ while True:
+ params: dict[str, Any] = {"offset": offset} if offset else {}
+ data = fetch("/meta/bases", params)
+ items = data.get("bases", []) or []
+ if items:
+ yield items
+ offset = data.get("offset")
+ if not offset or not items:
+ return
+
+ def tables_for_base(base_id: str) -> list[dict[str, Any]]:
+ data = fetch(f"/meta/bases/{quote(base_id)}/tables", {})
+ return data.get("tables", []) or []
+
+ if endpoint == "bases":
+ yield from iterate_bases()
+ return
+
+ base_ids = [base["id"] for page in iterate_bases() for base in page]
+
+ if endpoint == "tables":
+ for base_id in base_ids:
+ tables = [{**table, "_base_id": base_id} for table in tables_for_base(base_id)]
+ if tables:
+ yield tables
+ return
+
+ # records: fan out over every table of every base.
+ created_after = (
+ _format_created_time(db_incremental_field_last_value)
+ if should_use_incremental_field and db_incremental_field_last_value is not None
+ else None
+ )
+
+ for base_id in base_ids:
+ for table in tables_for_base(base_id):
+ table_id = table["id"]
+ offset = None
+ while True:
+ params: dict[str, Any] = {"pageSize": PAGE_SIZE}
+ if created_after is not None:
+ params["filterByFormula"] = f'IS_AFTER(CREATED_TIME(), "{created_after}")'
+ if offset:
+ params["offset"] = offset
+ data = fetch(f"/{quote(base_id)}/{quote(table_id)}", params)
+ items = [
+ {**record, "_base_id": base_id, "_table_id": table_id} for record in (data.get("records", []) or [])
+ ]
+ if items:
+ yield items
+ offset = data.get("offset")
+ if not offset or not items:
+ break
+
+
+def airtable_source(
+ personal_access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = AIRTABLE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ personal_access_token=personal_access_token,
+ endpoint=endpoint,
+ logger=logger,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ sort_mode="asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/airtable/settings.py b/posthog/temporal/data_imports/sources/airtable/settings.py
new file mode 100644
index 000000000000..b2763017e33d
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/airtable/settings.py
@@ -0,0 +1,46 @@
+from dataclasses import dataclass, field
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class AirtableEndpointConfig:
+ name: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+
+
+# Records can be filtered server-side with filterByFormula on CREATED_TIME(),
+# giving an honest append-only incremental on createdTime (the only timestamp
+# present on record payloads — updates to existing records need a full
+# refresh). Bases and tables are tiny metadata listings.
+AIRTABLE_ENDPOINTS: dict[str, AirtableEndpointConfig] = {
+ "bases": AirtableEndpointConfig(
+ name="bases",
+ ),
+ "tables": AirtableEndpointConfig(
+ name="tables",
+ # Table ids are globally unique, but keep the base linkage in the key
+ # so re-parented metadata can't collide.
+ primary_keys=["_base_id", "id"],
+ ),
+ "records": AirtableEndpointConfig(
+ name="records",
+ # Record ids are only unique within a table.
+ primary_keys=["_base_id", "_table_id", "id"],
+ incremental_fields=[
+ {
+ "label": "createdTime",
+ "type": IncrementalFieldType.DateTime,
+ "field": "createdTime",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+}
+
+ENDPOINTS = tuple(AIRTABLE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in AIRTABLE_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/posthog/temporal/data_imports/sources/airtable/source.py b/posthog/temporal/data_imports/sources/airtable/source.py
index ea5328e8778d..f88b8e86b0c8 100644
--- a/posthog/temporal/data_imports/sources/airtable/source.py
+++ b/posthog/temporal/data_imports/sources/airtable/source.py
@@ -1,12 +1,22 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.airtable.airtable import (
+ airtable_source,
+ validate_credentials as validate_airtable_credentials,
+)
+from posthog.temporal.data_imports.sources.airtable.settings import ENDPOINTS, INCREMENTAL_FIELDS
from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import AirtableSourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@@ -18,12 +28,77 @@ class AirtableSource(SimpleSource[AirtableSourceConfig]):
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AIRTABLE
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.airtable.com": "Airtable authentication failed. Please check your personal access token.",
+ "403 Client Error: Forbidden for url: https://api.airtable.com": "Airtable denied access. Please check that your personal access token has the required scopes and base access.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.AIRTABLE,
label="Airtable",
+ caption="""Enter your Airtable personal access token to pull your Airtable bases into the PostHog Data warehouse.
+
+Create a personal access token at [airtable.com/create/tokens](https://airtable.com/create/tokens) with the `data.records:read` and `schema.bases:read` scopes, and grant it access to the bases you want to sync. Records are synced from every table of every base the token can access.""",
iconPath="/static/services/airtable.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/airtable",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="personal_access_token",
+ label="Personal access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="pat...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: AirtableSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in ENDPOINTS
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self, config: AirtableSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_airtable_credentials(config.personal_access_token):
+ return True, None
+
+ return False, "Invalid Airtable personal access token"
+
+ def source_for_pipeline(self, config: AirtableSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return airtable_source(
+ personal_access_token=config.personal_access_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ 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,
)
diff --git a/posthog/temporal/data_imports/sources/airtable/tests/test_airtable.py b/posthog/temporal/data_imports/sources/airtable/tests/test_airtable.py
new file mode 100644
index 000000000000..ae7723be1054
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/airtable/tests/test_airtable.py
@@ -0,0 +1,176 @@
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.airtable.airtable import (
+ _format_created_time,
+ airtable_source,
+ get_rows,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.airtable.settings import AIRTABLE_ENDPOINTS, ENDPOINTS
+
+
+def _response(body: dict[str, Any]) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = body
+ resp.status_code = 200
+ resp.ok = True
+ return resp
+
+
[email protected](autouse=True)
+def _no_sleep():
+ with mock.patch("posthog.temporal.data_imports.sources.airtable.airtable.time.sleep"):
+ yield
+
+
+class TestFormatCreatedTime:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02T03:04:05.000Z"),
+ (datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05.000Z"),
+ (date(2024, 1, 2), "2024-01-02T00:00:00.000Z"),
+ ("2024-01-02T03:04:05.000Z", "2024-01-02T03:04:05.000Z"),
+ ],
+ )
+ def test_format_values(self, value, expected):
+ assert _format_created_time(value) == expected
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.airtable.airtable.make_tracked_session")
+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ assert validate_credentials("pat") is expected
+
+ @mock.patch("posthog.temporal.data_imports.sources.airtable.airtable.make_tracked_session")
+ def test_validate_credentials_swallows_exceptions(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("pat") is False
+
+
+class TestGetRowsBases:
+ @mock.patch("posthog.temporal.data_imports.sources.airtable.airtable.make_tracked_session")
+ def test_paginates_via_offset_token(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"bases": [{"id": "app1"}], "offset": "off1"}),
+ _response({"bases": [{"id": "app2"}]}),
+ ]
+
+ batches = list(get_rows("pat", "bases", mock.MagicMock()))
+
+ assert [item["id"] for batch in batches for item in batch] == ["app1", "app2"]
+ second_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert parse_qs(urlparse(second_url).query)["offset"] == ["off1"]
+
+
+class TestGetRowsTables:
+ @mock.patch("posthog.temporal.data_imports.sources.airtable.airtable.make_tracked_session")
+ def test_fans_out_over_bases_and_injects_base_id(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"bases": [{"id": "app1"}, {"id": "app2"}]}),
+ _response({"tables": [{"id": "tbl1", "name": "Tasks"}]}),
+ _response({"tables": [{"id": "tbl2", "name": "Leads"}]}),
+ ]
+
+ batches = list(get_rows("pat", "tables", mock.MagicMock()))
+
+ flat = [item for batch in batches for item in batch]
+ assert [(t["id"], t["_base_id"]) for t in flat] == [("tbl1", "app1"), ("tbl2", "app2")]
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert urlparse(urls[1]).path == "/v0/meta/bases/app1/tables"
+ assert urlparse(urls[2]).path == "/v0/meta/bases/app2/tables"
+
+
+class TestGetRowsRecords:
+ @mock.patch("posthog.temporal.data_imports.sources.airtable.airtable.make_tracked_session")
+ def test_fans_out_over_tables_and_paginates_records(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"bases": [{"id": "app1"}]}),
+ _response({"tables": [{"id": "tbl1"}]}),
+ _response({"records": [{"id": "rec1", "createdTime": "2024-01-01T00:00:00.000Z"}], "offset": "off1"}),
+ _response({"records": [{"id": "rec2", "createdTime": "2024-01-02T00:00:00.000Z"}]}),
+ ]
+
+ batches = list(get_rows("pat", "records", mock.MagicMock()))
+
+ flat = [item for batch in batches for item in batch]
+ assert [(r["id"], r["_base_id"], r["_table_id"]) for r in flat] == [
+ ("rec1", "app1", "tbl1"),
+ ("rec2", "app1", "tbl1"),
+ ]
+ record_urls = [call.args[0] for call in mock_session.return_value.get.call_args_list[2:]]
+ assert urlparse(record_urls[0]).path == "/v0/app1/tbl1"
+ assert parse_qs(urlparse(record_urls[1]).query)["offset"] == ["off1"]
+
+ @mock.patch("posthog.temporal.data_imports.sources.airtable.airtable.make_tracked_session")
+ def test_incremental_records_filter_on_created_time(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"bases": [{"id": "app1"}]}),
+ _response({"tables": [{"id": "tbl1"}]}),
+ _response({"records": []}),
+ ]
+
+ list(
+ get_rows(
+ "pat",
+ "records",
+ mock.MagicMock(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),
+ )
+ )
+
+ record_url = mock_session.return_value.get.call_args_list[2].args[0]
+ formula = parse_qs(urlparse(record_url).query)["filterByFormula"][0]
+ assert formula == 'IS_AFTER(CREATED_TIME(), "2024-01-02T00:00:00.000Z")'
+
+ @mock.patch("posthog.temporal.data_imports.sources.airtable.airtable.make_tracked_session")
+ def test_table_without_id_fails_loudly(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"bases": [{"id": "app1"}]}),
+ _response({"tables": [{"name": "broken"}]}),
+ ]
+
+ with pytest.raises(KeyError):
+ list(get_rows("pat", "records", mock.MagicMock()))
+
+ @mock.patch("posthog.temporal.data_imports.sources.airtable.airtable.make_tracked_session")
+ def test_empty_everything_yields_nothing(self, mock_session):
+ mock_session.return_value.get.return_value = _response({"bases": []})
+
+ assert list(get_rows("pat", "records", mock.MagicMock())) == []
+
+
+class TestAirtableSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = AIRTABLE_ENDPOINTS[endpoint]
+ response = airtable_source("pat", endpoint, mock.MagicMock())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == "asc"
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ def test_records_have_composite_primary_key(self):
+ response = airtable_source("pat", "records", mock.MagicMock())
+ assert response.primary_keys == ["_base_id", "_table_id", "id"]
diff --git a/posthog/temporal/data_imports/sources/airtable/tests/test_airtable_source.py b/posthog/temporal/data_imports/sources/airtable/tests/test_airtable_source.py
new file mode 100644
index 000000000000..a089205efcc4
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/airtable/tests/test_airtable_source.py
@@ -0,0 +1,131 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.airtable.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.airtable.source import AirtableSource
+from posthog.temporal.data_imports.sources.generated_configs import AirtableSourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestAirtableSource:
+ def setup_method(self):
+ self.source = AirtableSource()
+ self.team_id = 123
+ self.config = AirtableSourceConfig(personal_access_token="pat-token")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.AIRTABLE
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Airtable"
+ assert config.label == "Airtable"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/airtable.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["personal_access_token"]
+
+ def test_pat_field_is_secret_password(self):
+ config = self.source.get_source_config
+ token_field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "personal_access_token"
+ )
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.secret is True
+ assert token_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.airtable.com/v0/meta/bases",
+ "403 Client Error: Forbidden for url: https://api.airtable.com/v0/app1/tbl1",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_vendor_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.airtable.com/v0/meta/bases",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_vendor_error for key in non_retryable_errors)
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ incremental = {schema.name for schema in schemas if schema.supports_incremental}
+ # Only records can be filtered server-side (CREATED_TIME() formula).
+ assert incremental == {"records"}
+
+ def test_incremental_schemas_advertise_their_fields(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["records"].incremental_fields == INCREMENTAL_FIELDS["records"]
+ assert [f["field"] for f in schemas["records"].incremental_fields] == ["createdTime"]
+ assert schemas["bases"].incremental_fields == []
+ assert schemas["bases"].supports_append is False
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["records"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "records"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid Airtable personal access token"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.airtable.source.validate_airtable_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.personal_access_token)
+
+ @mock.patch("posthog.temporal.data_imports.sources.airtable.source.airtable_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_airtable_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "records"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05.000Z"
+
+ self.source.source_for_pipeline(self.config, inputs)
+
+ mock_airtable_source.assert_called_once()
+ kwargs = mock_airtable_source.call_args.kwargs
+ assert kwargs["personal_access_token"] == "pat-token"
+ assert kwargs["endpoint"] == "records"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05.000Z"
+
+ @mock.patch("posthog.temporal.data_imports.sources.airtable.source.airtable_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_airtable_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "records"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05.000Z"
+
+ self.source.source_for_pipeline(self.config, inputs)
+
+ assert mock_airtable_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 6319e97b2c8e..dd12a3e5f237 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -143,7 +143,7 @@ class AircallSourceConfig(config.Config):
@config.config
class AirtableSourceConfig(config.Config):
- pass
+ personal_access_token: str
@config.config