Use jsonify_if_need for sql updates (#204)

* add failing tests for update with json values
* use jsonify_if_needed in for sql updates

Thanks, @mfa
This commit is contained in:
Andreas Madsack 2020-12-08 18:49:42 +01:00 committed by GitHub
commit c5f4f0f70c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 2 deletions

View file

@ -1426,7 +1426,7 @@ class Table(Queryable):
validate_column_names(updates.keys())
for key, value in updates.items():
sets.append("[{}] = {}".format(key, conversions.get(key, "?")))
args.append(value)
args.append(jsonify_if_needed(value))
wheres = ["[{}] = ?".format(pk_name) for pk_name in pks]
args.extend(pk_values)
sql = "update [{table}] set {sets} where {wheres}".format(

View file

@ -1,6 +1,10 @@
from sqlite_utils.db import NotFoundError
import collections
import json
import pytest
from sqlite_utils.db import NotFoundError
def test_update_rowid_table(fresh_db):
table = fresh_db["table"]
@ -82,3 +86,27 @@ def test_update_with_no_values_sets_last_pk(fresh_db):
assert 2 == table.last_pk
with pytest.raises(NotFoundError):
table.update(3)
@pytest.mark.parametrize(
"data_structure",
(
["list with one item"],
["list with", "two items"],
{"dictionary": "simple"},
{"dictionary": {"nested": "complex"}},
collections.OrderedDict(
[
("key1", {"nested": "complex"}),
("key2", "foo"),
]
),
[{"list": "of"}, {"two": "dicts"}],
),
)
def test_update_dictionaries_and_lists_as_json(fresh_db, data_structure):
fresh_db["test"].insert({"id": 1, "data": ""}, pk="id")
fresh_db["test"].update(1, {"data": data_structure})
row = fresh_db.execute("select id, data from test").fetchone()
assert row[0] == 1
assert data_structure == json.loads(row[1])