Skip to content
Open
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
4 changes: 3 additions & 1 deletion sqlite_utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def __iter__(self) -> "_CloseableIterator":
def __next__(self) -> Row:
try:
return next(self._iterator)
except StopIteration:
except BaseException:
self._closeable.close()
raise

Expand Down Expand Up @@ -319,6 +319,8 @@ class Format(enum.Enum):
JSON = 3
NL = 4

CSV/TSV streams are closed when iteration finishes or raises an exception.

If a CSV or TSV file includes rows with more fields than are declared in the header a
``sqlite_utils.utils.RowError`` exception will be raised when you loop over the generator.

Expand Down
19 changes: 19 additions & 0 deletions tests/test_rows_from_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,22 @@ def test_detect_format_keeps_streaming_reader_open(
assert not buffered_readers[0].closed
assert len(list(rows)) == 2000
assert buffered_readers[0].closed


@pytest.mark.parametrize(
"content,expected_error",
[(b"name\nCleo,extra\n", RowError), (b"name\n\xff\n", UnicodeDecodeError)],
)
def test_csv_reader_closes_on_error(tmp_path, content, expected_error):
path = tmp_path / "input.csv"
path.write_bytes(content)
fp = path.open("rb")
try:
rows, detected = rows_from_file(fp, format=Format.CSV)
assert detected is Format.CSV
assert not fp.closed
with pytest.raises(expected_error):
next(iter(rows))
assert fp.closed
finally:
fp.close()
Loading