From 2f3371ecb1ad075672d3f815993193732ed00be5 Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Tue, 18 May 2021 20:26:13 -0700 Subject: [PATCH] Suggest --alter if column is missing, closes #259, refs #256 --- sqlite_utils/cli.py | 13 ++++++++++--- tests/test_cli.py | 15 +++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/sqlite_utils/cli.py b/sqlite_utils/cli.py index 9d899d5..011935a 100644 --- a/sqlite_utils/cli.py +++ b/sqlite_utils/cli.py @@ -732,9 +732,16 @@ def insert_upsert_implementation( extra_kwargs["upsert"] = upsert # Apply {"$base64": true, ...} decoding, if needed docs = (decode_base64_values(doc) for doc in docs) - db[table].insert_all( - docs, pk=pk, batch_size=batch_size, alter=alter, **extra_kwargs - ) + try: + db[table].insert_all( + docs, pk=pk, batch_size=batch_size, alter=alter, **extra_kwargs + ) + except sqlite3.OperationalError as e: + if e.args and "has no column named" in e.args[0]: + raise click.ClickException( + "{}\n\nTry using --alter to add additional columns".format(e.args[0]) + ) + raise @cli.command() diff --git a/tests/test_cli.py b/tests/test_cli.py index 8775396..2e982dd 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -354,6 +354,21 @@ def test_add_column_foreign_key(db_path): assert "table 'bobcats' does not exist" in str(result.exception) +def test_suggest_alter_if_column_missing(db_path): + db = Database(db_path) + db["authors"].insert({"id": 1, "name": "Sally"}, pk="id") + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "authors", "-"], + input='{"id": 2, "name": "Barry", "age": 43}', + ) + assert result.exit_code != 0 + assert result.output.strip() == ( + "Error: table authors has no column named age\n\n" + "Try using --alter to add additional columns" + ) + + def test_index_foreign_keys(db_path): test_add_column_foreign_key(db_path) db = Database(db_path)