From cf384192c427518a3976d39a7ecc039fffadc97c Mon Sep 17 00:00:00 2001 From: Shamil Habeeb Date: Tue, 1 Dec 2026 11:20:22 +0530 Subject: [PATCH 1/4] Add tests for insert and upsert --summary (refs #516) --- tests/test_cli_insert.py | 57 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/tests/test_cli_insert.py b/tests/test_cli_insert.py index 35b75e20a..458345aa4 100644 --- a/tests/test_cli_insert.py +++ b/tests/test_cli_insert.py @@ -928,3 +928,60 @@ def test_insert_code_file_not_found(tmpdir): ) assert result.exit_code == 1 assert "File not found: missing.py" in result.output + + +@pytest.mark.parametrize( + "extra_args,expected", + ( + ([], "2 rows inserted"), + (["--ignore"], "1 row inserted, 1 ignored"), + (["--replace"], "1 row inserted, 1 replaced"), + ), +) +def test_insert_summary(tmpdir, extra_args, expected): + db_path = str(tmpdir / "data.db") + db = Database(db_path) + db["t"].insert({"id": 1, "name": "old"}, pk="id") + new_rows = [{"id": 1, "name": "new"}, {"id": 2, "name": "two"}] + if not extra_args: + new_rows = [{"id": 5, "name": "five"}, {"id": 6, "name": "six"}] + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "t", "-", "--pk", "id", "--summary"] + extra_args, + input=json.dumps(new_rows), + ) + assert result.exit_code == 0, result.output + assert result.output.strip() == expected + + +def test_insert_without_summary_prints_nothing(tmpdir): + db_path = str(tmpdir / "data.db") + result = CliRunner().invoke( + cli.cli, ["insert", db_path, "t", "-"], input='[{"a": 1}]' + ) + assert result.exit_code == 0 + assert result.output == "" + + +def test_upsert_summary(tmpdir): + db_path = str(tmpdir / "data.db") + Database(db_path)["t"].insert({"id": 1, "name": "old"}, pk="id") + result = CliRunner().invoke( + cli.cli, + ["upsert", db_path, "t", "-", "--pk", "id", "--summary"], + input=json.dumps([{"id": 1, "name": "new"}, {"id": 2, "name": "two"}]), + ) + assert result.exit_code == 0 + assert result.output.strip() == "1 row inserted, 1 updated" + + +def test_insert_summary_with_truncate_and_csv(tmpdir): + db_path = str(tmpdir / "data.db") + Database(db_path)["t"].insert_all([{"id": i} for i in range(5)], pk="id") + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "t", "-", "--csv", "--pk", "id", "--truncate", "--summary"], + input="id\n1\n2\n", + ) + assert result.exit_code == 0 + assert result.output.strip() == "2 rows inserted" From e1cf49de421ab767079634cb106a41c04e6313b1 Mon Sep 17 00:00:00 2001 From: Shamil Habeeb Date: Tue, 1 Dec 2026 11:21:13 +0530 Subject: [PATCH 2/4] Add --summary option to insert and upsert (refs #516) --- sqlite_utils/cli.py | 51 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/sqlite_utils/cli.py b/sqlite_utils/cli.py index b684662ec..1d8b16988 100644 --- a/sqlite_utils/cli.py +++ b/sqlite_utils/cli.py @@ -1044,6 +1044,11 @@ def inner(fn): ), load_extension_option, click.option("--silent", is_flag=True, help="Do not show progress bar"), + click.option( + "--summary", + is_flag=True, + help="Write a summary of rows inserted, ignored, replaced or updated to standard error", + ), click.option( "--strict", is_flag=True, @@ -1058,6 +1063,21 @@ def inner(fn): return inner +def _insert_summary(total, added, *, ignore, replace, upsert): + """Describe the outcome of an insert or upsert for --summary""" + # Rows that did not add to the table were ignored, replaced or updated + added = max(added, 0) + existing = max(total - added, 0) + parts = [f"{added} {'row' if added == 1 else 'rows'} inserted"] + if ignore: + parts.append(f"{existing} ignored") + elif replace: + parts.append(f"{existing} replaced") + elif upsert: + parts.append(f"{existing} updated") + return ", ".join(parts) + + def insert_upsert_implementation( path, table, @@ -1091,6 +1111,7 @@ def insert_upsert_implementation( analyze=False, load_extension=None, silent=False, + summary=False, bulk_sql=None, functions=None, strict=False, @@ -1122,6 +1143,17 @@ def _insert_docs(docs, tracker=None): # docs should all be dictionaries docs = (verify_is_dict(doc) for doc in docs) + # Count the rows we were given, for --summary + input_count = [0] + + def _count(docs_iter): + for doc in docs_iter: + input_count[0] += 1 + yield doc + + if summary and not bulk_sql: + docs = _count(docs) + # Apply {"$base64": true, ...} decoding, if needed docs = (decode_base64_values(doc) for doc in docs) @@ -1139,6 +1171,9 @@ def _insert_docs(docs, tracker=None): # table_names() rather than db.table(), which raises NoTable for # views before the error handling below can deal with them table_existed_before_insert = table in db.table_names() + rows_before = 0 + if summary and table_existed_before_insert and not truncate: + rows_before = db.table(table).count try: db.table(table).insert_all( docs, pk=pk, batch_size=batch_size, alter=alter, **extra_kwargs @@ -1177,6 +1212,18 @@ def _insert_docs(docs, tracker=None): detected_types = tracker.types detected_types.update(column_type_overrides) db.table(table).transform(types=detected_types) + if summary: + rows_after = db.table(table).count if db.table(table).exists() else 0 + click.echo( + _insert_summary( + input_count[0], + rows_after - rows_before, + ignore=ignore, + replace=replace, + upsert=bool(upsert), + ), + err=True, + ) if code is not None: if file is not None: @@ -1382,6 +1429,7 @@ def insert( analyze, load_extension, silent, + summary, ignore, replace, truncate, @@ -1479,6 +1527,7 @@ def rows(): analyze=analyze, load_extension=load_extension, silent=silent, + summary=summary, not_null=not_null, default=default, types=types, @@ -1521,6 +1570,7 @@ def upsert( analyze, load_extension, silent, + summary, strict, ): """ @@ -1572,6 +1622,7 @@ def upsert( analyze=analyze, load_extension=load_extension, silent=silent, + summary=summary, strict=strict, code=code, ) From 5c356c5591deb8a241cfda0b7b7e8997de23b733 Mon Sep 17 00:00:00 2001 From: Shamil Habeeb Date: Tue, 1 Dec 2026 11:21:53 +0530 Subject: [PATCH 3/4] Document insert --summary (refs #516) --- docs/cli.rst | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/cli.rst b/docs/cli.rst index 78c33b8ae..96adee513 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -1197,6 +1197,18 @@ You can delete all the existing rows in the table before inserting the new recor You can add the ``--analyze`` option to run ``ANALYZE`` against the table after the rows have been inserted. +Add ``--summary`` to write a one-line count of what happened to standard error. It reports how many rows were added to the table, and with ``--ignore`` how many input rows were skipped (``--replace`` reports replaced rows, and ``upsert`` reports updated rows): + +.. code-block:: bash + + sqlite-utils insert dogs.db dogs dogs.json --pk=id --ignore --summary + +:: + + 1 row inserted, 1 ignored + +The summary works for file and standard input alike, and is written to standard error so it does not mix with other output. + .. note:: In Python: :ref:`table.insert_all() ` CLI reference: :ref:`sqlite-utils insert ` From 13fcfa356ac464219fc7199ddf0f8cba5e9bbbe4 Mon Sep 17 00:00:00 2001 From: Shamil Habeeb Date: Tue, 1 Dec 2026 11:22:22 +0530 Subject: [PATCH 4/4] Update CLI reference for --summary (refs #516) --- docs/cli-reference.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/cli-reference.rst b/docs/cli-reference.rst index c53d64222..913c5c7a5 100644 --- a/docs/cli-reference.rst +++ b/docs/cli-reference.rst @@ -315,6 +315,8 @@ See :ref:`cli_inserting_data`, :ref:`cli_insert_csv_tsv`, :ref:`cli_insert_unstr --analyze Run ANALYZE at the end of this operation --load-extension TEXT Path to SQLite extension, with optional :entrypoint --silent Do not show progress bar + --summary Write a summary of rows inserted, ignored, replaced + or updated to standard error --strict Apply STRICT mode to created table --ignore Ignore records if pk already exists --replace Replace records if pk already exists @@ -379,6 +381,8 @@ See :ref:`cli_upsert`. --analyze Run ANALYZE at the end of this operation --load-extension TEXT Path to SQLite extension, with optional :entrypoint --silent Do not show progress bar + --summary Write a summary of rows inserted, ignored, replaced + or updated to standard error --strict Apply STRICT mode to created table -h, --help Show this message and exit.