Skip to content

Commit

Permalink
Fix bug with upsert_all() and single column tables, closes #271
Browse files Browse the repository at this point in the history
  • Loading branch information
simonw committed Jun 13, 2021
1 parent b0f9d1e commit b962909
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 13 deletions.
28 changes: 15 additions & 13 deletions sqlite_utils/db.py
Expand Up @@ -1732,20 +1732,22 @@ def build_insert_queries_and_params(
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)
Expand Down
7 changes: 7 additions & 0 deletions tests/test_create.py
Expand Up @@ -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)
Expand Down
7 changes: 7 additions & 0 deletions tests/test_upsert.py
Expand Up @@ -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):
Expand Down

0 comments on commit b962909

Please sign in to comment.