Skip to content

Commit a9d420c

Browse files
author
Test User
committed
Fix: CSV insert with --detect-types crashes on header-only CSV
When using --detect-types with a CSV file containing only a header row (and no data rows), the insert would fail with 'Cannot transform a table that doesn't exist yet' because the table is only created when rows are inserted. This fix adds an existence check before attempting to transform. Fixes #702
1 parent 8d74ffc commit a9d420c

2 files changed

Lines changed: 18 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: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -597,3 +597,19 @@ def try_until(expected):
597597
proc.stdin.close()
598598
proc.wait()
599599
assert proc.returncode == 0
600+
601+
602+
def test_insert_csv_header_only(tmpdir):
603+
# https://github.com/simonw/sqlite-utils/issues/702
604+
# Inserting a CSV with only a header row (no data) and --detect-types
605+
# should not crash
606+
db_path = str(tmpdir / "test.db")
607+
result = CliRunner().invoke(
608+
cli.cli,
609+
["insert", db_path, "data", "-", "--csv", "--detect-types"],
610+
input="foo,bar,baz",
611+
)
612+
assert result.exit_code == 0, result.output
613+
# Table should not exist since no rows were inserted
614+
db = Database(db_path)
615+
assert "data" not in db.table_names()

0 commit comments

Comments
 (0)