Skip to content
Merged
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
2 changes: 2 additions & 0 deletions docs/python-api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1105,6 +1105,8 @@ You can skip inserting any records that have a primary key that already exists u

You can delete all the existing rows in the table before inserting the new records using ``truncate=True``. This is useful if you want to replace the data in the table.

An empty iterable, or a list or tuple iterator containing only column names, will also delete all existing rows when ``truncate=True``.

Pass ``analyze=True`` to run ``ANALYZE`` against the table after inserting the new records.

.. note::
Expand Down
4 changes: 4 additions & 0 deletions sqlite_utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -4937,6 +4937,8 @@ def insert_all(
try:
first_record = next(records_iter)
except StopIteration:
if truncate:
return self.delete_where()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

insert_all([], truncate=True, analyze=True) (and --truncate --analyze) skips the ANALYZE, so on a 50 row table sqlite_stat1 still says 50 10 after the delete, while truncating to one row updates it. self.delete_where(analyze=analyze) here and on line 4802 clears it, and the test suite still passes.

return self # It was an empty list

# Check if this is list mode or dict mode
Expand All @@ -4954,6 +4956,8 @@ def insert_all(
try:
first_record = next(records_iter)
except StopIteration:
if truncate:
return self.delete_where()
return self # Only headers, no data
if not isinstance(first_record, (list, tuple)):
raise ValueError( # noqa: TRY004
Expand Down
22 changes: 22 additions & 0 deletions tests/test_cli_insert.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,28 @@ def test_insert_truncate(db_path):
] == list(db.query("select foo, n from from_json_nl"))


@pytest.mark.parametrize(
"input, options",
(("[]", []), ("id,name\n", ["--csv"]), ("id\tname\n", ["--tsv"]), ("", ["--nl"])),
)
def test_insert_truncate_empty(tmp_path, input, options):
db_path = str(tmp_path / "items.db")
db = Database(db_path)
table = db.table("items").insert({"id": 1, "name": "old"}, pk="id")
table.create_index(["name"])
schema, indexes = table.schema, table.indexes
db.close()

result = CliRunner().invoke(
cli.cli, ["insert", db_path, "items", "-", "--truncate"] + options, input=input
)
assert result.exit_code == 0, result.output
with Database(db_path) as reopened:
assert list(reopened.table("items").rows) == []
assert reopened.table("items").schema == schema
assert reopened.table("items").indexes == indexes


def test_insert_alter(db_path, tmpdir):
result = CliRunner().invoke(
cli.cli,
Expand Down
44 changes: 44 additions & 0 deletions tests/test_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -1303,6 +1303,50 @@ def test_insert_all_empty_list(fresh_db):
assert fresh_db.table("t").count == 1


@pytest.mark.parametrize("records", ([], iter(()), [["id", "name"]], [("id", "name")]))
@pytest.mark.parametrize("truncate", (False, True))
def test_insert_all_empty_truncate(tmp_path, records, truncate):
db_path = tmp_path / "items.db"
db = Database(db_path)
table = db.table("items").insert({"id": 1, "name": "old"}, pk="id")
table.create_index(["name"])
schema, indexes = table.schema, table.indexes

assert table.insert_all(records, truncate=truncate) is table
assert table.schema == schema
assert table.indexes == indexes
db.close()
with Database(db_path) as reopened:
assert list(reopened["items"].rows) == (
[] if truncate else [{"id": 1, "name": "old"}]
)


@pytest.mark.parametrize("records", ([], iter(()), [["id", "name"]]))
def test_insert_all_empty_truncate_missing_table(tmp_path, records):
db = Database(tmp_path / "items.db")
table = db.table("items")
assert table.insert_all(records, truncate=True) is table
assert not table.exists()


@pytest.mark.parametrize(
"records, error",
(
(None, TypeError),
([None], AttributeError),
([[1]], ValueError),
([["id"], None], ValueError),
),
)
def test_insert_all_truncate_invalid_input(tmp_path, records, error):
db = Database(tmp_path / "items.db")
table = db.table("items").insert({"id": 1, "name": "old"}, pk="id")
with pytest.raises(error):
table.insert_all(records, truncate=True)
assert list(table.rows) == [{"id": 1, "name": "old"}]


def test_insert_all_single_column(fresh_db):
table = fresh_db.table("table")
table.insert_all([{"name": "Cleo"}], pk="name")
Expand Down