Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 14 additions & 18 deletions sqlite_utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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")

Expand Down
96 changes: 96 additions & 0 deletions tests/test_rows_from_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Loading