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
4 changes: 4 additions & 0 deletions docs/cli-reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down
12 changes: 12 additions & 0 deletions docs/cli.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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() <python_api_bulk_inserts>` CLI reference: :ref:`sqlite-utils insert <cli_ref_insert>`

Expand Down
51 changes: 51 additions & 0 deletions sqlite_utils/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -1091,6 +1111,7 @@ def insert_upsert_implementation(
analyze=False,
load_extension=None,
silent=False,
summary=False,
bulk_sql=None,
functions=None,
strict=False,
Expand Down Expand Up @@ -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)

Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -1382,6 +1429,7 @@ def insert(
analyze,
load_extension,
silent,
summary,
ignore,
replace,
truncate,
Expand Down Expand Up @@ -1479,6 +1527,7 @@ def rows():
analyze=analyze,
load_extension=load_extension,
silent=silent,
summary=summary,
not_null=not_null,
default=default,
types=types,
Expand Down Expand Up @@ -1521,6 +1570,7 @@ def upsert(
analyze,
load_extension,
silent,
summary,
strict,
):
"""
Expand Down Expand Up @@ -1572,6 +1622,7 @@ def upsert(
analyze=analyze,
load_extension=load_extension,
silent=silent,
summary=summary,
strict=strict,
code=code,
)
Expand Down
57 changes: 57 additions & 0 deletions tests/test_cli_insert.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Loading