From c5f4f0f70ce394dfec6054c3c5aaedf330887093 Mon Sep 17 00:00:00 2001 From: Andreas Madsack Date: Tue, 8 Dec 2020 18:49:42 +0100 Subject: [PATCH] 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 --- sqlite_utils/db.py | 2 +- tests/test_update.py | 30 +++++++++++++++++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index c91ef82..8849680 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -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( diff --git a/tests/test_update.py b/tests/test_update.py index 3f4c4ba..7e3e0ab 100644 --- a/tests/test_update.py +++ b/tests/test_update.py @@ -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])