diff --git a/docs/cli.rst b/docs/cli.rst index 78c33b8ae..c849c2865 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -1195,6 +1195,8 @@ You can delete all the existing rows in the table before inserting the new recor sqlite-utils insert dogs.db dogs dogs.json --truncate +An empty JSON array (``[]``) is a valid empty snapshot and clears the existing table when used with ``--truncate``. A top-level scalar such as an empty string (``""``) or ``null`` is not a snapshot and is rejected before truncation. + You can add the ``--analyze`` option to run ``ANALYZE`` against the table after the rows have been inserted. .. note:: diff --git a/sqlite_utils/cli.py b/sqlite_utils/cli.py index b684662ec..f347d7ce0 100644 --- a/sqlite_utils/cli.py +++ b/sqlite_utils/cli.py @@ -1282,6 +1282,10 @@ def _insert_docs(docs, tracker=None): docs = json.load(decoded) if isinstance(docs, dict): docs = [docs] + elif not isinstance(docs, list): + raise click.ClickException( + "JSON input must be an object or an array" + ) except json.decoder.JSONDecodeError as ex: raise click.ClickException( f"Invalid JSON - use --csv for CSV or --tsv for TSV files\n\nJSON error: {ex}" diff --git a/tests/test_cli_insert.py b/tests/test_cli_insert.py index 35b75e20a..6d8141138 100644 --- a/tests/test_cli_insert.py +++ b/tests/test_cli_insert.py @@ -391,6 +391,49 @@ def test_insert_truncate_empty(tmp_path, input, options): assert reopened.table("items").indexes == indexes +@pytest.mark.parametrize( + "payload,options", + ( + ('""', []), + ('""', ["--flatten"]), + ('"not a row"', []), + ("null", []), + ("false", []), + ("42", []), + ), +) +def test_insert_truncate_rejects_scalar_json(db_path, payload, options): + with Database(db_path) as db: + table = db.table("items").insert({"id": 1, "name": "old"}, pk="id") + table.create_index(["name"]) + schema, indexes = table.schema, table.indexes + args = ["insert", db_path, "items", "-", "--truncate"] + options + runner = CliRunner() + result = runner.invoke(cli.cli, args, input=payload) + assert result.exit_code == 1, result.output + assert result.output == "Error: JSON input must be an object or an array\n" + with Database(db_path) as db: + table = db.table("items") + assert list(table.rows) == [{"id": 1, "name": "old"}] + assert (table.schema, table.indexes) == (schema, indexes) + + result = runner.invoke(cli.cli, args, input='[{"id": 2, "name": "fresh"}]') + assert result.exit_code == 0, result.output + with Database(db_path) as db: + assert list(db.table("items").rows) == [{"id": 2, "name": "fresh"}] + + +def test_insert_array_of_scalars_with_convert(db_path): + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "items", "-", "--convert", '{"value": row}'], + input="[1, 2]", + ) + assert result.exit_code == 0, result.output + with Database(db_path) as db: + assert list(db.table("items").rows) == [{"value": 1}, {"value": 2}] + + def test_insert_alter(db_path, tmpdir): result = CliRunner().invoke( cli.cli,