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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions docs/cli.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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::
Expand Down Expand Up @@ -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 <https://github.com/simonw/sqlite-utils/issues/66>`__ for details of this change.

Expand Down
21 changes: 21 additions & 0 deletions sqlite_utils/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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)
Expand All @@ -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,
Expand Down Expand Up @@ -1373,6 +1386,7 @@ def insert(
no_headers,
encoding,
batch_size,
atomic,
stop_after,
alter,
no_detect_types,
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -1511,6 +1528,7 @@ def upsert(
no_headers,
encoding,
alter,
atomic,
not_null,
default,
types,
Expand All @@ -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.

Expand Down Expand Up @@ -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))
Expand Down
68 changes: 68 additions & 0 deletions tests/test_cli_insert.py
Original file line number Diff line number Diff line change
Expand Up @@ -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})
Expand Down
Loading