From 4922fc2e39ba3e6033ed3c1f6fccef60fa76d316 Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Wed, 15 Apr 2026 15:11:18 -0700 Subject: [PATCH] Disallow null primary keys in upsert Refs https://github.com/simonw/datasette/issues/1936#issuecomment-1341849496 --- datasette/views/table.py | 7 +++++++ tests/test_api_write.py | 8 ++++++++ 2 files changed, 15 insertions(+) diff --git a/datasette/views/table.py b/datasette/views/table.py index 5643858d..7027bb10 100644 --- a/datasette/views/table.py +++ b/datasette/views/table.py @@ -461,6 +461,13 @@ class TableInsertView(BaseView): i, '", "'.join(missing_pks) ) ) + null_pks = [pk for pk in pks_list if pk in row and row[pk] is None] + if null_pks: + errors.append( + 'Row {} has null primary key column(s): "{}"'.format( + i, '", "'.join(null_pks) + ) + ) invalid_columns = set(row.keys()) - columns if invalid_columns and not extras.get("alter"): errors.append( diff --git a/tests/test_api_write.py b/tests/test_api_write.py index adf8d310..91a88606 100644 --- a/tests/test_api_write.py +++ b/tests/test_api_write.py @@ -299,6 +299,14 @@ async def test_insert_rows(ds_write, return_rows): 400, ['Row 0 is missing primary key column(s): "id"'], ), + # null primary key + ( + "/data/docs/-/upsert", + {"rows": [{"id": None, "title": "Null PK"}]}, + None, + 400, + ['Row 0 has null primary key column(s): "id"'], + ), # Upsert does not support ignore or replace ( "/data/docs/-/upsert",