From eb6f2ac2b0bf46426aa4002966b15640b7aa73b5 Mon Sep 17 00:00:00 2001 From: NoVa-LuNo <110672024+NoVa-LuNo@users.noreply.github.com> Date: Fri, 4 Dec 2026 04:06:12 +0100 Subject: [PATCH] Roll back output columns when conversion fails AI assistance: OpenAI Codex. --- sqlite_utils/db.py | 62 +++++++++++++++++++++---------------------- tests/test_convert.py | 29 ++++++++++++++++++++ 2 files changed, 59 insertions(+), 32 deletions(-) diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index e85ac52a9..947303637 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -4302,34 +4302,34 @@ def convert( if len(columns) != 1: raise ValueError("output= can only be used with a single column") output = resolve_casing(output, self.columns_dict) - if output not in self.columns_dict: - self.add_column(output, output_type or "text") - - todo_count = self.count_where(where, where_args) * len(columns) - with progressbar(length=todo_count, silent=not show_progress) as bar: - def convert_value(v): - bar.update(1) - return jsonify_if_needed(fn(v)) - - fn_name = getattr(fn, "__name__", "fn") - if fn_name == "": - fn_name = f"lambda_{abs(hash(fn))}" - # replace=True: a previous .convert() may have registered a - # different callable under the same name, e.g. two bound methods - # called "get" or two functools.partial objects - self.db.register_function(convert_value, name=fn_name, replace=True) - sql = "update {} set {sets}{where};".format( - quote_identifier(self.name), - sets=", ".join( - [ - f"{quote_identifier(output or column)} = {fn_name}({quote_identifier(column)})" - for column in columns - ] - ), - where=f" where {where}" if where is not None else "", - ) - with self.db.atomic(): + with self.db.atomic(): + if output is not None and output not in self.columns_dict: + self.add_column(output, output_type or "text") + todo_count = self.count_where(where, where_args) * len(columns) + with progressbar(length=todo_count, silent=not show_progress) as bar: + + def convert_value(v): + bar.update(1) + return jsonify_if_needed(fn(v)) + + fn_name = getattr(fn, "__name__", "fn") + if fn_name == "": + fn_name = f"lambda_{abs(hash(fn))}" + # replace=True: a previous .convert() may have registered a + # different callable under the same name, e.g. two bound methods + # called "get" or two functools.partial objects + self.db.register_function(convert_value, name=fn_name, replace=True) + sql = "update {} set {sets}{where};".format( + quote_identifier(self.name), + sets=", ".join( + [ + f"{quote_identifier(output or column)} = {fn_name}({quote_identifier(column)})" + for column in columns + ] + ), + where=f" where {where}" if where is not None else "", + ) self.db.execute(sql, where_args or []) if drop: self.transform(drop=columns) @@ -4365,19 +4365,17 @@ def _convert_multi( pk_to_values[row_pk] = values bar.update(1) - # Add any new columns columns_to_create = types_for_column_types(new_column_types) - for column_name, column_type in columns_to_create.items(): - if column_name not in self.columns_dict: - self.add_column(column_name, column_type) - # Run the updates with ( progressbar( length=self.count, silent=not show_progress, label="2: Updating" ) as bar, self.db.atomic(), ): + for column_name, column_type in columns_to_create.items(): + if column_name not in self.columns_dict: + self.add_column(column_name, column_type) for pk, updates in pk_to_values.items(): self.update(pk, updates) bar.update(1) diff --git a/tests/test_convert.py b/tests/test_convert.py index fff1faf21..1344b2ea4 100644 --- a/tests/test_convert.py +++ b/tests/test_convert.py @@ -3,6 +3,7 @@ import pytest from sqlite_utils.db import BadMultiValues +from sqlite_utils.utils import sqlite3 @pytest.mark.parametrize( @@ -85,6 +86,34 @@ def test_convert_output_multiple_column_error(fresh_db): assert "output= can only be used with a single column" in str(excinfo.value) +def test_convert_rolls_back_output_column_on_error(fresh_db): + table = fresh_db.table("example").insert({"value": "not a number"}) + original_schema = table.schema + + with pytest.raises(sqlite3.OperationalError, match="user-defined function"): + table.convert("value", int, output="converted", output_type=int) + + assert table.schema == original_schema + assert list(table.rows) == [{"value": "not a number"}] + + +def test_convert_multi_rolls_back_output_columns_on_error(fresh_db): + fresh_db.execute( + "CREATE TABLE example (value INTEGER, checked INTEGER CHECK (checked >= 0))" + ) + rows = [{"value": 1, "checked": 0}, {"value": -1, "checked": 0}] + table = fresh_db.table("example").insert_all(rows) + original_schema = table.schema + + with pytest.raises(sqlite3.IntegrityError, match="CHECK constraint failed"): + table.convert( + "value", lambda value: {"converted": value, "checked": value}, multi=True + ) + + assert table.schema == original_schema + assert list(table.rows) == rows + + @pytest.mark.parametrize( "type,expected", (