From bb63c45b300adeebed84c77c446fb11feb3ba0bb Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Sun, 29 Nov 2026 11:52:25 -0800 Subject: [PATCH 1/3] upsert_all() no longer nulls out columns a record omits When records in a single upsert_all() batch supplied different keys, every record was padded to the batch-wide column list with None and the upsert assigned all of those columns, overwriting existing values with NULL. The same happened across chunks, since all_columns accumulates columns seen in earlier chunks. Upserts in dict mode now split each chunk into consecutive runs of records that supply the same columns and emit one statement per run, so each record only assigns the columns it provided. Runs are consecutive rather than globally grouped so records are still applied in order. Homogeneous batches still produce a single, unchanged statement. The use_old_upsert / SQLite < 3.24 path likewise only UPDATEs the columns each record supplied. Refs #873 Co-Authored-By: Claude Opus 5.5 --- sqlite_utils/db.py | 75 +++++++++++++++++++------- tests/test_upsert.py | 125 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 180 insertions(+), 20 deletions(-) diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index a80f52e87..56dcd6366 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -4440,35 +4440,70 @@ def build_insert_queries_and_params( ", ".join(pk_cols), ) ) - non_pk_cols = [c for c in all_columns if c not in pk_cols] conflict_sql = ", ".join(quote_identifier(c) for c in pk_cols) - if self.db.supports_on_conflict and not self.db.use_old_upsert: - if non_pk_cols: - # DO UPDATE - assignments = [] - for c in non_pk_cols: - c_quoted = quote_identifier(c) - assignments.append(f"{c_quoted} = excluded.{c_quoted}") - do_clause = "DO UPDATE SET " + ", ".join(assignments) + # A record should only update the columns it supplied, not every + # column seen in the batch (#873). Split the chunk into consecutive + # runs of records that supply the same columns - consecutive so that + # records are still applied in their original order. + runs: list[tuple[list[str], list[list[Any]]]] = [] + previous_indexes = None + for record, record_values in zip(chunk, values): + indexes = tuple( + i + for i, c in enumerate(all_columns) + if list_mode or c in record or c == hash_id + ) + run_values = [record_values[i] for i in indexes] + if runs and indexes == previous_indexes: + runs[-1][1].append(run_values) else: - # All columns are in the PK – nothing to update. - do_clause = "DO NOTHING" + runs.append(([all_columns[i] for i in indexes], [run_values])) + previous_indexes = indexes - sql = ( - f"INSERT INTO {quote_identifier(self.name)} ({columns_sql}) " - f"VALUES {row_placeholders_sql} " - f"ON CONFLICT({conflict_sql}) {do_clause}" - ) - return [(sql, flat_params)] + if self.db.supports_on_conflict and not self.db.use_old_upsert: + queries_and_params = [] + for run_columns, run_rows in runs: + non_pk_cols = [c for c in run_columns if c not in pk_cols] + if non_pk_cols: + # DO UPDATE + assignments = [] + for c in non_pk_cols: + c_quoted = quote_identifier(c) + assignments.append(f"{c_quoted} = excluded.{c_quoted}") + do_clause = "DO UPDATE SET " + ", ".join(assignments) + else: + # All columns are in the PK – nothing to update. + do_clause = "DO NOTHING" + + columns_sql = ", ".join(quote_identifier(c) for c in run_columns) + placeholder_expr = ", ".join( + conversions.get(c, "?") for c in run_columns + ) + row_placeholders_sql = ", ".join( + f"({placeholder_expr})" for _ in run_rows + ) + sql = ( + f"INSERT INTO {quote_identifier(self.name)} ({columns_sql}) " + f"VALUES {row_placeholders_sql} " + f"ON CONFLICT({conflict_sql}) {do_clause}" + ) + queries_and_params.append( + (sql, list(itertools.chain.from_iterable(run_rows))) + ) + return queries_and_params # At this point we need compatibility UPSERT for SQLite < 3.24.0 # (INSERT OR IGNORE + second UPDATE stage) queries_and_params = [] pks = pk_cols self.last_pk = None - for record_values in values: - record = dict(zip(all_columns, record_values)) + records = [ + dict(zip(run_columns, row)) + for run_columns, run_rows in runs + for row in run_rows + ] + for record in records: placeholders = list(pks) # Need to populate not-null columns too, or INSERT OR IGNORE ignores # them since it ignores the resulting integrity errors @@ -4485,7 +4520,7 @@ def build_insert_queries_and_params( (sql, [record[col] for col in pks] + ["" for _ in (not_null or [])]) ) # UPDATE "book" SET "name" = 'Programming' WHERE "id" = 1001; - set_cols = [col for col in all_columns if col not in pks] + set_cols = [col for col in record if col not in pks] if set_cols: sql2 = "UPDATE {} SET {pairs} WHERE {wheres}".format( quote_identifier(self.name), diff --git a/tests/test_upsert.py b/tests/test_upsert.py index 8274557fa..1ebbef57b 100644 --- a/tests/test_upsert.py +++ b/tests/test_upsert.py @@ -185,3 +185,128 @@ def test_upsert_compound_primary_key(fresh_db): # .upsert_all() with a single item should set .last_pk table.upsert_all([{"species": "cat", "id": 1, "age": 5}], pk=("species", "id")) assert ("cat", 1) == table.last_pk + + +@pytest.mark.parametrize("use_old_upsert", (False, True)) +def test_upsert_all_mixed_columns_leaves_omitted_columns_unchanged(use_old_upsert): + # https://github.com/simonw/sqlite-utils/issues/873 + db = Database(memory=True, use_old_upsert=use_old_upsert) + table = db.table("dogs") + table.insert_all( + [{"id": 1, "name": "Cleo", "age": 5}, {"id": 2, "name": "Nixie", "age": 6}], + pk="id", + ) + table.upsert_all( + [ + {"id": 1, "age": 7}, + {"id": 2, "name": "Nixie II"}, + # A brand new row gets NULL for the columns it omits + {"id": 3, "name": "Pancakes"}, + ], + pk="id", + ) + assert list(table.rows_where(order_by="id")) == [ + {"id": 1, "name": "Cleo", "age": 7}, + {"id": 2, "name": "Nixie II", "age": 6}, + {"id": 3, "name": "Pancakes", "age": None}, + ] + + +@pytest.mark.parametrize("use_old_upsert", (False, True)) +def test_upsert_all_mixed_columns_same_pk_twice(use_old_upsert): + # Records are applied in order, even when the same pk appears twice + db = Database(memory=True, use_old_upsert=use_old_upsert) + table = db.table("dogs") + table.insert({"id": 1, "name": "Cleo", "age": 5}, pk="id") + table.upsert_all( + [ + {"id": 1, "name": "First"}, + {"id": 1, "age": 6}, + {"id": 1, "name": "Second"}, + ], + pk="id", + ) + assert list(table.rows) == [{"id": 1, "name": "Second", "age": 6}] + + +@pytest.mark.parametrize("use_old_upsert", (False, True)) +def test_upsert_all_mixed_columns_across_chunks(use_old_upsert): + # Columns seen in an earlier chunk must not be nulled out in a later one + db = Database(memory=True, use_old_upsert=use_old_upsert) + table = db.table("dogs") + table.insert_all( + [{"id": 1, "name": "Cleo", "age": 5}, {"id": 2, "name": "Nixie", "age": 6}], + pk="id", + ) + table.upsert_all( + [{"id": 1, "age": 7}, {"id": 2, "name": "Nixie II"}], pk="id", batch_size=1 + ) + assert list(table.rows_where(order_by="id")) == [ + {"id": 1, "name": "Cleo", "age": 7}, + {"id": 2, "name": "Nixie II", "age": 6}, + ] + + +@pytest.mark.parametrize("use_old_upsert", (False, True)) +def test_upsert_all_mixed_columns_with_conversions(use_old_upsert): + db = Database(memory=True, use_old_upsert=use_old_upsert) + table = db.table("dogs") + table.insert_all( + [{"id": 1, "name": "Cleo", "age": 5}, {"id": 2, "name": "Nixie", "age": 6}], + pk="id", + ) + table.upsert_all( + [{"id": 1, "age": 7}, {"id": 2, "name": "nixie ii"}], + pk="id", + conversions={"name": "upper(?)"}, + ) + assert list(table.rows_where(order_by="id")) == [ + {"id": 1, "name": "Cleo", "age": 7}, + {"id": 2, "name": "NIXIE II", "age": 6}, + ] + + +@pytest.mark.parametrize("use_old_upsert", (False, True)) +def test_upsert_all_mixed_columns_with_hash_id(use_old_upsert): + db = Database(memory=True, use_old_upsert=use_old_upsert) + table = db.table("dogs") + table.insert_all( + [{"name": "Cleo", "age": 5}, {"name": "Nixie", "age": 6}], + hash_id="pk", + hash_id_columns=["name"], + ) + table.upsert_all( + [{"name": "Cleo", "age": 7}, {"name": "Nixie"}], + hash_id="pk", + hash_id_columns=["name"], + ) + assert [(r["name"], r["age"]) for r in table.rows_where(order_by="name")] == [ + ("Cleo", 7), + ("Nixie", 6), + ] + + +def test_upsert_all_homogeneous_batch_is_single_query(fresh_db): + table = fresh_db.table("dogs") + table.insert({"id": 1, "name": "Cleo"}, pk="id") + queries = table.build_insert_queries_and_params( + extracts=None, + chunk=[{"id": 1, "name": "A"}, {"id": 2, "name": "B"}], + all_columns=["id", "name"], + hash_id=None, + hash_id_columns=None, + upsert=True, + pk="id", + not_null=None, + conversions={}, + num_records_processed=2, + replace=False, + ignore=False, + ) + assert queries == [ + ( + 'INSERT INTO "dogs" ("id", "name") VALUES (?, ?), (?, ?) ' + 'ON CONFLICT("id") DO UPDATE SET "name" = excluded."name"', + [1, "A", 2, "B"], + ) + ] From 984745369d98b15e7c632583ae7d4ae580379fee Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Sun, 29 Nov 2026 12:04:35 -0800 Subject: [PATCH 2/3] Skip exact-SQL upsert test on SQLite without ON CONFLICT Refs #873 Co-Authored-By: Claude Fable 5.2 --- tests/test_upsert.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/test_upsert.py b/tests/test_upsert.py index 1ebbef57b..8c9fc55ef 100644 --- a/tests/test_upsert.py +++ b/tests/test_upsert.py @@ -287,6 +287,8 @@ def test_upsert_all_mixed_columns_with_hash_id(use_old_upsert): def test_upsert_all_homogeneous_batch_is_single_query(fresh_db): + if not fresh_db.supports_on_conflict: + pytest.skip("Needs SQLite 3.24+ for INSERT ... ON CONFLICT") table = fresh_db.table("dogs") table.insert({"id": 1, "name": "Cleo"}, pk="id") queries = table.build_insert_queries_and_params( From 24dd58921044a94cb9e0f0185222b2887fc5c779 Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Sun, 29 Nov 2026 12:04:35 -0800 Subject: [PATCH 3/3] Use db.table() in conversion tests to satisfy pyright db[name] is typed as Table | View, so pyright rejected .get() and .upsert_all() in the tests added for #946. Co-Authored-By: Claude Fable 5.2 --- tests/test_conversions.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_conversions.py b/tests/test_conversions.py index a7267174a..8d18c614c 100644 --- a/tests/test_conversions.py +++ b/tests/test_conversions.py @@ -55,7 +55,7 @@ def test_upsert_conversion_once( use_old_upsert, method, first, second, conversion, expected_first, expected_second ): db = Database(memory=True, use_old_upsert=use_old_upsert) - table = db["records"] + table = db.table("records") for value, expected in ( (first, expected_first), (second, expected_second), @@ -74,7 +74,7 @@ def test_upsert_conversion_once( @pytest.mark.parametrize("batch_size", (1, 100)) def test_upsert_all_converted_values_mixed_insert_update(use_old_upsert, batch_size): db = Database(memory=True, use_old_upsert=use_old_upsert) - table = db["prices"] + table = db.table("prices") table.insert({"id": 1, "amount": 1000, "note": "original"}, pk="id") table.upsert_all( [