Skip to content
Merged
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
2 changes: 2 additions & 0 deletions docs/python-api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2346,6 +2346,8 @@ You can specify an upper case conversion for a specific column like so:

The dictionary key is the column name to be converted. The value is the SQL fragment to use, with a ``?`` placeholder for the original value.

With ``upsert()`` and ``upsert_all()``, conversions are applied once to each incoming non-primary-key value, whether a row is inserted or updated. The legacy upsert implementation (``use_old_upsert=True``) ignores conversions on primary-key columns.

A more useful example: if you are working with `SpatiaLite <https://www.gaia-gis.it/fossil/libspatialite/index>`__ you may find yourself wanting to create geometry values from a WKT value. Code to do that could look like this:

.. code-block:: python
Expand Down
7 changes: 1 addition & 6 deletions sqlite_utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -4449,12 +4449,7 @@ def build_insert_queries_and_params(
assignments = []
for c in non_pk_cols:
c_quoted = quote_identifier(c)
if c in conversions:
assignments.append(
f"{c_quoted} = {conversions[c].replace('?', f'excluded.{c_quoted}')}"
)
else:
assignments.append(f"{c_quoted} = excluded.{c_quoted}")
assignments.append(f"{c_quoted} = excluded.{c_quoted}")
do_clause = "DO UPDATE SET " + ", ".join(assignments)
else:
# All columns are in the PK – nothing to update.
Expand Down
63 changes: 63 additions & 0 deletions tests/test_conversions.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import pytest

from sqlite_utils import Database


def test_insert_conversion(fresh_db):
table = fresh_db.table("table")
table.insert({"foo": "bar"}, conversions={"foo": "upper(?)"})
Expand Down Expand Up @@ -28,6 +33,64 @@ def test_upsert_all_conversion(fresh_db):
assert [{"id": 1, "foo": "BAR"}] == list(table.rows)


@pytest.mark.parametrize("use_old_upsert", (False, True))
@pytest.mark.parametrize("method", ("upsert", "upsert_all"))
@pytest.mark.parametrize(
"first,second,conversion,expected_first,expected_second",
(
(10, 12, "? * 100", 1000, 1200),
("first", "second", "? || '-stored'", "first-stored", "second-stored"),
(
'{"name":"first"}',
'{"name":"second"}',
"json_extract(?, '$.name')",
"first",
"second",
),
("first", "second", "? || '?'", "first?", "second?"),
),
ids=("multiply", "append", "json-extract", "literal-question-mark"),
)
def test_upsert_conversion_once(
use_old_upsert, method, first, second, conversion, expected_first, expected_second
):
db = Database(memory=True, use_old_upsert=use_old_upsert)
table = db["records"]
for value, expected in (
(first, expected_first),
(second, expected_second),

@simonw simonw Nov 29, 2026 •

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This second operation was the one that previously exposed the bug - the conversion ran once in the VALUES clause and again in DO UPDATE SET.

(second, expected_second),
):
record = {"id": 1, "value": value}
getattr(table, method)(
record if method == "upsert" else [record],
pk="id",
conversions={"value": conversion},
)
assert table.get(1) == {"id": 1, "value": expected}


@pytest.mark.parametrize("use_old_upsert", (False, True))
@pytest.mark.parametrize("batch_size", (1, 100))
def test_upsert_all_converted_values_mixed_insert_update(use_old_upsert, batch_size):
db = Database(memory=True, use_old_upsert=use_old_upsert)
table = db["prices"]
table.insert({"id": 1, "amount": 1000, "note": "original"}, pk="id")
table.upsert_all(
[
{"id": 1, "amount": 12, "note": "updated"},
{"id": 2, "amount": 20, "note": "new"},
],
pk="id",
conversions={"amount": "? * 100"},
batch_size=batch_size,
)
assert list(table.rows_where(order_by="id")) == [
{"id": 1, "amount": 1200, "note": "updated"},
{"id": 2, "amount": 2000, "note": "new"},
]


def test_update_conversion(fresh_db):
table = fresh_db.table("table")
table.insert({"id": 5, "foo": "bar"}, pk="id")
Expand Down