From b9629099ab21554a00eb11506201e6972600b93c Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Sat, 12 Jun 2021 19:57:21 -0700 Subject: [PATCH] Fix bug with upsert_all() and single column tables, closes #271 --- sqlite_utils/db.py | 28 +++++++++++++++------------- tests/test_create.py | 7 +++++++ tests/test_upsert.py | 7 +++++++ 3 files changed, 29 insertions(+), 13 deletions(-) diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index 53fae10..31d4cee 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -1732,20 +1732,22 @@ class Table(Queryable): queries_and_params.append((sql, [record[col] for col in pks])) # UPDATE [book] SET [name] = 'Programming' WHERE [id] = 1001; set_cols = [col for col in all_columns if col not in pks] - sql2 = "UPDATE [{table}] SET {pairs} WHERE {wheres}".format( - table=self.name, - pairs=", ".join( - "[{}] = {}".format(col, conversions.get(col, "?")) - for col in set_cols - ), - wheres=" AND ".join("[{}] = ?".format(pk) for pk in pks), - ) - queries_and_params.append( - ( - sql2, - [record[col] for col in set_cols] + [record[pk] for pk in pks], + if set_cols: + sql2 = "UPDATE [{table}] SET {pairs} WHERE {wheres}".format( + table=self.name, + pairs=", ".join( + "[{}] = {}".format(col, conversions.get(col, "?")) + for col in set_cols + ), + wheres=" AND ".join("[{}] = ?".format(pk) for pk in pks), + ) + queries_and_params.append( + ( + sql2, + [record[col] for col in set_cols] + + [record[pk] for pk in pks], + ) ) - ) # We can populate .last_pk right here if num_records_processed == 1: self.last_pk = tuple(record[pk] for pk in pks) diff --git a/tests/test_create.py b/tests/test_create.py index 6e925dc..926a7d1 100644 --- a/tests/test_create.py +++ b/tests/test_create.py @@ -991,6 +991,13 @@ def test_insert_all_empty_list(fresh_db): assert 1 == fresh_db["t"].count +def test_insert_all_single_column(fresh_db): + table = fresh_db["table"] + table.insert_all([{"name": "Cleo"}], pk="name") + assert [{"name": "Cleo"}] == list(table.rows) + assert table.pks == ["name"] + + def test_create_with_a_null_column(fresh_db): record = {"name": "Name", "description": None} fresh_db["t"].insert(record) diff --git a/tests/test_upsert.py b/tests/test_upsert.py index 100c6c1..9b1990e 100644 --- a/tests/test_upsert.py +++ b/tests/test_upsert.py @@ -21,6 +21,13 @@ def test_upsert_all(fresh_db): assert table.last_pk is None +def test_upsert_all_single_column(fresh_db): + table = fresh_db["table"] + table.upsert_all([{"name": "Cleo"}], pk="name") + assert [{"name": "Cleo"}] == list(table.rows) + assert table.pks == ["name"] + + def test_upsert_error_if_no_pk(fresh_db): table = fresh_db["table"] with pytest.raises(PrimaryKeyRequired):