diff --git a/sqlite_utils/cli.py b/sqlite_utils/cli.py index b684662ec..999334ab4 100644 --- a/sqlite_utils/cli.py +++ b/sqlite_utils/cli.py @@ -38,8 +38,10 @@ from .utils import ( Format, OperationalError, + RowError, TypeTracker, _compile_code, + _duplicate_headers, chunks, decode_base64_values, dedupe_keys, @@ -1259,6 +1261,11 @@ def _insert_docs(docs, tracker=None): reader = itertools.chain([first_row], reader) else: headers = first_row + duplicates = _duplicate_headers(headers) + if duplicates: + raise click.ClickException( + "Duplicate column names: {}".format(", ".join(duplicates)) + ) if empty_null: docs = ( dict(zip(headers, [None if cell == "" else cell for cell in row])) @@ -2211,6 +2218,8 @@ def memory( view_name, f"select * from {quote_identifier(file_table)}", ) + except RowError as ex: + raise click.ClickException(str(ex)) finally: if should_close_fp and fp: fp.close() diff --git a/sqlite_utils/utils.py b/sqlite_utils/utils.py index 49c218750..01c47b177 100644 --- a/sqlite_utils/utils.py +++ b/sqlite_utils/utils.py @@ -260,11 +260,32 @@ class RowError(Exception): pass +def _duplicate_headers(headers: Iterable[Any]) -> list[Any]: + seen = set() + duplicates = [] + for header in headers: + if header in seen: + if header not in duplicates: + duplicates.append(header) + else: + seen.add(header) + return duplicates + + def _extra_key_strategy( reader: Iterable[dict[str | None, object]], ignore_extras: bool | None = False, extras_key: str | None = None, ) -> Iterable[Row]: + # DictReader silently keeps only the last value for a duplicate header, + # so reject those instead of losing data + fieldnames = getattr(reader, "fieldnames", None) + if fieldnames: + duplicates = _duplicate_headers(fieldnames) + if duplicates: + raise RowError( + "Duplicate column names: {}".format(", ".join(map(str, duplicates))) + ) # Logic for handling CSV rows with more values than there are headings for row in reader: # DictReader adds a 'None' key with extra row values diff --git a/tests/test_cli_insert.py b/tests/test_cli_insert.py index 35b75e20a..c40a71d1a 100644 --- a/tests/test_cli_insert.py +++ b/tests/test_cli_insert.py @@ -235,6 +235,20 @@ def test_insert_csv_tsv(content, options, db_path, tmpdir): assert [{"foo": "1", "bar": "2", "baz": "cat,dog"}] == list(db.table("data").rows) +@pytest.mark.parametrize("options", (["--csv"], ["--tsv"])) +def test_insert_csv_tsv_rejects_duplicate_headers(options, db_path): + delimiter = "\t" if "--tsv" in options else "," + content = f"name{delimiter}name\ndog{delimiter}cat\n" + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "data", "-"] + options, + input=content.encode("utf-8"), + ) + assert result.exit_code == 1 + assert result.output.strip() == "Error: Duplicate column names: name" + assert not Database(db_path).table("data").exists() + + @pytest.mark.parametrize("fmt_opt", (["--csv"], ["--tsv"])) def test_insert_csv_tsv_preserves_carriage_returns_in_quoted_fields(fmt_opt, db_path): delimiter = "\t" if "--tsv" in fmt_opt else "," diff --git a/tests/test_cli_memory.py b/tests/test_cli_memory.py index 445f50b0f..776811efb 100644 --- a/tests/test_cli_memory.py +++ b/tests/test_cli_memory.py @@ -354,3 +354,14 @@ def test_memory_return_db(tmpdir): db = ctx.invoke(cli.commands["memory"], paths=(path,), return_db=True) assert db.table_names() == ["dogs"] + + +def test_memory_rejects_duplicate_csv_headers(tmpdir): + csv_path = str(tmpdir / "data.csv") + with open(csv_path, "w", encoding="utf-8") as fp: + fp.write("id,id\n1,2\n") + result = CliRunner().invoke( + cli.cli, ["memory", f"{csv_path}:csv", "select * from data"] + ) + assert result.exit_code == 1 + assert result.output.strip() == "Error: Duplicate column names: id" diff --git a/tests/test_rows_from_file.py b/tests/test_rows_from_file.py index b117bc679..580763947 100644 --- a/tests/test_rows_from_file.py +++ b/tests/test_rows_from_file.py @@ -255,3 +255,17 @@ def test_rows_from_file_preserves_carriage_returns_in_quoted_fields( rows, detected_format = rows_from_file(BytesIO(file_bytes), format=expected_format) assert detected_format == expected_format assert list(rows) == expected_rows + + +@pytest.mark.parametrize( + "input,format_used", + ( + (b"id,id\n1,2", Format.CSV), + (b"id\tid\n1\t2", Format.TSV), + ), +) +def test_rows_from_file_rejects_duplicate_headers(input, format_used): + rows, detected_format = rows_from_file(BytesIO(input), format=format_used) + assert detected_format == format_used + with pytest.raises(RowError, match="Duplicate column names: id"): + list(rows)