Repository navigation
Apply SQL conversions once during upsert updates - #947
Conversation
|
|
||
| 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. | ||
|
|
||
| Conversions are applied once to each incoming value. With ``upsert()`` and ``upsert_all()``, this is the same whether a row is inserted or updated. |
There was a problem hiding this comment.
Could this wording be limited to non-primary-key values, or mention the legacy exception? With use_old_upsert=True, a conversion on the primary key is currently ignored:
db = Database(memory=True, use_old_upsert=True)
table = db["records"]
table.upsert({"id": 3, "value": "a"}, pk="id", conversions={"id": "? * 10"})
list(table.rows) # [{"id": 3, "value": "a"}]The native implementation stores id=30. I checked both upsert() and upsert_all() against the base and this PR using in-memory SQLite. This difference predates the PR; I don't think the old path needs to be changed here, but “each incoming value” appears broader than the existing behaviour. Checked with Codex assistance.
There was a problem hiding this comment.
Thanks for catching this. Confirmed for both upsert() and upsert_all(): the native path stores id=30, while the legacy path stores id=3, including on subsequent updates. I narrowed the documentation to non-primary-key values and explicitly noted the use_old_upsert=True primary-key exception in e16d89d. The existing legacy behavior is unchanged.
| table = db["records"] | ||
| for value, expected in ( | ||
| (first, expected_first), | ||
| (second, expected_second), |
There was a problem hiding this comment.
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.
Closes:
When an upsert updates an existing row, SQL conversions are applied to the incoming value in
VALUESand then again inDO UPDATE. For example,? * 100stores120000instead of1200for an incoming value of12. JSON extraction can fail on the second conversion, and replacing every?also changes question marks inside SQL string literals.Assign
excluded.<column>directly in the conflict-update clause, since it already contains the converted insertion value. This gives inserts and updates the same conversion-once behavior and leaves the legacy upsert implementation intact. The API documentation now states that behavior.Regression coverage includes both upsert methods and implementations, multiplication, suffixes, JSON extraction, literal question marks, repeated updates, and mixed insert/update batches with two batch sizes.
Validation on Linux, Python 3.13.18, SQLite 3.53.1:
--sqlite-autocommit: 26 passed.cog --check --diff), andgit diff --checkpass.📚 Documentation preview 📚: https://sqlite-utils--947.org.readthedocs.build/en/947/