From 2b0cc04c8def113d176cbc95630b665bdb05d6d9 Mon Sep 17 00:00:00 2001 From: Rami Abdelrazzaq Date: Sun, 21 Jun 2026 17:57:06 -0500 Subject: [PATCH] Fix issue #702: Handle CSV with only header row in --detect-types (#707) 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 Co-authored-by: Test User --- sqlite_utils/cli.py | 4 ++-- tests/test_cli_insert.py | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/sqlite_utils/cli.py b/sqlite_utils/cli.py index 1c3ce8d..2f6268f 100644 --- a/sqlite_utils/cli.py +++ b/sqlite_utils/cli.py @@ -1177,7 +1177,7 @@ def insert_upsert_implementation( ) else: raise - if tracker is not None: + if tracker is not None and db.table(table).exists(): db.table(table).transform(types=tracker.types) # Clean up open file-like objects @@ -2034,7 +2034,7 @@ def memory( rows = (_flatten(row) for row in rows) db.table(file_table).insert_all(rows, alter=True) - if tracker is not None: + if tracker is not None and db.table(file_table).exists(): db.table(file_table).transform(types=tracker.types) # Add convenient t / t1 / t2 views view_names = ["t{}".format(i + 1)] diff --git a/tests/test_cli_insert.py b/tests/test_cli_insert.py index 9f21b00..5812851 100644 --- a/tests/test_cli_insert.py +++ b/tests/test_cli_insert.py @@ -597,3 +597,21 @@ def test_insert_streaming_batch_size_1(db_path): proc.stdin.close() proc.wait() assert proc.returncode == 0 + + +def test_insert_csv_headers_only(tmpdir): + """Test that CSV with only header row (no data) works with --detect-types (issue #702)""" + db_path = str(tmpdir / "test.db") + csv_path = str(tmpdir / "headers_only.csv") + with open(csv_path, "w") as fp: + fp.write("id,name,age\n") + # Should not crash with --detect-types (which is now the default) + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "data", csv_path, "--csv"], + catch_exceptions=False, + ) + assert result.exit_code == 0 + # Table should not exist since there were no data rows + db = Database(db_path) + assert not db["data"].exists()