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.

fix(data-warehouse): name the csv quote setting that actually parses (#102043)

Tom Owers2f205a517ce2
diff --git a/products/data_warehouse/backend/models/test/test_table.py b/products/data_warehouse/backend/models/test/test_table.py
index 0fbb447716e7..bbfffee39cd8 100644
--- a/products/data_warehouse/backend/models/test/test_table.py
+++ b/products/data_warehouse/backend/models/test/test_table.py
@@ -872,7 +872,83 @@ class TestTable(BaseTest):
"products.warehouse_sources.backend.models.table.sync_execute",
side_effect=ServerException("Expected end of line", code=code),
):
- with pytest.raises(Exception, match="CSV parsing failed"):
+ with pytest.raises(Exception, match="didn't parse with either quote setting"):
+ table._validate_csv_double_quotes_setting()
+
+ @parameterized.expand(
+ [
+ (True, "Literal quotes"),
+ (False, "RFC 4180 double quotes"),
+ ]
+ )
+ def test_validate_csv_double_quotes_names_the_setting_that_parses(self, selected, expected_label):
+ from clickhouse_driver.errors import ServerException
+
+ credential = DataWarehouseCredential.objects.create(access_key="key", access_secret="secret", team=self.team)
+ table = DataWarehouseTable.objects.create(
+ name="test_csv",
+ url_pattern="https://example.com/test.csv",
+ credential=credential,
+ format=DataWarehouseTable.TableFormat.CSVWithNames,
+ options={"csv_allow_double_quotes": selected},
+ team=self.team,
+ )
+
+ with patch(
+ "products.warehouse_sources.backend.models.table.sync_execute",
+ side_effect=[ServerException("Expected end of line", code=117), None],
+ ):
+ with pytest.raises(Exception, match=f"Set CSV quote handling to '{expected_label}'"):
+ table._validate_csv_double_quotes_setting()
+
+ @parameterized.expand(
+ [
+ (
+ "Cannot extract table structure from CSV format file, because there are no files with "
+ "provided path in S3 or all files are empty",
+ "doesn't exist in the bucket",
+ ),
+ ("Cannot extract table structure: the file is empty", "contains no data"),
+ ]
+ )
+ def test_validate_csv_double_quotes_does_not_blame_quoting_for_missing_data(self, message, expected):
+ from clickhouse_driver.errors import ServerException
+
+ credential = DataWarehouseCredential.objects.create(access_key="key", access_secret="secret", team=self.team)
+ table = DataWarehouseTable.objects.create(
+ name="test_csv",
+ url_pattern="https://example.com/test.csv",
+ credential=credential,
+ format=DataWarehouseTable.TableFormat.CSVWithNames,
+ options={"csv_allow_double_quotes": True},
+ team=self.team,
+ )
+
+ with patch(
+ "products.warehouse_sources.backend.models.table.sync_execute",
+ side_effect=ServerException(message, code=636),
+ ):
+ with pytest.raises(Exception, match=expected):
+ table._validate_csv_double_quotes_setting()
+
+ def test_validate_csv_double_quotes_reraises_a_non_parse_error(self):
+ from clickhouse_driver.errors import ServerException
+
+ credential = DataWarehouseCredential.objects.create(access_key="key", access_secret="secret", team=self.team)
+ table = DataWarehouseTable.objects.create(
+ name="test_csv",
+ url_pattern="https://example.com/test.csv",
+ credential=credential,
+ format=DataWarehouseTable.TableFormat.CSVWithNames,
+ options={"csv_allow_double_quotes": True},
+ team=self.team,
+ )
+
+ with patch(
+ "products.warehouse_sources.backend.models.table.sync_execute",
+ side_effect=ServerException("Access Denied", code=499),
+ ):
+ with pytest.raises(ServerException):
table._validate_csv_double_quotes_setting()
@parameterized.expand(
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/components/SelfManagedSourceForm.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/components/SelfManagedSourceForm.tsx
index 3a10ff90e346..cda904cd0096 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/components/SelfManagedSourceForm.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/components/SelfManagedSourceForm.tsx
@@ -140,8 +140,7 @@ export function SelfManagedSourceForm({ onUpdate }: Props): JSX.Element {
</LemonField>
<div className="mb-4 text-xs text-secondary">
Pick RFC 4180 if your CSV wraps values in double quotes (the usual way to keep commas inside
- a field). If import fails with a column count mismatch, switching to RFC 4180 usually fixes
- it.
+ a field). If the file doesn't parse, the error says what to change.
</div>
</>
)}
diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.py
index d925e2a76317..dc6aeb951caf 100644
--- a/products/warehouse_sources/backend/models/table.py
+++ b/products/warehouse_sources/backend/models/table.py
@@ -1107,10 +1107,44 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
}
)
+ # Code 636 also comes back when the path matches no file, or every file is empty, which no
+ # quote setting can fix. `_safe_expose_ch_error` already carries the copy for both.
+ _CSV_NO_DATA_ERRORS = ("there are no files with provided path", "file is empty")
+
+ def _csv_parses_with_double_quotes(self, allow_double_quotes: bool) -> bool:
+ """Read a few rows under one quote setting. False when the rows don't parse; any other
+ failure (credentials, a missing file) is raised for the caller to surface as-is."""
+ ctx = HogQLContext(team_id=self.team.pk)
+ func = build_function_call(
+ url=self.url_pattern,
+ queryable_folder=self.queryable_folder,
+ format=self.format,
+ access_key=self.credential.access_key if self.credential else None,
+ access_secret=self.credential.access_secret if self.credential else None,
+ context=ctx,
+ table_size_mib=0,
+ )
+ try:
+ sync_execute(
+ f"SELECT 1 FROM {func} LIMIT 100",
+ args=ctx.values,
+ settings={
+ **DISABLE_HIVE_PARTITIONING_SETTINGS,
+ "format_csv_allow_double_quotes": 1 if allow_double_quotes else 0,
+ },
+ )
+ except ClickHouseServerException as e:
+ if any(needle in e.message for needle in self._CSV_NO_DATA_ERRORS):
+ self._safe_expose_ch_error(e)
+ if e.code in self._CSV_PARSE_ERROR_CODES:
+ return False
+ raise
+ return True
+
def _validate_csv_double_quotes_setting(self) -> None:
"""Validate the user-chosen csv_allow_double_quotes setting by trying to parse data rows.
Raises Exception with a helpful message if parsing fails."""
- setting = self.csv_allow_double_quotes
+ setting = bool(self.csv_allow_double_quotes)
tag_queries(
team_id=self.team.pk,
table_id=self.id,
@@ -1119,29 +1153,21 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
product=Product.WAREHOUSE,
feature=Feature.QUERY,
)
- try:
- ctx = HogQLContext(team_id=self.team.pk)
- func = build_function_call(
- url=self.url_pattern,
- queryable_folder=self.queryable_folder,
- format=self.format,
- access_key=self.credential.access_key if self.credential else None,
- access_secret=self.credential.access_secret if self.credential else None,
- context=ctx,
- table_size_mib=0,
- )
- sync_execute(
- f"SELECT 1 FROM {func} LIMIT 100",
- args=ctx.values,
- settings={**DISABLE_HIVE_PARTITIONING_SETTINGS, "format_csv_allow_double_quotes": 1 if setting else 0},
+ if self._csv_parses_with_double_quotes(setting):
+ return
+
+ # Naming the other setting is only useful when it actually parses the file. When neither
+ # does, the same advice sends the user toggling between two failing options.
+ if self._csv_parses_with_double_quotes(not setting):
+ other_label = "Literal quotes" if setting else "RFC 4180 double quotes"
+ raise Exception(
+ "Your CSV didn't parse with the quote setting you picked. "
+ f"Set CSV quote handling to '{other_label}', then save again."
)
- except ClickHouseServerException as e:
- if e.code in self._CSV_PARSE_ERROR_CODES:
- other_label = "Literal quotes" if setting else "RFC 4180 double quotes"
- raise Exception(
- f"CSV parsing failed with the selected quote setting. Try selecting '{other_label}' instead."
- )
- raise
+ raise Exception(
+ "Your CSV didn't parse with either quote setting. Check that the file is comma-separated "
+ "and that every row has the same number of values."
+ )
def _safe_expose_ch_error(self, err):
# Match ExtractErrors against the raw ClickHouse message: wrap_clickhouse_query_error may