From 86c5b281c2363ce0c9ea44c228a641b41e701ba3 Mon Sep 17 00:00:00 2001 From: rajvira10 Date: Sat, 5 Dec 2026 00:27:47 +0600 Subject: [PATCH] fix: roll back a failed .import --- CHANGELOG.md | 1 + litecli/packages/special/dbcommands.py | 24 ++++++++++++++---------- tests/test_main.py | 20 ++++++++++++++++++++ 3 files changed, 35 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d91317..9ae6980 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ### Bug Fixes - Expand `~` in configured log file paths before opening the log. +- Roll back a failed `.import` instead of leaving its transaction open. ### Internal diff --git a/litecli/packages/special/dbcommands.py b/litecli/packages/special/dbcommands.py index 5391e8a..ee816bc 100644 --- a/litecli/packages/special/dbcommands.py +++ b/litecli/packages/special/dbcommands.py @@ -321,16 +321,20 @@ def split(s: str) -> list[str]: cur.execute("BEGIN") ninserted, nignored = 0, 0 - for i, row in enumerate(reader): - if len(row) != ncols: - print( - "%s:%d expected %d columns but found %d - ignored" % (filename, i, ncols, len(row)), - file=sys.stderr, - ) - nignored += 1 - continue - cur.execute(insert_tmpl, row) - ninserted += 1 + try: + for i, row in enumerate(reader): + if len(row) != ncols: + print( + "%s:%d expected %d columns but found %d - ignored" % (filename, i, ncols, len(row)), + file=sys.stderr, + ) + nignored += 1 + continue + cur.execute(insert_tmpl, row) + ninserted += 1 + except BaseException: + cur.execute("ROLLBACK") + raise cur.execute("COMMIT") status = "Inserted %d rows into %s" % (ninserted, table) diff --git a/tests/test_main.py b/tests/test_main.py index 21ad5b6..b2801f4 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -265,6 +265,26 @@ def test_import_command(executor): assert expected in "".join(result.output) +@dbtest +def test_import_command_rolls_back_on_error(executor, tmp_path): + data_file = tmp_path / "duplicates.csv" + data_file.write_text("1,a\n1,b\n") + run(executor, "create table tbl1(id integer primary key, name text)") + + with pytest.raises(Exception, match="UNIQUE constraint failed"): + run(executor, f".import {data_file} tbl1") + + # The failed import must not leave its transaction open or keep the + # rows it inserted before the failure. + assert not executor.conn.in_transaction + assert run(executor, "select count(*) from tbl1")[0]["rows"] == [(0,)] + + # A later import can start its own transaction. + data_file.write_text("1,a\n2,b\n") + run(executor, f".import {data_file} tbl1") + assert run(executor, "select * from tbl1")[0]["rows"] == [(1, "a"), (2, "b")] + + def test_startup_commands(executor): m = LiteCli(liteclirc=default_config_file) assert m.startup_commands