From 204003f0372a8b4b6fe7b009f09ebe31dc91b7db Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Sun, 29 Nov 2026 13:38:35 -0800 Subject: [PATCH] rows_from_file(): honour ignore_extras= and extras_key= for TSV and auto-detect The TSV branch and the format-detection branch both recursed into the CSV branch without forwarding ignore_extras= or extras_key=, so the inner call used its defaults and raised RowError before the outer _extra_key_strategy() wrapper ever saw the row. Forward both arguments and drop the outer wrappers, which were dead code, so extras are handled exactly once on the shared CSV path. Tests now cover explicit CSV, explicit TSV and auto-detected CSV/TSV with the default, ignore_extras=True and extras_key=, plus the both-options ValueError and the no-op behaviour for JSON/NL. Refs #892 Co-Authored-By: Claude Opus 5.5 --- sqlite_utils/utils.py | 32 ++++++------ tests/test_rows_from_file.py | 96 ++++++++++++++++++++++++++++++++++++ 2 files changed, 110 insertions(+), 18 deletions(-) diff --git a/sqlite_utils/utils.py b/sqlite_utils/utils.py index a0b386b16..49c218750 100644 --- a/sqlite_utils/utils.py +++ b/sqlite_utils/utils.py @@ -359,16 +359,14 @@ class Format(enum.Enum): return _CloseableIterator(iter(rows), decoded_fp), Format.CSV elif format == Format.TSV: rows, _ = rows_from_file( - fp, format=Format.CSV, dialect=csv.excel_tab, encoding=encoding - ) - return ( - _extra_key_strategy( - cast(Iterable[dict[str | None, object]], rows), - ignore_extras, - extras_key, - ), - Format.TSV, + fp, + format=Format.CSV, + dialect=csv.excel_tab, + encoding=encoding, + ignore_extras=ignore_extras, + extras_key=extras_key, ) + return rows, Format.TSV elif format is None: # Detect the format, then call this recursively buffered = io.BufferedReader(cast(io.RawIOBase, fp), buffer_size=4096) @@ -393,18 +391,16 @@ class Format(enum.Enum): first_bytes.decode(encoding or "utf-8-sig", "ignore") ) rows, _ = rows_from_file( - buffered, format=Format.CSV, dialect=dialect, encoding=encoding + buffered, + format=Format.CSV, + dialect=dialect, + encoding=encoding, + ignore_extras=ignore_extras, + extras_key=extras_key, ) # Make sure we return the format we detected detected_format = Format.TSV if dialect.delimiter == "\t" else Format.CSV - return ( - _extra_key_strategy( - cast(Iterable[dict[str | None, object]], rows), - ignore_extras, - extras_key, - ), - detected_format, - ) + return rows, detected_format else: raise RowsFromFileError("Bad format") diff --git a/tests/test_rows_from_file.py b/tests/test_rows_from_file.py index 094a75c40..b117bc679 100644 --- a/tests/test_rows_from_file.py +++ b/tests/test_rows_from_file.py @@ -57,6 +57,102 @@ def test_rows_from_file_extra_fields_strategies(ignore_extras, extras_key, expec assert list_rows == expected +def _ragged_file(delimiter): + # One row has an extra value. Enough regular rows follow it that + # csv.Sniffer still detects the delimiter when the format is omitted. + lines = ["id{d}value", "1{d}10{d}oops"] + lines.extend(f"{i}{{d}}{i * 10}" for i in range(2, 30)) + return "".join(line.format(d=delimiter) + "\n" for line in lines).encode() + + +_REGULAR_ROWS = [{"id": str(i), "value": str(i * 10)} for i in range(2, 30)] + + +@pytest.mark.parametrize( + "delimiter,format,expected_format", + ( + (",", Format.CSV, Format.CSV), + ("\t", Format.TSV, Format.TSV), + (",", None, Format.CSV), + ("\t", None, Format.TSV), + ), +) +@pytest.mark.parametrize( + "ignore_extras,extras_key,expected_first_row", + ( + (True, None, {"id": "1", "value": "10"}), + (False, "_rest", {"id": "1", "value": "10", "_rest": ["oops"]}), + # expected_first_row of None means expect an error: + (False, None, None), + ), +) +def test_rows_from_file_extra_fields_strategies_all_formats( + delimiter, + format, + expected_format, + ignore_extras, + extras_key, + expected_first_row, +): + rows, format_used = rows_from_file( + BytesIO(_ragged_file(delimiter)), + format=format, + ignore_extras=ignore_extras, + extras_key=extras_key, + ) + assert format_used == expected_format + if expected_first_row is None: + with pytest.raises(RowError) as ex: + list(rows) + assert ex.value.args == ( + "Row {'id': '1', 'value': '10'} contained these extra values: ['oops']", + ) + else: + assert list(rows) == [expected_first_row] + _REGULAR_ROWS + + +@pytest.mark.parametrize( + "input,format", + ( + (b"id,name\n1,Cleo", Format.CSV), + (b"id\tname\n1\tCleo", Format.TSV), + (b"id,name\n1,Cleo", None), + (b'[{"id": "1"}]', Format.JSON), + (b'{"id": "1"}\n', Format.NL), + ), +) +def test_rows_from_file_ignore_extras_and_extras_key_together(input, format): + with pytest.raises(ValueError) as ex: + rows_from_file( + BytesIO(input), format=format, ignore_extras=True, extras_key="_rest" + ) + assert ex.value.args == ("Cannot use ignore_extras= and extras_key= together",) + + +@pytest.mark.parametrize( + "input,format", + ( + (b'[{"id": "1", "name": "Cleo"}]', Format.JSON), + (b'[{"id": "1", "name": "Cleo"}]', None), + (b'{"id": "1", "name": "Cleo"}\n', Format.NL), + ), +) +@pytest.mark.parametrize( + "ignore_extras,extras_key", ((True, None), (False, "_rest"), (False, None)) +) +def test_rows_from_file_extra_fields_options_ignored_for_json( + input, format, ignore_extras, extras_key +): + # JSON objects have no header row, so there are no extra values to handle + rows, _ = rows_from_file( + BytesIO(input), + format=format, + ignore_extras=ignore_extras, + extras_key=extras_key, + ) + assert list(rows) == [{"id": "1", "name": "Cleo"}] + + def test_rows_from_file_error_on_string_io(): with pytest.raises(TypeError) as ex: rows_from_file(StringIO("id,name\r\n1,Cleo")) # type: ignore[arg-type]