Skip to content
Open
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
62 changes: 30 additions & 32 deletions sqlite_utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 == "<lambda>":
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 == "<lambda>":
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)
Expand Down Expand Up @@ -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)
Expand Down
29 changes: 29 additions & 0 deletions tests/test_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import pytest

from sqlite_utils.db import BadMultiValues
from sqlite_utils.utils import sqlite3


@pytest.mark.parametrize(
Expand Down Expand Up @@ -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",
(
Expand Down