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
9 changes: 9 additions & 0 deletions sqlite_utils/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,10 @@
from .utils import (
Format,
OperationalError,
RowError,
TypeTracker,
_compile_code,
_duplicate_headers,
chunks,
decode_base64_values,
dedupe_keys,
Expand Down Expand Up @@ -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]))
Expand Down Expand Up @@ -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()
Expand Down
21 changes: 21 additions & 0 deletions sqlite_utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions tests/test_cli_insert.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ","
Expand Down
11 changes: 11 additions & 0 deletions tests/test_cli_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
14 changes: 14 additions & 0 deletions tests/test_rows_from_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Loading