diff --git a/docs/python-api.rst b/docs/python-api.rst index ac2b0d0ac..78f73f2cc 100644 --- a/docs/python-api.rst +++ b/docs/python-api.rst @@ -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:: diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index 6761817f9..ce0866c8f 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -4937,6 +4937,8 @@ def insert_all( try: first_record = next(records_iter) except StopIteration: + if truncate: + return self.delete_where() return self # It was an empty list # Check if this is list mode or dict mode @@ -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 diff --git a/tests/test_cli_insert.py b/tests/test_cli_insert.py index cc4af3ac6..922750a80 100644 --- a/tests/test_cli_insert.py +++ b/tests/test_cli_insert.py @@ -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, diff --git a/tests/test_create.py b/tests/test_create.py index 42448ebc9..fcd9eee34 100644 --- a/tests/test_create.py +++ b/tests/test_create.py @@ -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")