Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
24 changes: 14 additions & 10 deletions litecli/packages/special/dbcommands.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
20 changes: 20 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down