Skip to content

Commit fce0eb4

Browse files
author
Test User
committed
Fix issue #702: Handle CSV with only header row in --detect-types
When inserting a CSV file that contains only a header row (no data rows), the --detect-types option would crash with an AssertionError because it tried to transform a table that didn't exist. This fix adds a check to ensure the table exists before attempting to apply type transformations. The fix is applied in two places: 1. insert_upsert_implementation() for the insert command 2. memory() command for CSV/TSV files Added test case: test_insert_csv_headers_only
1 parent 8d74ffc commit fce0eb4

2 files changed

Lines changed: 20 additions & 2 deletions

File tree

sqlite_utils/cli.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1176,7 +1176,7 @@ def insert_upsert_implementation(
11761176
)
11771177
else:
11781178
raise
1179-
if tracker is not None:
1179+
if tracker is not None and db.table(table).exists():
11801180
db.table(table).transform(types=tracker.types)
11811181

11821182
# Clean up open file-like objects
@@ -2033,7 +2033,7 @@ def memory(
20332033
rows = (_flatten(row) for row in rows)
20342034

20352035
db.table(file_table).insert_all(rows, alter=True)
2036-
if tracker is not None:
2036+
if tracker is not None and db.table(file_table).exists():
20372037
db.table(file_table).transform(types=tracker.types)
20382038
# Add convenient t / t1 / t2 views
20392039
view_names = ["t{}".format(i + 1)]

tests/test_cli_insert.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -597,3 +597,21 @@ def try_until(expected):
597597
proc.stdin.close()
598598
proc.wait()
599599
assert proc.returncode == 0
600+
601+
602+
def test_insert_csv_headers_only(tmpdir):
603+
"""Test that CSV with only header row (no data) works with --detect-types (issue #702)"""
604+
db_path = str(tmpdir / "test.db")
605+
csv_path = str(tmpdir / "headers_only.csv")
606+
with open(csv_path, "w") as fp:
607+
fp.write("id,name,age\n")
608+
# Should not crash with --detect-types (which is now the default)
609+
result = CliRunner().invoke(
610+
cli.cli,
611+
["insert", db_path, "data", csv_path, "--csv"],
612+
catch_exceptions=False,
613+
)
614+
assert result.exit_code == 0
615+
# Table should not exist since there were no data rows
616+
db = Database(db_path)
617+
assert not db["data"].exists()

0 commit comments

Comments
 (0)