Skip to content

Commit 7c28a4d

Browse files
committed
Fix for upsert(hash_id=) bug, closes #84
1 parent 72fa16b commit 7c28a4d

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

sqlite_utils/db.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -943,8 +943,6 @@ def insert_all(
943943
data
944944
"""
945945
pk = self.value_or_default("pk", pk)
946-
if upsert and not pk:
947-
raise PrimaryKeyRequired("upsert() requires a pk")
948946
foreign_keys = self.value_or_default("foreign_keys", foreign_keys)
949947
column_order = self.value_or_default("column_order", column_order)
950948
not_null = self.value_or_default("not_null", not_null)
@@ -957,7 +955,12 @@ def insert_all(
957955
extracts = self.value_or_default("extracts", extracts)
958956
conversions = self.value_or_default("conversions", conversions)
959957

958+
if upsert and (not pk and not hash_id):
959+
raise PrimaryKeyRequired("upsert() requires a pk")
960960
assert not (hash_id and pk), "Use either pk= or hash_id="
961+
if hash_id:
962+
pk = hash_id
963+
961964
assert not (
962965
ignore and replace
963966
), "Use either ignore=True or replace=True, not both"

tests/test_upsert.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,14 @@ def test_upsert_error_if_no_pk(fresh_db):
2828
table.upsert({"id": 1, "name": "Cleo"})
2929

3030

31+
def test_upsert_with_hash_id(fresh_db):
32+
table = fresh_db["table"]
33+
table.upsert({"foo": "bar"}, hash_id="pk")
34+
assert [{"pk": "a5e744d0164540d33b1d7ea616c28f2fa97e754a", "foo": "bar"}] == list(
35+
table.rows
36+
)
37+
38+
3139
def test_upsert_compound_primary_key(fresh_db):
3240
table = fresh_db["table"]
3341
table.upsert_all(

0 commit comments

Comments
 (0)