diff --git a/sqlite_utils/utils.py b/sqlite_utils/utils.py index 91fd24ddd..0a90f6563 100644 --- a/sqlite_utils/utils.py +++ b/sqlite_utils/utils.py @@ -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 @@ -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. diff --git a/tests/test_rows_from_file.py b/tests/test_rows_from_file.py index a8e7f9d76..179ea3a47 100644 --- a/tests/test_rows_from_file.py +++ b/tests/test_rows_from_file.py @@ -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()