From a9d420c949977b430e5e9912693ced22bbfa1d52 Mon Sep 17 00:00:00 2001 From: Test User Date: Sun, 8 Feb 2026 17:09:13 -0600 Subject: [PATCH] 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 --- sqlite_utils/cli.py | 4 ++-- tests/test_cli_insert.py | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/sqlite_utils/cli.py b/sqlite_utils/cli.py index 9b9ee20e7..1add5aa4f 100644 --- a/sqlite_utils/cli.py +++ b/sqlite_utils/cli.py @@ -1176,7 +1176,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 @@ -2033,7 +2033,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 9f21b0010..09c64e4da 100644 --- a/tests/test_cli_insert.py +++ b/tests/test_cli_insert.py @@ -597,3 +597,19 @@ def try_until(expected): proc.stdin.close() proc.wait() assert proc.returncode == 0 + + +def test_insert_csv_header_only(tmpdir): + # https://github.com/simonw/sqlite-utils/issues/702 + # Inserting a CSV with only a header row (no data) and --detect-types + # should not crash + db_path = str(tmpdir / "test.db") + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "data", "-", "--csv", "--detect-types"], + input="foo,bar,baz", + ) + assert result.exit_code == 0, result.output + # Table should not exist since no rows were inserted + db = Database(db_path) + assert "data" not in db.table_names()