Skip to content

Commit 7399ae4

Browse files
committed
Fix for bug where self.last_pk didn't work for single list rows
1 parent d33b0e0 commit 7399ae4

File tree

2 files changed

+45
-10
lines changed

2 files changed

+45
-10
lines changed

sqlite_utils/db.py

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3529,17 +3529,29 @@ def insert_all(
35293529
self.last_pk = self.last_rowid
35303530
else:
35313531
# For an upsert use first_record from earlier
3532-
# Note: This code path assumes dict mode; list mode upserts
3533-
# with single records don't populate last_pk correctly yet
3534-
first_record_dict = cast(Dict[str, Any], first_record)
3535-
if hash_id:
3536-
self.last_pk = hash_record(first_record_dict, hash_id_columns)
3532+
if list_mode:
3533+
# In list mode, look up pk value by column index
3534+
first_record_list = cast(Sequence[Any], first_record)
3535+
if hash_id:
3536+
# hash_id not supported in list mode for last_pk
3537+
pass
3538+
elif isinstance(pk, str):
3539+
pk_index = column_names.index(pk)
3540+
self.last_pk = first_record_list[pk_index]
3541+
else:
3542+
self.last_pk = tuple(
3543+
first_record_list[column_names.index(p)] for p in pk
3544+
)
35373545
else:
3538-
self.last_pk = (
3539-
first_record_dict[pk]
3540-
if isinstance(pk, str)
3541-
else tuple(first_record_dict[p] for p in pk)
3542-
)
3546+
first_record_dict = cast(Dict[str, Any], first_record)
3547+
if hash_id:
3548+
self.last_pk = hash_record(first_record_dict, hash_id_columns)
3549+
else:
3550+
self.last_pk = (
3551+
first_record_dict[pk]
3552+
if isinstance(pk, str)
3553+
else tuple(first_record_dict[p] for p in pk)
3554+
)
35433555

35443556
if analyze:
35453557
self.analyze()

tests/test_list_mode.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,3 +263,26 @@ def data_generator():
263263
assert rows[0] == {"id": 1, "name": "Alice", "age": 30, "city": "NYC"}
264264
assert rows[1] == {"id": 2, "name": "Bob", "age": None, "city": None}
265265
assert rows[2] == {"id": 3, "name": "Charlie", "age": 35, "city": None}
266+
267+
268+
def test_list_mode_single_record_upsert_last_pk():
269+
"""Test that last_pk is populated correctly for single-record upserts in list mode"""
270+
db = Database(memory=True)
271+
272+
# Create table first
273+
db["data"].insert({"id": 1, "name": "Alice", "value": 100}, pk="id")
274+
275+
# Now upsert a single record using list mode
276+
def upsert_data():
277+
yield ["id", "name", "value"]
278+
yield [1, "Alice", 150] # Update existing
279+
280+
table = db["data"]
281+
table.upsert_all(upsert_data(), pk="id")
282+
283+
# Verify the data was updated
284+
rows = list(db["data"].rows)
285+
assert rows == [{"id": 1, "name": "Alice", "value": 150}]
286+
287+
# Verify last_pk is populated correctly
288+
assert table.last_pk == 1

0 commit comments

Comments
 (0)