From 9fd9b268cbb5ff85f2bb97094df75190c0fe41cd Mon Sep 17 00:00:00 2001 From: Rajula chandrasekhar Reddy Date: Tue, 24 Nov 2026 16:39:57 +0530 Subject: [PATCH] Implemented optional --atomic for insert and upsert --- docs/cli-reference.rst | 6 ++++ docs/cli.rst | 9 ++++++ sqlite_utils/cli.py | 21 +++++++++++++ tests/test_cli_insert.py | 68 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 104 insertions(+) diff --git a/docs/cli-reference.rst b/docs/cli-reference.rst index c53d64222..15094f867 100644 --- a/docs/cli-reference.rst +++ b/docs/cli-reference.rst @@ -250,6 +250,8 @@ See :ref:`cli_inserting_data`, :ref:`cli_insert_csv_tsv`, :ref:`cli_insert_unstr Use --type column-name type to override the type automatically chosen when the table is created. + Use --atomic to roll back the entire import if any row fails. + You can also use --convert to pass a fragment of Python code that will be used to convert each input. @@ -306,6 +308,7 @@ See :ref:`cli_inserting_data`, :ref:`cli_insert_csv_tsv`, :ref:`cli_insert_unstr --no-headers CSV file has no header row --encoding TEXT Character encoding for input, defaults to utf-8 --batch-size INTEGER Commit every X records + --atomic Run the entire import in a single transaction --stop-after INTEGER Stop after X records --alter Alter existing table to add any missing columns --not-null TEXT Columns that should be created as NOT NULL @@ -340,6 +343,8 @@ See :ref:`cli_upsert`. If the table already exists and has a primary key, --pk can be omitted. + Use --atomic to roll back the entire import if any row fails. + Use --type column-name type to override the type automatically chosen when the table is created. @@ -370,6 +375,7 @@ See :ref:`cli_upsert`. --no-headers CSV file has no header row --encoding TEXT Character encoding for input, defaults to utf-8 --batch-size INTEGER Commit every X records + --atomic Run the entire import in a single transaction --stop-after INTEGER Stop after X records --alter Alter existing table to add any missing columns --not-null TEXT Columns that should be created as NOT NULL diff --git a/docs/cli.rst b/docs/cli.rst index 78c33b8ae..bf0b22da1 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -1195,6 +1195,11 @@ You can delete all the existing rows in the table before inserting the new recor sqlite-utils insert dogs.db dogs dogs.json --truncate +Use ``--atomic`` to run the entire import in one transaction. If a row fails, +all rows and schema changes from that import will be rolled back. This also +means ``--batch-size`` will no longer commit partial progress when ``--atomic`` +is used. + You can add the ``--analyze`` option to run ``ANALYZE`` against the table after the rows have been inserted. .. note:: @@ -1656,6 +1661,10 @@ If the table already exists and has a primary key, you can omit the ``--pk`` opt The command will fail if you reference columns that do not exist on the table. To automatically create missing columns, use the ``--alter`` option. +Use ``--atomic`` to run the entire import in one transaction. If a row fails, +all rows and schema changes from that import will be rolled back, including when +``--batch-size`` is specified. + .. note:: ``upsert`` in sqlite-utils 1.x worked like ``insert ... --replace`` does in 2.x. See `issue #66 `__ for details of this change. diff --git a/sqlite_utils/cli.py b/sqlite_utils/cli.py index c23090283..aa169aa85 100644 --- a/sqlite_utils/cli.py +++ b/sqlite_utils/cli.py @@ -1005,6 +1005,11 @@ def inner(fn): click.option( "--batch-size", type=int, default=100, help="Commit every X records" ), + click.option( + "--atomic", + is_flag=True, + help="Run the entire import in a single transaction", + ), click.option("--stop-after", type=int, help="Stop after X records"), click.option( "--alter", @@ -1095,6 +1100,7 @@ def insert_upsert_implementation( functions=None, strict=False, code=None, + atomic=False, ): db = sqlite_utils.Database(path) _register_db_for_cleanup(db) @@ -1103,6 +1109,13 @@ def insert_upsert_implementation( column_type_overrides = {column: ctype.upper() for column, ctype in (types or [])} def _insert_docs(docs, tracker=None): + if atomic: + with db.atomic(): + _insert_docs_inner(docs, tracker=tracker) + else: + _insert_docs_inner(docs, tracker=tracker) + + def _insert_docs_inner(docs, tracker=None): extra_kwargs: dict[str, Any] = { "ignore": ignore, "replace": replace, @@ -1373,6 +1386,7 @@ def insert( no_headers, encoding, batch_size, + atomic, stop_after, alter, no_detect_types, @@ -1406,6 +1420,8 @@ def insert( Use --type column-name type to override the type automatically chosen when the table is created. + Use --atomic to roll back the entire import if any row fails. + You can also use --convert to pass a fragment of Python code that will be used to convert each input. @@ -1481,6 +1497,7 @@ def rows(): types=types, strict=strict, code=code, + atomic=atomic, ) except UnicodeDecodeError as ex: raise click.ClickException(UNICODE_ERROR.format(ex)) @@ -1511,6 +1528,7 @@ def upsert( no_headers, encoding, alter, + atomic, not_null, default, types, @@ -1527,6 +1545,8 @@ def upsert( If the table already exists and has a primary key, --pk can be omitted. + Use --atomic to roll back the entire import if any row fails. + Use --type column-name type to override the type automatically chosen when the table is created. @@ -1571,6 +1591,7 @@ def upsert( silent=silent, strict=strict, code=code, + atomic=atomic, ) except UnicodeDecodeError as ex: raise click.ClickException(UNICODE_ERROR.format(ex)) diff --git a/tests/test_cli_insert.py b/tests/test_cli_insert.py index 011786259..7fa1c244e 100644 --- a/tests/test_cli_insert.py +++ b/tests/test_cli_insert.py @@ -385,6 +385,74 @@ def test_insert_alter(db_path, tmpdir): ] == list(db.query("select foo, n, baz from from_json_nl")) +@pytest.mark.parametrize( + "command,rows", + ( + ("insert", [{"id": 1}, {"id": 1}]), + ("upsert", [{"id": 1}, {"name": "Missing primary key"}]), + ), +) +def test_insert_upsert_atomic_rolls_back_new_table(db_path, command, rows): + result = CliRunner().invoke( + cli.cli, + [ + command, + db_path, + "rows", + "-", + "--pk", + "id", + "--atomic", + "--batch-size", + "1", + ], + input=json.dumps(rows), + ) + assert result.exit_code != 0 + assert not Database(db_path).table("rows").exists() + + +@pytest.mark.parametrize( + "command,rows", + ( + ("insert", [{"id": 2, "name": "New", "extra": "value"}, {"id": 2}]), + ( + "upsert", + [ + {"id": 1, "name": "Updated", "extra": "value"}, + {"name": "Missing primary key"}, + ], + ), + ), +) +def test_insert_upsert_atomic_rolls_back_rows_and_altered_columns( + db_path, command, rows +): + db = Database(db_path) + db.table("rows").insert({"id": 1, "name": "Original"}, pk="id") + + result = CliRunner().invoke( + cli.cli, + [ + command, + db_path, + "rows", + "-", + "--pk", + "id", + "--alter", + "--atomic", + "--batch-size", + "1", + ], + input=json.dumps(rows), + ) + + assert result.exit_code != 0 + assert set(db.table("rows").columns_dict) == {"id", "name"} + assert list(db.table("rows").rows) == [{"id": 1, "name": "Original"}] + + def test_insert_analyze(db_path): db = Database(db_path) db.table("rows").insert({"foo": "x", "n": 3})