: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add file upload as a self-managed table (#72282)
Tom Owers2bcdd814e475
diff --git a/frontend/public/services/file-upload.svg b/frontend/public/services/file-upload.svgnew file mode 100644index 000000000000..d29ec6eb3501--- /dev/null+++ b/frontend/public/services/file-upload.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" fill="none" viewBox="0 0 64 64"><rect width="64" height="64" rx="12" fill="#EEEFF2"/><path fill="#fff" stroke="#8F90A6" stroke-width="2.5" stroke-linejoin="round" d="M17.5 14.75A2.25 2.25 0 0 1 19.75 12.5h15.19a2.25 2.25 0 0 1 1.59.66l9.06 9.06c.42.42.66 1 .66 1.59v25.44a2.25 2.25 0 0 1-2.25 2.25h-24.5a2.25 2.25 0 0 1-2.25-2.25V14.75Z"/><path stroke="#8F90A6" stroke-width="2.5" stroke-linejoin="round" d="M35.5 13v9a2 2 0 0 0 2 2h9"/><circle cx="45" cy="45" r="11" fill="#1D4AFF"/><path stroke="#fff" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" d="M45 50.5v-11M40.5 44l4.5-4.5 4.5 4.5"/></svg>diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 9bdffeb5a0c8..e6960e93cedd 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -223,6 +223,7 @@ import {UserBasicType,UserInterviewType,UserType,+ WarehouseTableFileUpload,WebAnalyticsFilterPresetType,WebhookInfo,} from '~/types'@@ -5704,6 +5705,19 @@ const api = {async refreshSchema(tableId: DataWarehouseTable['id']): Promise<void> {await new ApiRequest().dataWarehouseTable(tableId).withAction('refresh_schema').create()},+ // FormData, not JSON — the browser sets the multipart boundary itself, so don't add a+ // Content-Type header here (`api.createResponse` already skips it for FormData bodies).+ async uploadFile(data: FormData): Promise<WarehouseTableFileUpload> {+ return await new ApiRequest().dataWarehouseTables().withAction('upload_file').create({ data })+ },+ async createFromUpload(data: {+ upload_id: string+ filename: string+ file_format: string+ table_name: string+ }): Promise<DataWarehouseTable> {+ return await new ApiRequest().dataWarehouseTables().withAction('create_from_upload').create({ data })+ },},dataWarehouseSavedQueries: {diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex a77464924e58..603801fc7fe0 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -6188,6 +6188,14 @@ export interface ExternalDataSourceCreatePayload {payload: Record<string, any>}+/** Response of `POST warehouse_tables/upload_file` — the stored file a self-managed table is built from. */+export interface WarehouseTableFileUpload {+ upload_id: string+ filename: string+ file_format: string+ size_bytes: number+}+export interface ExternalDataSourceConnectionMetadata {database?: string | nullversion?: string | nulldiff --git a/products/data_warehouse/backend/presentation/views/table.py b/products/data_warehouse/backend/presentation/views/table.pyindex 51c17f4d519c..68058d149015 100644--- a/products/data_warehouse/backend/presentation/views/table.py+++ b/products/data_warehouse/backend/presentation/views/table.py@@ -1,4 +1,5 @@import re+import uuidfrom typing import Any, castfrom django.conf import settings@@ -23,7 +24,15 @@ from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.rbac.user_access_control import UserAccessControlSerializerMixinfrom posthog.tasks.warehouse import validate_data_warehouse_table_columns+from products.data_warehouse.backend.facade.api import get_s3_clientfrom products.data_warehouse.backend.presentation.views.external_data_source import SimpleExternalDataSourceSerializers+from products.warehouse_sources.backend.facade.api import (+ FILE_FORMAT_TO_TABLE_FORMAT,+ MAX_FILE_UPLOAD_SIZE_BYTES,+ SUPPORTED_FILE_FORMATS,+ build_file_upload_s3_path,+ build_file_upload_url_pattern,+)from products.warehouse_sources.backend.facade.hogql import (CLICKHOUSE_HOGQL_MAPPING,SERIALIZED_FIELD_TO_CLICKHOUSE_MAPPING,@@ -36,6 +45,13 @@ from products.warehouse_sources.backend.facade.models import (validate_warehouse_table_url_pattern,)+# Whole-request-body ceiling for the upload endpoint, checked from Content-Length before the+# multipart parser spools anything to disk. The per-file check only sees request.FILES["file"], so+# without this an authenticated caller could push many large parts through the parser and fill temp+# storage far past the per-file cap. The margin over the file cap covers the multipart envelope and+# the small form fields sent alongside the file.+MAX_UPLOAD_REQUEST_BODY_BYTES = MAX_FILE_UPLOAD_SIZE_BYTES + 1024 * 1024+class CredentialSerializer(serializers.ModelSerializer):created_by = UserBasicSerializer(read_only=True)@@ -268,6 +284,31 @@ class SimpleTableSerializer(UserAccessControlSerializerMixin, serializers.ModelS]+class FileUploadResponseSerializer(serializers.Serializer):+ upload_id = serializers.UUIDField(+ help_text="Id of the stored upload. Pass it to create_from_upload to build the table."+ )+ filename = serializers.CharField(help_text="Sanitized name the file was stored under.")+ file_format = serializers.CharField(help_text="Format the file will be read as: 'csv', 'json', or 'parquet'.")+ size_bytes = serializers.IntegerField(help_text="Size of the stored file in bytes.")+++class CreateTableFromUploadSerializer(serializers.Serializer):+ upload_id = serializers.UUIDField(help_text="Id returned by upload_file for the stored file.")+ filename = serializers.CharField(help_text="Sanitized filename returned by upload_file.")+ file_format = serializers.ChoiceField(+ choices=SUPPORTED_FILE_FORMATS, help_text="How the uploaded file is read: 'csv', 'json', or 'parquet'."+ )+ table_name = serializers.CharField(help_text="Name the resulting table is queried by in HogQL.")++ def validate_table_name(self, table_name: str) -> str:+ if not re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*$", table_name):+ raise serializers.ValidationError(+ "Table names must start with a letter or underscore and contain only alphanumeric characters or underscores."+ )+ return table_name++class TableViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):"""Create, Read, Update and Delete Warehouse Tables.@@ -424,6 +465,194 @@ class TableViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mreturn response.Response(status=status.HTTP_200_OK)+ @extend_schema(+ request={+ "multipart/form-data": {+ "type": "object",+ "properties": {+ "file": {"type": "string", "format": "binary", "description": "The file to upload."},+ "file_format": {+ "type": "string",+ "enum": list(SUPPORTED_FILE_FORMATS),+ "description": "How the file will be read when the table is created.",+ },+ },+ "required": ["file", "file_format"],+ }+ },+ responses={201: FileUploadResponseSerializer},+ summary="Upload a file for a new self-managed warehouse table",+ )+ @action(+ methods=["POST"],+ detail=False,+ required_scopes=["warehouse_table:write"],+ parser_classes=[parsers.MultiPartParser, parsers.FormParser],+ )+ def upload_file(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:+ """Store an uploaded file in object storage so a self-managed table can be created from it.++ Uploading is a separate first step from `create_from_upload` so the create call stays JSON-only:+ this returns an `upload_id` the caller passes back to build the table. The file is written under+ a team-scoped prefix, so a table can only ever read back its own team's uploads.+ """+ if not settings.DATAWAREHOUSE_BUCKET:+ return response.Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Object storage must be available to upload files."},+ )++ # Reject an oversized body up front, before accessing request.FILES triggers multipart parsing+ # and spools every part to disk. Reading only Content-Length here keeps the guard cheap.+ content_length = request.META.get("CONTENT_LENGTH")+ try:+ declared_body_size = int(content_length) if content_length else 0+ except (TypeError, ValueError):+ declared_body_size = 0+ if declared_body_size > MAX_UPLOAD_REQUEST_BODY_BYTES:+ return response.Response(+ status=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,+ data={+ "message": f"Upload exceeds the maximum of {MAX_FILE_UPLOAD_SIZE_BYTES // (1024 * 1024)}MB. "+ "For larger files, connect the bucket they live in as a self-managed source instead."+ },+ )++ if "file" not in request.FILES:+ return response.Response(status=status.HTTP_400_BAD_REQUEST, data={"message": "No file provided"})++ # One upload per request: additional parts would already be spooled by the parser, but bounded+ # by the body cap above; rejecting keeps the endpoint's contract single-file and unambiguous.+ if len(request.FILES.getlist("file")) > 1 or len(request.FILES) > 1:+ return response.Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Upload one file per request."},+ )++ file = request.FILES["file"]++ file_format = request.data.get("file_format")+ if file_format not in SUPPORTED_FILE_FORMATS:+ return response.Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Invalid format. Must be one of: {', '.join(SUPPORTED_FILE_FORMATS)}"},+ )++ if file.size > MAX_FILE_UPLOAD_SIZE_BYTES:+ return response.Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": f"File size exceeds the maximum of {MAX_FILE_UPLOAD_SIZE_BYTES // (1024 * 1024)}MB. "+ "For larger files, connect the bucket they live in as a self-managed source instead."+ },+ )++ # Django strips path separators via os.path.basename in UploadedFile._set_name; restricting+ # further to safe characters is defense-in-depth for the S3 key.+ safe_filename = re.sub(r"[^a-zA-Z0-9._-]", "_", file.name or "")+ if not safe_filename or safe_filename.startswith("."):+ return response.Response(status=status.HTTP_400_BAD_REQUEST, data={"message": "Invalid filename"})++ upload_id = uuid.uuid4()+ path = build_file_upload_s3_path(self.team_id, str(upload_id), safe_filename)++ try:+ s3 = get_s3_client()+ with s3.open(path, "wb") as destination:+ for chunk in file.chunks():+ destination.write(chunk)+ except Exception as e:+ capture_exception(e)+ return response.Response(status=status.HTTP_400_BAD_REQUEST, data={"message": "Failed to upload file"})++ return response.Response(+ status=status.HTTP_201_CREATED,+ data=FileUploadResponseSerializer(+ {+ "upload_id": upload_id,+ "filename": safe_filename,+ "file_format": file_format,+ "size_bytes": file.size,+ }+ ).data,+ )++ @extend_schema(+ request=CreateTableFromUploadSerializer,+ responses={201: TableSerializer},+ summary="Create a self-managed warehouse table from an uploaded file",+ )+ @action(methods=["POST"], detail=False, required_scopes=["warehouse_table:write"])+ def create_from_upload(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:+ """Turn a previously uploaded file into a self-managed warehouse table.++ The file already sits in PostHog's own bucket (see `upload_file`), so the table points straight+ at it and is read in place — no import pipeline and no recurring sync, the same shape as a linked+ S3/GCS bucket. The read location is always derived from the caller's own team, so a client-supplied+ `upload_id` can only resolve inside that team's folder, and the table carries no credential (reads+ fall back to the node role, never a user-supplied key).+ """+ # Both settings back the table: the bucket resolves the S3 read path, the domain builds the+ # queryable url_pattern. Missing either would create a table whose every query fails.+ if not settings.DATAWAREHOUSE_BUCKET or not settings.DATAWAREHOUSE_BUCKET_DOMAIN:+ return response.Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Object storage must be available to create a table from a file."},+ )++ serializer = CreateTableFromUploadSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ upload_id = str(serializer.validated_data["upload_id"])+ filename = serializer.validated_data["filename"]+ file_format = serializer.validated_data["file_format"]+ table_name = serializer.validated_data["table_name"]++ # Reject duplicate names up front, the same way TableSerializer.validate_name does — has_table+ # is user-filtered, so also resolve team-wide to stop a denied table being shadowed by a new one.+ database = Database.create_for(team_id=self.team_id, user=cast(User, request.user))+ if database.has_table(table_name) or get_view_or_table_by_name(self.team_id, table_name):+ return response.Response(+ status=status.HTTP_400_BAD_REQUEST, data={"message": "A table with this name already exists."}+ )++ # Confirm the object is actually there before creating a table that would fail every query.+ upload_path = build_file_upload_s3_path(self.team_id, upload_id, filename)+ try:+ if not get_s3_client().exists(upload_path):+ return response.Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Uploaded file not found. Please upload the file again."},+ )+ except Exception as e:+ capture_exception(e)+ return response.Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Could not verify the uploaded file. Please try uploading it again."},+ )++ table = DataWarehouseTable(+ team_id=self.team_id,+ name=table_name,+ format=FILE_FORMAT_TO_TABLE_FORMAT[file_format],+ url_pattern=build_file_upload_url_pattern(self.team_id, upload_id, filename),+ created_by=request.user if isinstance(request.user, User) else None,+ )+ try:+ table.columns = table.get_columns()+ except Exception as err:+ return response.Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Could not read columns from the uploaded file: {err}"},+ )+ table.save()++ validate_data_warehouse_table_columns.delay(self.team_id, str(table.id))++ return response.Response(+ status=status.HTTP_201_CREATED,+ data=TableSerializer(table, context=self.get_serializer_context()).data,+ )+@action(methods=["POST"],detail=False,diff --git a/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.py b/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.pynew file mode 100644index 000000000000..920a970041ee--- /dev/null+++ b/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.py@@ -0,0 +1,281 @@+import io++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.core.files.uploadedfile import SimpleUploadedFile+from django.test import override_settings++from parameterized import parameterized+from rest_framework import status++from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.models.table import DataWarehouseTable++VIEW_MODULE = "products.data_warehouse.backend.presentation.views.table"+MODEL_MODULE = "products.warehouse_sources.backend.models.table"++# Stand-in for what `DataWarehouseTable.get_columns()` reads off the object in place — patched so the+# create tests never reach chdb/ClickHouse, which can't introspect a fake S3 object.+FAKE_COLUMNS = {+ "id": {"hogql": "IntegerDatabaseField", "clickhouse": "Nullable(Int64)"},+ "total": {"hogql": "IntegerDatabaseField", "clickhouse": "Nullable(Int64)"},+}+++class _CapturingBuffer(io.BytesIO):+ """A BytesIO that publishes its contents to a sink on close, so the endpoint's+ context-managed write is captured once the file handle is closed."""++ def __init__(self, sink: dict[str, bytes], path: str) -> None:+ super().__init__()+ self._sink = sink+ self._path = path++ def close(self) -> None:+ self._sink[self._path] = self.getvalue()+ super().close()+++class _FakeS3:+ """Captures what the endpoint writes, standing in for the object store boundary."""++ def __init__(self, *, exists_result: bool = True) -> None:+ self.written: dict[str, bytes] = {}+ self._exists_result = exists_result++ def open(self, path: str, mode: str) -> io.BytesIO:+ return _CapturingBuffer(self.written, path)++ def exists(self, path: str) -> bool:+ return self._exists_result+++@override_settings(DATAWAREHOUSE_BUCKET="test-bucket")+class TestWarehouseTableUploadFile(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.url = f"/api/environments/{self.team.pk}/warehouse_tables/upload_file/"+ self.s3 = _FakeS3()++ def _upload(self, **data):+ with patch(f"{VIEW_MODULE}.get_s3_client", return_value=self.s3):+ return self.client.post(self.url, data, format="multipart")++ def test_stores_file_under_a_team_scoped_key_and_returns_the_upload_id(self) -> None:+ response = self._upload(+ file=SimpleUploadedFile("data.csv", b"a,b\n1,2\n", content_type="text/csv"),+ file_format="csv",+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ body = response.json()+ assert body["filename"] == "data.csv"+ assert body["file_format"] == "csv"+ assert body["size_bytes"] == 8++ [written_path] = self.s3.written+ assert written_path == f"test-bucket/file_uploads/team_{self.team.pk}/{body['upload_id']}/data.csv"+ assert self.s3.written[written_path] == b"a,b\n1,2\n"++ def test_filename_cannot_escape_the_team_prefix(self) -> None:+ response = self._upload(+ file=SimpleUploadedFile("../../secrets.csv", b"a\n1\n", content_type="text/csv"),+ file_format="csv",+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ [written_path] = self.s3.written+ assert ".." not in written_path+ assert written_path.startswith(f"test-bucket/file_uploads/team_{self.team.pk}/")++ @parameterized.expand(+ [+ ("unsupported_format", "xlsx", "Invalid format"),+ ("empty_format", "", "Invalid format"),+ ]+ )+ def test_rejects_bad_format(self, _name: str, file_format: str, expected: str) -> None:+ response = self._upload(+ file=SimpleUploadedFile("data.csv", b"a\n1\n", content_type="text/csv"),+ file_format=file_format,+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert expected in response.json()["message"]++ def test_rejects_missing_file(self) -> None:+ response = self._upload(file_format="csv")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["message"] == "No file provided"++ def test_rejects_a_file_over_the_size_cap(self) -> None:+ with patch(f"{VIEW_MODULE}.MAX_FILE_UPLOAD_SIZE_BYTES", 4):+ response = self._upload(+ file=SimpleUploadedFile("data.csv", b"way too much data", content_type="text/csv"),+ file_format="csv",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "File size exceeds the maximum" in response.json()["message"]+ assert self.s3.written == {}++ def test_rejects_an_oversized_request_body_before_storing_anything(self) -> None:+ # Guards the Content-Length pre-check that bounds the whole body before the multipart parser+ # spools parts to disk — dropping it would let a large body through to be written.+ with patch(f"{VIEW_MODULE}.MAX_UPLOAD_REQUEST_BODY_BYTES", 4):+ response = self._upload(+ file=SimpleUploadedFile("data.csv", b"a\n1\n", content_type="text/csv"),+ file_format="csv",+ )++ assert response.status_code == status.HTTP_413_REQUEST_ENTITY_TOO_LARGE+ assert "Upload exceeds the maximum" in response.json()["message"]+ assert self.s3.written == {}++ def test_rejects_more_than_one_file_part(self) -> None:+ with patch(f"{VIEW_MODULE}.get_s3_client", return_value=self.s3):+ response = self.client.post(+ self.url,+ {+ "file": [+ SimpleUploadedFile("a.csv", b"a\n1\n", content_type="text/csv"),+ SimpleUploadedFile("b.csv", b"b\n2\n", content_type="text/csv"),+ ],+ "file_format": "csv",+ },+ format="multipart",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["message"] == "Upload one file per request."+ assert self.s3.written == {}++ @override_settings(DATAWAREHOUSE_BUCKET=None)+ def test_rejects_when_object_storage_is_unavailable(self) -> None:+ response = self._upload(+ file=SimpleUploadedFile("data.csv", b"a\n1\n", content_type="text/csv"),+ file_format="csv",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "Object storage" in response.json()["message"]++ def test_requires_authentication(self) -> None:+ self.client.logout()+ response = self.client.post(+ self.url,+ {"file": SimpleUploadedFile("data.csv", b"a\n1\n"), "file_format": "csv"},+ format="multipart",+ )++ assert response.status_code == status.HTTP_401_UNAUTHORIZED+ assert self.s3.written == {}+++@override_settings(DATAWAREHOUSE_BUCKET="test-bucket", DATAWAREHOUSE_BUCKET_DOMAIN="warehouse.posthog.test")+class TestCreateTableFromUpload(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.upload_url = f"/api/environments/{self.team.pk}/warehouse_tables/upload_file/"+ self.create_url = f"/api/environments/{self.team.pk}/warehouse_tables/create_from_upload/"++ def _upload(self, filename: str = "orders.csv", file_format: str = "csv") -> str:+ with patch(f"{VIEW_MODULE}.get_s3_client", return_value=_FakeS3()):+ response = self.client.post(+ self.upload_url,+ {"file": SimpleUploadedFile(filename, b"id,total\n1,9\n"), "file_format": file_format},+ format="multipart",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ return response.json()["upload_id"]++ def _create(self, *, exists: bool = True, **payload):+ with (+ patch(f"{VIEW_MODULE}.get_s3_client", return_value=_FakeS3(exists_result=exists)),+ patch(f"{MODEL_MODULE}.DataWarehouseTable.get_columns", return_value=dict(FAKE_COLUMNS)),+ # Background column validation runs eagerly under test and would re-query the (faked) S3+ # table, stamping `valid` onto each column. It's out of scope for these wiring tests, so+ # keep it from mutating the columns the create endpoint just persisted.+ patch(f"{VIEW_MODULE}.validate_data_warehouse_table_columns.delay"),+ ):+ return self.client.post(f"{self.create_url}?include_columns=false", data=payload, format="json")++ def test_an_uploaded_file_becomes_a_self_managed_table(self) -> None:+ # The wiring guard for the two-step contract: the upload endpoint's `upload_id` has to be+ # accepted by create_from_upload, and the result has to be a self-managed table (no source,+ # queried in place from our own bucket) rather than a pipeline ExternalDataSource.+ upload_id = self._upload()++ response = self._create(upload_id=upload_id, filename="orders.csv", file_format="csv", table_name="orders")++ assert response.status_code == status.HTTP_201_CREATED, response.json()++ table = DataWarehouseTable.objects.get(id=response.json()["id"])+ assert table.name == "orders"+ assert table.external_data_source is None+ assert table.credential is None+ assert table.format == "CSVWithNames"+ assert (+ table.url_pattern+ == f"https://warehouse.posthog.test/file_uploads/team_{self.team.pk}/{upload_id}/orders.csv"+ )+ assert table.columns == FAKE_COLUMNS+ # No pipeline source is created — this is the whole point of the self-managed shape.+ assert ExternalDataSource.objects.count() == 0++ @parameterized.expand(+ [+ ("csv", "CSVWithNames"),+ ("json", "JSONEachRow"),+ ("parquet", "Parquet"),+ ]+ )+ def test_file_format_maps_to_table_format(self, file_format: str, expected_format: str) -> None:+ upload_id = self._upload(filename=f"data.{file_format}", file_format=file_format)++ response = self._create(+ upload_id=upload_id,+ filename=f"data.{file_format}",+ file_format=file_format,+ table_name=f"data_{file_format}",+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ table = DataWarehouseTable.objects.get(id=response.json()["id"])+ assert table.format == expected_format++ def test_url_pattern_is_scoped_to_the_requesting_team(self) -> None:+ # The read location is always built from the caller's own team, so a client-supplied upload_id+ # can only ever resolve inside that team's folder.+ upload_id = self._upload()++ response = self._create(upload_id=upload_id, filename="orders.csv", file_format="csv", table_name="orders")++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ table = DataWarehouseTable.objects.get(id=response.json()["id"])+ assert f"/team_{self.team.pk}/" in table.url_pattern++ def test_rejects_a_duplicate_table_name(self) -> None:+ upload_id = self._upload()+ first = self._create(upload_id=upload_id, filename="orders.csv", file_format="csv", table_name="orders")+ assert first.status_code == status.HTTP_201_CREATED, first.json()++ second = self._create(upload_id=upload_id, filename="orders.csv", file_format="csv", table_name="orders")+ assert second.status_code == status.HTTP_400_BAD_REQUEST+ assert "already exists" in second.json()["message"]++ def test_rejects_an_invalid_table_name(self) -> None:+ upload_id = self._upload()+ response = self._create(upload_id=upload_id, filename="orders.csv", file_format="csv", table_name="1-bad name")+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_rejects_when_the_uploaded_file_is_missing(self) -> None:+ upload_id = self._upload()+ response = self._create(+ upload_id=upload_id, filename="orders.csv", file_format="csv", table_name="orders", exists=False+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "not found" in response.json()["message"]+ assert DataWarehouseTable.objects.count() == 0diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.tsindex d256f6b41d78..0209d97da35c 100644--- a/products/data_warehouse/frontend/generated/api.schemas.ts+++ b/products/data_warehouse/frontend/generated/api.schemas.ts@@ -3839,6 +3839,46 @@ export interface PatchedTableApi {readonly user_access_level?: string | null}+/**+ * * `csv` - csv+ * * `json` - json+ * * `parquet` - parquet+ */+export type CreateTableFromUploadFileFormatEnumApi =+ (typeof CreateTableFromUploadFileFormatEnumApi)[keyof typeof CreateTableFromUploadFileFormatEnumApi]++export const CreateTableFromUploadFileFormatEnumApi = {+ Csv: 'csv',+ Json: 'json',+ Parquet: 'parquet',+} as const++export interface CreateTableFromUploadApi {+ /** Id returned by upload_file for the stored file. */+ upload_id: string+ /** Sanitized filename returned by upload_file. */+ filename: string+ /** How the uploaded file is read: 'csv', 'json', or 'parquet'.+ *+ * * `csv` - csv+ * * `json` - json+ * * `parquet` - parquet */+ file_format: CreateTableFromUploadFileFormatEnumApi+ /** Name the resulting table is queried by in HogQL. */+ table_name: string+}++export interface FileUploadResponseApi {+ /** Id of the stored upload. Pass it to create_from_upload to build the table. */+ upload_id: string+ /** Sanitized name the file was stored under. */+ filename: string+ /** Format the file will be read as: 'csv', 'json', or 'parquet'. */+ file_format: string+ /** Size of the stored file in bytes. */+ size_bytes: number+}+export interface ViewLinkApi {readonly id: string/** @nullable */@@ -4054,6 +4094,25 @@ export type WarehouseTablesListParams = {search?: string}+/**+ * How the file will be read when the table is created.+ */+export type WarehouseTablesUploadFileCreateBodyFileFormat =+ (typeof WarehouseTablesUploadFileCreateBodyFileFormat)[keyof typeof WarehouseTablesUploadFileCreateBodyFileFormat]++export const WarehouseTablesUploadFileCreateBodyFileFormat = {+ Csv: 'csv',+ Json: 'json',+ Parquet: 'parquet',+} as const++export type WarehouseTablesUploadFileCreateBody = {+ /** The file to upload. */+ file: Blob+ /** How the file will be read when the table is created. */+ file_format: WarehouseTablesUploadFileCreateBodyFileFormat+}+export type WarehouseViewLinkListParams = {/*** Number of results to return per page.diff --git a/products/data_warehouse/frontend/generated/api.ts b/products/data_warehouse/frontend/generated/api.tsindex 295beb1a0a66..717a74f03260 100644--- a/products/data_warehouse/frontend/generated/api.ts+++ b/products/data_warehouse/frontend/generated/api.ts@@ -11,6 +11,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'import type {CheckDatabaseNameResponseApi,CheckSchemaNameResponseApi,+ CreateTableFromUploadApi,DataModelingJobApi,DataModelingJobsListParams,DataWarehouseCheckDatabaseNameRetrieveParams,@@ -23,6 +24,7 @@ import type {DataWarehouseSavedQueryFolderApi,DeleteWarehouseOrgResponseApi,DeprovisionWarehouseResponseApi,+ FileUploadResponseApi,FixHogqlListParams,InsightVariableApi,InsightVariablesListParams,@@ -68,6 +70,7 @@ import type {WarehouseSavedQueryDraftsListParams,WarehouseStatusResponseApi,WarehouseTablesListParams,+ WarehouseTablesUploadFileCreateBody,WarehouseViewLinkListParams,WarehouseViewLinksListParams,} from './api.schemas'@@ -2039,6 +2042,33 @@ export const warehouseTablesUpdateSchemaCreate = async (})}+export const getWarehouseTablesCreateFromUploadCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/warehouse_tables/create_from_upload/`+}++/**+ * Turn a previously uploaded file into a self-managed warehouse table.+ *+ * The file already sits in PostHog's own bucket (see `upload_file`), so the table points straight+ * at it and is read in place — no import pipeline and no recurring sync, the same shape as a linked+ * S3/GCS bucket. The read location is always derived from the caller's own team, so a client-supplied+ * `upload_id` can only resolve inside that team's folder, and the table carries no credential (reads+ * fall back to the node role, never a user-supplied key).+ * @summary Create a self-managed warehouse table from an uploaded file+ */+export const warehouseTablesCreateFromUploadCreate = async (+ projectId: string,+ createTableFromUploadApi: CreateTableFromUploadApi,+ options?: RequestInit+): Promise<TableApi> => {+ return apiMutator<TableApi>(getWarehouseTablesCreateFromUploadCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(createTableFromUploadApi),+ })+}+export const getWarehouseTablesFileCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/warehouse_tables/file/`}@@ -2070,6 +2100,38 @@ export const warehouseTablesFileCreate = async (})}+export const getWarehouseTablesUploadFileCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/warehouse_tables/upload_file/`+}++/**+ * Store an uploaded file in object storage so a self-managed table can be created from it.+ *+ * Uploading is a separate first step from `create_from_upload` so the create call stays JSON-only:+ * this returns an `upload_id` the caller passes back to build the table. The file is written under+ * a team-scoped prefix, so a table can only ever read back its own team's uploads.+ * @summary Upload a file for a new self-managed warehouse table+ */+export const warehouseTablesUploadFileCreate = async (+ projectId: string,+ warehouseTablesUploadFileCreateBody?: WarehouseTablesUploadFileCreateBody,+ options?: RequestInit+): Promise<FileUploadResponseApi> => {+ const formData = new FormData()+ if (warehouseTablesUploadFileCreateBody?.file !== undefined) {+ formData.append(`file`, warehouseTablesUploadFileCreateBody.file)+ }+ if (warehouseTablesUploadFileCreateBody?.file_format !== undefined) {+ formData.append(`file_format`, warehouseTablesUploadFileCreateBody.file_format)+ }++ return apiMutator<FileUploadResponseApi>(getWarehouseTablesUploadFileCreateUrl(projectId), {+ ...options,+ method: 'POST',+ body: formData,+ })+}+export const getWarehouseViewLinkListUrl = (projectId: string, params?: WarehouseViewLinkListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/data_warehouse/frontend/generated/api.zod.ts b/products/data_warehouse/frontend/generated/api.zod.tsindex cf0c4794fc7c..51c2f667732d 100644--- a/products/data_warehouse/frontend/generated/api.zod.ts+++ b/products/data_warehouse/frontend/generated/api.zod.ts@@ -999,6 +999,28 @@ export const WarehouseTablesUpdateSchemaCreateBody = /* @__PURE__ */ zod.record(zod.string(), zod.unknown()).describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')+/**+ * Turn a previously uploaded file into a self-managed warehouse table.+ *+ * The file already sits in PostHog's own bucket (see `upload_file`), so the table points straight+ * at it and is read in place — no import pipeline and no recurring sync, the same shape as a linked+ * S3/GCS bucket. The read location is always derived from the caller's own team, so a client-supplied+ * `upload_id` can only resolve inside that team's folder, and the table carries no credential (reads+ * fall back to the node role, never a user-supplied key).+ * @summary Create a self-managed warehouse table from an uploaded file+ */+export const WarehouseTablesCreateFromUploadCreateBody = /* @__PURE__ */ zod.object({+ upload_id: zod.uuid().describe('Id returned by upload_file for the stored file.'),+ filename: zod.string().describe('Sanitized filename returned by upload_file.'),+ file_format: zod+ .enum(['csv', 'json', 'parquet'])+ .describe('\* `csv` - csv\n\* `json` - json\n\* `parquet` - parquet')+ .describe(+ "How the uploaded file is read: 'csv', 'json', or 'parquet'.\n\n\* `csv` - csv\n\* `json` - json\n\* `parquet` - parquet"+ ),+ table_name: zod.string().describe('Name the resulting table is queried by in HogQL.'),+})+/*** Create, Read, Update and Delete Warehouse Tables.*/@@ -1006,6 +1028,19 @@ export const WarehouseTablesFileCreateBody = /* @__PURE__ */ zod.record(zod.string(), zod.unknown()).describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')+/**+ * Store an uploaded file in object storage so a self-managed table can be created from it.+ *+ * Uploading is a separate first step from `create_from_upload` so the create call stays JSON-only:+ * this returns an `upload_id` the caller passes back to build the table. The file is written under+ * a team-scoped prefix, so a table can only ever read back its own team's uploads.+ * @summary Upload a file for a new self-managed warehouse table+ */+export const WarehouseTablesUploadFileCreateBody = /* @__PURE__ */ zod.object({+ file: zod.instanceof(File).describe('The file to upload.'),+ file_format: zod.enum(['csv', 'json', 'parquet']).describe('How the file will be read when the table is created.'),+})+/*** Create, Read, Update and Delete View Columns.*/diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsxindex 3ca8282562fd..132c4f53a26b 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsx+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsx@@ -36,7 +36,9 @@ import { FreeHistoricalSyncsBanner } from '../../shared/components/FreeHistoricaimport { SourceIcon } from '../../shared/components/SourceIcon'import { availableSourcesLogic } from './availableSourcesLogic'import { BillingLimitNotice } from './components/BillingLimitNotice'+import { FileUploadSourceForm } from './components/FileUploadSourceForm'import { SelfManagedSourceForm } from './components/SelfManagedSourceForm'+import { FILE_UPLOAD_SOURCE_NAME } from './fileUploadSource'import { selfManagedSourceLogic } from './selfManagedSourceLogic'import { SourceCatalog } from './SourceCatalog'import { type SourceWizardLogicProps, sourceWizardLogic } from './sourceWizardLogic'@@ -250,11 +252,19 @@ function InternalSourcesWizard(props: NewSourcesWizardProps): JSX.Element {}}, [props.initialSource]) // oxlint-disable-line react-hooks/exhaustive-deps+ const isFileUploadSource = selectedConnector?.name === FILE_UPLOAD_SOURCE_NAME+const footer = useCallback(() => {if (currentStep === 1) {return null}+ // The file upload form has its own submit button — the wizard's Next would submit the+ // generic connection form that this source never renders.+ if (isFileUploadSource) {+ return null+ }+const nextButton = (disabledReason?: string | false): JSX.Element => (<LemonButtonloading={isLoading || manualLinkIsLoading}@@ -307,6 +317,7 @@ function InternalSourcesWizard(props: NewSourcesWizardProps): JSX.Element {onSubmit,props.hideBackButton,isSelfManagedSource,+ isFileUploadSource,])return (@@ -507,6 +518,12 @@ function SecondStep({ sourceWizardLogicProps }: { sourceWizardLogicProps?: Sourcsource.access_method)+ // File upload owns its whole flow (upload the file, then create the source), so it replaces the+ // generic connection form and drives its own submit button rather than the wizard footer.+ if (selectedConnector?.name === FILE_UPLOAD_SOURCE_NAME) {+ return <FileUploadSourceForm />+ }+return selectedConnector ? (<div className="space-y-4">{selectedConnector.caption && selectedAccessMethod !== 'direct' && (diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/components/FileUploadSourceForm.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/components/FileUploadSourceForm.tsxnew file mode 100644index 000000000000..d796ac2c0a51--- /dev/null+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/components/FileUploadSourceForm.tsx@@ -0,0 +1,88 @@+import { useActions, useValues } from 'kea'+import { Form } from 'kea-forms'++import { LemonButton, LemonInput, LemonSelect } from '@posthog/lemon-ui'++import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput/LemonFileInput'++import { FILE_UPLOAD_ACCEPT, fileUploadSourceLogic } from '../fileUploadSourceLogic'++export function FileUploadSourceForm(): JSX.Element {+ const { fileUpload, isFileUploadSubmitting } = useValues(fileUploadSourceLogic)+ const { selectFiles, setTableName, setFileFormat } = useActions(fileUploadSourceLogic)++ return (+ <Form+ formKey="fileUpload"+ logic={fileUploadSourceLogic}+ className="deprecated-space-y-4"+ enableFormOnSubmit+ autoComplete="off"+ >+ <div className="flex flex-col gap-2">+ <LemonField name="file_format" label="File format" className="w-max">+ {({ value }) => (+ <LemonSelect+ data-attr="file-upload-format"+ options={[+ { label: 'CSV', value: 'csv' },+ { label: 'JSON', value: 'json' },+ { label: 'Parquet', value: 'parquet' },+ ]}+ value={value}+ onChange={setFileFormat}+ disabledReason={isFileUploadSubmitting ? 'Uploading your file' : undefined}+ />+ )}+ </LemonField>++ <LemonField name="files" label="File">+ {({ value }) => (+ <LemonFileInput+ multiple={false}+ accept={FILE_UPLOAD_ACCEPT[fileUpload.file_format]}+ value={value}+ onChange={selectFiles}+ disabledReason={isFileUploadSubmitting ? 'Uploading your file' : undefined}+ />+ )}+ </LemonField>+ <div className="mb-4 text-xs text-secondary">Files can be up to 50MB.</div>++ <LemonField name="table_name" label="Table name">+ {({ value = '' }) => (+ <LemonInput+ data-attr="file-upload-table-name"+ className="ph-ignore-input"+ placeholder="Examples: monthly_revenue, customer_list"+ autoComplete="off"+ autoCapitalize="off"+ autoCorrect="off"+ spellCheck={false}+ value={value}+ onChange={setTableName}+ disabled={isFileUploadSubmitting}+ />+ )}+ </LemonField>+ <div className="mb-4 text-xs text-secondary">+ This will be the table name used when writing queries. Use only letters, numbers, and underscores,+ and start with a letter or underscore.+ </div>+ </div>++ <div className="flex justify-end">+ <LemonButton+ type="primary"+ htmlType="submit"+ loading={isFileUploadSubmitting}+ disabledReason={isFileUploadSubmitting ? 'Uploading your file' : undefined}+ data-attr="file-upload-submit"+ >+ Upload and create table+ </LemonButton>+ </div>+ </Form>+ )+}diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSource.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSource.tsnew file mode 100644index 000000000000..97cdf484bb40--- /dev/null+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSource.ts@@ -0,0 +1,35 @@+import { urls } from 'scenes/urls'++import { ExternalDataSourceType, SourceConfig } from '~/queries/schema/schema-general'++// File upload is a client-only catalog entry — it has no backend SourceConfig because an uploaded+// file becomes a self-managed DataWarehouseTable (read in place from our own bucket), not a synced+// source. `FileUpload` is deliberately not a real `ExternalDataSourceType` (there is no backend+// source of that type), so it's cast here once to reuse the shared `SourceConfig` shape and the+// wizard's connector-selection plumbing. This synthetic config drives the wizard's second step and+// the tile icon; the three tiles below (one per format) all point back at it, since users look for+// "CSV", not "File upload".+export const FILE_UPLOAD_SOURCE_NAME = 'FileUpload' as unknown as ExternalDataSourceType++export type FileUploadFormat = 'csv' | 'json' | 'parquet'++export const FILE_UPLOAD_SOURCE_CONFIG: SourceConfig = {+ name: FILE_UPLOAD_SOURCE_NAME,+ label: 'File upload',+ caption: 'Upload a CSV, JSON, or Parquet file to query it in the PostHog data warehouse.',+ iconPath: '/static/services/file-upload.svg',+ releaseStatus: 'alpha',+ // The upload form is bespoke (`FileUploadSourceForm`), so no generic connection fields.+ fields: [],+}++export const FILE_UPLOAD_FORMATS: { format: FileUploadFormat; label: string; keywords: string[] }[] = [+ { format: 'csv', label: 'CSV file', keywords: ['csv', 'spreadsheet', 'excel export', 'comma separated', 'upload'] },+ { format: 'json', label: 'JSON file', keywords: ['json', 'ndjson', 'jsonl', 'upload'] },+ { format: 'parquet', label: 'Parquet file', keywords: ['parquet', 'pqt', 'columnar', 'upload'] },+]++export function fileUploadSourceUrl(format: FileUploadFormat): string {+ const url = urls.dataWarehouseSourceNew(FILE_UPLOAD_SOURCE_NAME)+ return `${url}${url.includes('?') ? '&' : '?'}format=${format}`+}diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.tsxnew file mode 100644index 000000000000..591942fe8ec3--- /dev/null+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.tsx@@ -0,0 +1,229 @@+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'+import { forms } from 'kea-forms'+import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'+import { router, urlToAction } from 'kea-router'++import { lemonToast } from '@posthog/lemon-ui'++import api from 'lib/api'+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'+import { urls } from 'scenes/urls'++import { FileUploadFormat } from './fileUploadSource'++// Mirrors MAX_FILE_UPLOAD_SIZE_BYTES on the backend. Checked here too so an oversized file fails+// instantly instead of after uploading 50MB+ only to be rejected.+export const MAX_FILE_UPLOAD_SIZE_BYTES = 50 * 1024 * 1024++export const FILE_UPLOAD_ACCEPT: Record<FileUploadFormat, string> = {+ csv: '.csv',+ json: '.json,.ndjson',+ parquet: '.parquet',+}++const HOGQL_TABLE_NAME_REGEX = /^[a-zA-Z_][a-zA-Z0-9_]*$/++export interface FileUploadForm {+ files: File[]+ table_name: string+ file_format: FileUploadFormat+}++export function deriveTableName(filename: string): string {+ const withoutExtension = filename.replace(/\.[^.]+$/, '')+ const slug = withoutExtension+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '_')+ .replace(/_+$/, '')+ if (!slug) {+ return 'uploaded_file'+ }+ return /^[0-9]/.test(slug) ? `_${slug}` : slug+}++export function parseFileUploadFormat(value: string | undefined): FileUploadFormat | null {+ const normalized = value?.toLowerCase()+ return normalized === 'csv' || normalized === 'json' || normalized === 'parquet' ? normalized : null+}++export function fileUploadFormErrors({ files, table_name }: Partial<FileUploadForm>): Record<string, unknown> {+ const file = files?.[0]+ return {+ files: !file+ ? 'Please choose a file to upload.'+ : file.size > MAX_FILE_UPLOAD_SIZE_BYTES+ ? 'This file is larger than 50MB. For bigger files, connect the bucket they live in as a self-managed source instead.'+ : undefined,+ table_name: !table_name+ ? 'Please enter a table name.'+ : !HOGQL_TABLE_NAME_REGEX.test(table_name)+ ? 'Table names must start with a letter or underscore and contain only letters, numbers, and underscores.'+ : undefined,+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface fileUploadSourceLogicValues {+ fileUpload: FileUploadForm+ fileUploadAllErrors: Record<string, any>+ fileUploadChanged: boolean+ fileUploadErrors: DeepPartialMap<FileUploadForm, ValidationErrorType>+ fileUploadHasErrors: boolean+ fileUploadManualErrors: Record<string, any>+ fileUploadTouched: boolean+ fileUploadTouches: Record<string, boolean>+ fileUploadValidationErrors: DeepPartialMap<FileUploadForm, ValidationErrorType>+ isFileUploadSubmitting: boolean+ isFileUploadValid: boolean+ showFileUploadErrors: boolean+ tableNameEdited: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface fileUploadSourceLogicActions {+ loadDatabase: (+ args_0?:+ | {+ force?: boolean+ }+ | undefined+ ) => {+ force?: boolean+ } // databaseTableListLogic+ resetFileUpload: (values?: FileUploadForm) => {+ values?: FileUploadForm+ }+ selectFiles: (files: File[]) => {+ files: File[]+ }+ setFileFormat: (fileFormat: FileUploadFormat) => {+ fileFormat: FileUploadFormat+ }+ setFileUploadManualErrors: (errors: Record<string, any>) => {+ errors: Record<string, any>+ }+ setFileUploadValue: (+ key: FieldName,+ value: any+ ) => {+ name: FieldName+ value: any+ }+ setFileUploadValues: (values: DeepPartial<FileUploadForm>) => {+ values: DeepPartial<FileUploadForm>+ }+ setTableName: (tableName: string) => {+ tableName: string+ }+ submitFileUpload: () => {+ value: boolean+ }+ submitFileUploadFailure: (+ error: Error,+ errors: Record<string, any>+ ) => {+ error: Error+ errors: Record<string, any>+ }+ submitFileUploadRequest: (fileUpload: FileUploadForm) => {+ fileUpload: FileUploadForm+ }+ submitFileUploadSuccess: (fileUpload: FileUploadForm) => {+ fileUpload: FileUploadForm+ }+ touchFileUploadField: (key: string) => {+ key: string+ }+}++export type fileUploadSourceLogicType = MakeLogicType<fileUploadSourceLogicValues, fileUploadSourceLogicActions>++export const fileUploadSourceLogic = kea<fileUploadSourceLogicType>([+ path(['products', 'dataWarehouse', 'fileUploadSourceLogic']),+ connect(() => ({+ actions: [databaseTableListLogic, ['loadDatabase']],+ })),+ actions({+ selectFiles: (files: File[]) => ({ files }),+ setTableName: (tableName: string) => ({ tableName }),+ setFileFormat: (fileFormat: FileUploadFormat) => ({ fileFormat }),+ }),+ reducers({+ // Once the user types their own table name we stop overwriting it when they swap the file.+ tableNameEdited: [false, { setTableName: () => true }],+ }),+ forms(({ actions }) => ({+ fileUpload: {+ defaults: {+ files: [] as File[],+ table_name: '',+ file_format: parseFileUploadFormat(router.values.searchParams.format) ?? 'csv',+ } as FileUploadForm,+ errors: fileUploadFormErrors,+ submit: async ({ files, table_name, file_format }) => {+ const file = files[0]+ // The form's `errors` already block submission, but a stale/oversized file can only+ // be reported as a toast — the button is what the user is looking at.+ if (!file) {+ lemonToast.error('Please choose a file to upload.')+ return+ }+ if (file.size > MAX_FILE_UPLOAD_SIZE_BYTES) {+ lemonToast.error('This file is larger than the 50MB upload limit.')+ return+ }++ const formData = new FormData()+ formData.append('file', file)+ formData.append('file_format', file_format)++ let upload+ try {+ upload = await api.dataWarehouseTables.uploadFile(formData)+ } catch (e: any) {+ lemonToast.error(e.data?.message ?? e.message ?? 'Could not upload the file.')+ return+ }++ try {+ await api.dataWarehouseTables.createFromUpload({+ upload_id: upload.upload_id,+ filename: upload.filename,+ file_format,+ table_name,+ })+ } catch (e: any) {+ lemonToast.error(e.data?.message ?? e.message ?? 'Could not create the table.')+ return+ }++ lemonToast.success(`Table ${table_name} created`)+ actions.loadDatabase()+ router.actions.replace(urls.sources())+ },+ },+ })),+ listeners(({ actions, values }) => ({+ selectFiles: ({ files }) => {+ actions.setFileUploadValue('files', files)+ const file = files[0]+ if (file && !values.tableNameEdited) {+ actions.setFileUploadValue('table_name', deriveTableName(file.name))+ }+ },+ setTableName: ({ tableName }) => {+ actions.setFileUploadValue('table_name', tableName)+ },+ setFileFormat: ({ fileFormat }) => {+ actions.setFileUploadValue('file_format', fileFormat)+ },+ })),+ urlToAction(({ actions }) => ({+ [urls.dataWarehouseSourceNew()]: (_, searchParams) => {+ const format = parseFileUploadFormat(searchParams.format)+ if (format) {+ actions.setFileFormat(format)+ }+ },+ })),+])diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceCatalogLogic.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceCatalogLogic.tsindex cf733445b522..3067645e284b 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceCatalogLogic.ts+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceCatalogLogic.ts@@ -23,6 +23,12 @@ import { HogFunctionTemplateStatus } from '~/types'import type { FeatureFlagsSet } from '../../../../../frontend/src/lib/logic/featureFlagLogic'import type { ManualLinkSourceType, UserType } from '../../../../../frontend/src/types'import { availableSourcesLogic } from './availableSourcesLogic'+import {+ FILE_UPLOAD_FORMATS,+ FILE_UPLOAD_SOURCE_CONFIG,+ FILE_UPLOAD_SOURCE_NAME,+ fileUploadSourceUrl,+} from './fileUploadSource'import { sourceWizardLogic } from './sourceWizardLogic'// Helps kea-typegen reference the Fuse type without a bad `import { Fuse } from 'fuse.js'`.@@ -1480,7 +1486,7 @@ export const sourceCatalogLogic = kea<sourceCatalogLogicType>([): CatalogItem[] => {const managed = Object.values(availableSources ?? {}).filter((c) => !allowedSources || allowedSources.includes(c.name))- .map((connector: SourceConfig): CatalogItem => {+ .flatMap((connector: SourceConfig): CatalogItem[] => {// Mirror nonHogFunctionTemplatesLogic: a declared-but-absent flag reads as// off (featureFlagLogic only exposes truthy flags), so flag-gated sources// render as coming-soon ("Notify me") until the user is in the rollout.@@ -1494,19 +1500,21 @@ export const sourceCatalogLogic = kea<sourceCatalogLogicType>([? connector.releaseStatus: undefined- return {- name: connector.name,- label: connector.label ?? connector.name,- iconType: connector.name,- iconClassName: connector.iconClassName,- category: connector.category ?? MANUAL_SOURCE_CATEGORY,- keywords: connector.keywords ?? [],- status,- releaseStatus,- url: urls.dataWarehouseSourceNew(connector.name),- disabledReason: connector.disabledReason,- existingSource: connector.existingSource,- }+ return [+ {+ iconType: connector.name,+ iconClassName: connector.iconClassName,+ category: connector.category ?? MANUAL_SOURCE_CATEGORY,+ status,+ releaseStatus,+ disabledReason: connector.disabledReason,+ existingSource: connector.existingSource,+ name: connector.name,+ label: connector.label ?? connector.name,+ keywords: connector.keywords ?? [],+ url: urls.dataWarehouseSourceNew(connector.name),+ },+ ]})const selfManaged = manualConnectors.map(@@ -1522,7 +1530,24 @@ export const sourceCatalogLogic = kea<sourceCatalogLogicType>([}))- return [...managed, ...selfManaged]+ // File upload is self-managed too — the uploaded file becomes an in-place table — but+ // it isn't a `manualConnector` (those link a user's own bucket). It's one entry with+ // three tiles, one per format, since users search for "CSV" rather than "File upload".+ const fileUpload = FILE_UPLOAD_FORMATS.map(+ ({ format, label, keywords }): CatalogItem => ({+ name: `${FILE_UPLOAD_SOURCE_NAME}-${format}`,+ label,+ iconType: FILE_UPLOAD_SOURCE_NAME,+ category: MANUAL_SOURCE_CATEGORY,+ keywords,+ status: 'stable',+ releaseStatus: FILE_UPLOAD_SOURCE_CONFIG.releaseStatus,+ url: fileUploadSourceUrl(format),+ selfManaged: true,+ })+ )++ return [...managed, ...selfManaged, ...fileUpload]},// featureFlags is a broad dependency that changes identity on every flag refresh;// keeping the previous array when the derived catalog is unchanged stops the Fusediff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsxindex 976546f0afdd..ae696a49312b 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx@@ -54,6 +54,7 @@ import {} from '../../shared/components/forms/schemaGroupingUtils'import type { WebhookCreateResult } from '../../shared/components/forms/WebhookSetupForm'import { sourceManagementLogic } from '../../shared/logics/sourceManagementLogic'+import { FILE_UPLOAD_SOURCE_CONFIG, FILE_UPLOAD_SOURCE_NAME } from './fileUploadSource'import { selfManagedSourceLogic } from './selfManagedSourceLogic'import { restoreSourceFormState, saveSourceFormState } from './wizardFormStorage'@@ -3530,6 +3531,17 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([actions.clearReturnConfig()}+ // File upload has no backend connector (the uploaded file becomes a self-managed table),+ // so resolve its client-only synthetic config directly rather than from `connectors`.+ if (kind === FILE_UPLOAD_SOURCE_NAME.toLowerCase()) {+ if (values.selectedConnector?.name === FILE_UPLOAD_SOURCE_NAME && values.currentStep > 1) {+ return+ }+ actions.selectConnector(FILE_UPLOAD_SOURCE_CONFIG)+ actions.setStep(2)+ return+ }+const source = values.connectors?.find((s) => s?.name?.toLowerCase?.() === kind)const manualSource = values.manualConnectors?.find((s) => s?.type?.toLowerCase() === kind)diff --git a/products/data_warehouse/frontend/shared/components/SourceIcon.tsx b/products/data_warehouse/frontend/shared/components/SourceIcon.tsxindex f6f265e39d3b..15e931ead2c4 100644--- a/products/data_warehouse/frontend/shared/components/SourceIcon.tsx+++ b/products/data_warehouse/frontend/shared/components/SourceIcon.tsx@@ -13,6 +13,7 @@ import IconAwsS3 from 'public/services/aws-s3.png'import Iconazure from 'public/services/azure.png'import IconCloudflare from 'public/services/cloudflare.png'import IconDuckDB from 'public/services/duckdb.svg'+import IconFileUpload from 'public/services/file-upload.svg'import IconGoogleCloudStorage from 'public/services/google-cloud-storage.png'import { availableSourcesLogic } from '../../scenes/NewSourceScene/availableSourcesLogic'@@ -86,6 +87,8 @@ export const DATA_WAREHOUSE_SOURCE_ICON_MAP: Record<string, string> = {'google-cloud': IconGoogleCloudStorage,'cloudflare-r2': IconCloudflare,azure: Iconazure,+ // File upload has no backend SourceConfig (its `iconPath`), so map its icon here directly.+ FileUpload: IconFileUpload,BlushingHog: BlushingHog, // fallback, we don't know what this isPostHog: IconPostHog,}diff --git a/products/data_warehouse/mcp/tools.yaml b/products/data_warehouse/mcp/tools.yamlindex 4a63da335ba7..5fe2b5da7c3b 100644--- a/products/data_warehouse/mcp/tools.yaml+++ b/products/data_warehouse/mcp/tools.yaml@@ -527,6 +527,9 @@ tools:warehouse-tables-create:operation: warehouse_tables_createenabled: false+ warehouse-tables-create-from-upload-create:+ operation: warehouse_tables_create_from_upload_create+ enabled: falsewarehouse-tables-destroy:operation: warehouse_tables_destroyenabled: false@@ -564,6 +567,9 @@ tools:warehouse-tables-update-schema-create:operation: warehouse_tables_update_schema_createenabled: false+ warehouse-tables-upload-file-create:+ operation: warehouse_tables_upload_file_create+ enabled: falsewarehouse-view-link-create:operation: warehouse_view_link_createenabled: falsediff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.pyindex cf2c85f3807f..37e925554adc 100644--- a/products/warehouse_sources/backend/facade/api.py+++ b/products/warehouse_sources/backend/facade/api.py@@ -18,6 +18,15 @@ first facade serves the read consumers and the framework-free helpers.from uuid import UUID+# Source-agnostic storage contract for user-uploaded files — shared with the upload endpoint.+from products.warehouse_sources.backend.file_uploads import (+ FILE_FORMAT_TO_TABLE_FORMAT,+ MAX_UPLOAD_SIZE_BYTES as MAX_FILE_UPLOAD_SIZE_BYTES,+ SUPPORTED_FILE_FORMATS,+ build_file_upload_s3_key,+ build_file_upload_s3_path,+ build_file_upload_url_pattern,+)from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob as _ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema as _ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource as _ExternalDataSource@@ -53,6 +62,13 @@ __all__ = ["snowflake_columns_to_dwh_columns","validate_source_prefix","validate_warehouse_table_url_pattern",+ # file-upload storage contract+ "FILE_FORMAT_TO_TABLE_FORMAT",+ "MAX_FILE_UPLOAD_SIZE_BYTES",+ "SUPPORTED_FILE_FORMATS",+ "build_file_upload_s3_key",+ "build_file_upload_s3_path",+ "build_file_upload_url_pattern",]# --- Mappers (ORM -> contract) ---diff --git a/products/warehouse_sources/backend/file_uploads.py b/products/warehouse_sources/backend/file_uploads.pynew file mode 100644index 000000000000..994b46949ff5--- /dev/null+++ b/products/warehouse_sources/backend/file_uploads.py@@ -0,0 +1,70 @@+"""Storage contract for user-uploaded source files.++Framework-free and source-agnostic on purpose: the upload endpoint and the table-create endpoint+(both in ``data_warehouse``) share this key layout, so it has to live in exactly one place. Uploads+land in PostHog's own data warehouse bucket, namespaced by team then by a per-upload id, which is+what keeps a table's read path scoped to its own team's files.++An uploaded file becomes a self-managed ``DataWarehouseTable`` pointing straight at the stored+object: PostHog reads it in place from its own bucket, so there is no import pipeline and no+recurring sync — the same shape as a linked S3/GCS bucket, just hosted by us.+"""++from django.conf import settings++# Top-level bucket folder for user-uploaded files.+FILE_UPLOADS_FOLDER = "file_uploads"++# Formats a user can upload. Lowercase tokens accepted by the upload endpoint and mapped to a+# ClickHouse read format (`FILE_FORMAT_TO_TABLE_FORMAT`) when the table is created.+FORMAT_CSV = "csv"+FORMAT_JSON = "json"+FORMAT_PARQUET = "parquet"++SUPPORTED_FILE_FORMATS = (FORMAT_CSV, FORMAT_JSON, FORMAT_PARQUET)++# Maps an uploaded file's format to the `DataWarehouseTable.TableFormat` value ClickHouse reads it+# with in place. CSV is assumed to carry a header row (the common export shape), and JSON is read as+# newline-delimited rows — the same format a self-managed S3 JSON table uses. Kept as plain strings+# so this module stays free of the model import.+FILE_FORMAT_TO_TABLE_FORMAT: dict[str, str] = {+ FORMAT_CSV: "CSVWithNames",+ FORMAT_JSON: "JSONEachRow",+ FORMAT_PARQUET: "Parquet",+}++# Cap on uploads streamed through the web pod. Larger datasets belong on a self-managed S3/GCS+# source, where PostHog reads the customer's bucket directly instead of hosting the bytes.+MAX_UPLOAD_SIZE_BYTES = 50 * 1024 * 1024+++def build_file_upload_s3_prefix(team_id: int, upload_id: str) -> str:+ """Folder holding one upload's object, keyed by team then upload id."""+ return f"{FILE_UPLOADS_FOLDER}/team_{team_id}/{upload_id}"+++def build_file_upload_s3_key(team_id: int, upload_id: str, filename: str) -> str:+ """Bucket-relative S3 key for one uploaded file."""+ return f"{build_file_upload_s3_prefix(team_id, upload_id)}/{filename}"+++def build_file_upload_s3_path(team_id: int, upload_id: str, filename: str) -> str:+ """Bucket-qualified ``bucket/key`` path, the form s3fs takes. Use this for every read and write+ of an uploaded file so the upload endpoint and the import pipeline can't drift apart."""+ return f"{settings.DATAWAREHOUSE_BUCKET}/{build_file_upload_s3_key(team_id, upload_id, filename)}"+++def build_file_upload_s3_uri(team_id: int, upload_id: str, filename: str) -> str:+ """Full ``s3://`` URI into the data warehouse bucket for one uploaded file."""+ return f"s3://{build_file_upload_s3_path(team_id, upload_id, filename)}"+++def build_file_upload_url_pattern(team_id: int, upload_id: str, filename: str) -> str:+ """``https://`` URL used as the self-managed table's ``url_pattern``.++ This is the form `DataWarehouseTable.get_columns` builds its ClickHouse s3 table function from.+ The object lives in PostHog's own bucket, so the table carries no credential and reads fall back+ to the node role — never a user-supplied key. Built server-side from the source's own team, so a+ client-supplied ``upload_id`` can only ever resolve inside that team's folder.+ """+ return f"https://{settings.DATAWAREHOUSE_BUCKET_DOMAIN}/{build_file_upload_s3_key(team_id, upload_id, filename)}"diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 79a9bd9fee95..4c3c7e028cc4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -15983,6 +15983,35 @@ export namespace Schemas {uploads: UploadTarget[];}+ /**+ * * `csv` - csv+ * * `json` - json+ * * `parquet` - parquet+ */+ export type CreateTableFromUploadFileFormatEnum = typeof CreateTableFromUploadFileFormatEnum[keyof typeof CreateTableFromUploadFileFormatEnum];+++ export const CreateTableFromUploadFileFormatEnum = {+ Csv: 'csv',+ Json: 'json',+ Parquet: 'parquet',+ } as const;++ export interface CreateTableFromUpload {+ /** Id returned by upload_file for the stored file. */+ upload_id: string;+ /** Sanitized filename returned by upload_file. */+ filename: string;+ /** How the uploaded file is read: 'csv', 'json', or 'parquet'.+ *+ * * `csv` - csv+ * * `json` - json+ * * `parquet` - parquet */+ file_format: CreateTableFromUploadFileFormatEnum;+ /** Name the resulting table is queried by in HogQL. */+ table_name: string;+ }+/*** The PostHog Task created from an observation.*/@@ -31093,6 +31122,17 @@ export namespace Schemas {ordered_ids: string[];}+ export interface FileUploadResponse {+ /** Id of the stored upload. Pass it to create_from_upload to build the table. */+ upload_id: string;+ /** Sanitized name the file was stored under. */+ filename: string;+ /** Format the file will be read as: 'csv', 'json', or 'parquet'. */+ file_format: string;+ /** Size of the stored file in bytes. */+ size_bytes: number;+ }+export interface RunSummary {total: number;changed: number;@@ -80015,6 +80055,25 @@ export namespace Schemas {search?: string;};+ /**+ * How the file will be read when the table is created.+ */+ export type WarehouseTablesUploadFileCreateBodyFileFormat = typeof WarehouseTablesUploadFileCreateBodyFileFormat[keyof typeof WarehouseTablesUploadFileCreateBodyFileFormat];+++ export const WarehouseTablesUploadFileCreateBodyFileFormat = {+ Csv: 'csv',+ Json: 'json',+ Parquet: 'parquet',+ } as const;++ export type WarehouseTablesUploadFileCreateBody = {+ /** The file to upload. */+ file: Blob;+ /** How the file will be read when the table is created. */+ file_format: WarehouseTablesUploadFileCreateBodyFileFormat;+ };+export type WarehouseViewLinkListParams = {/*** Number of results to return per page.