From dee18ed8ce7af2ab8699bcb5a51a99f48301bc42 Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Wed, 7 Dec 2022 17:29:24 -0800 Subject: [PATCH] test_create_table_error_rows_twice_with_duplicates, refs #1927 --- datasette/views/database.py | 6 +++++- tests/test_api_write.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/datasette/views/database.py b/datasette/views/database.py index c295904c..8467aa5b 100644 --- a/datasette/views/database.py +++ b/datasette/views/database.py @@ -683,7 +683,11 @@ class TableCreateView(BaseView): bad_pks = False if len(actual_pks) == 1 and data.get("pk") and data["pk"] != actual_pks[0]: bad_pks = True - elif len(actual_pks) > 1 and data.get("pks") and set(data["pks"]) != set(actual_pks): + elif ( + len(actual_pks) > 1 + and data.get("pks") + and set(data["pks"]) != set(actual_pks) + ): bad_pks = True if bad_pks: return _error(["pk cannot be changed for existing table"]) diff --git a/tests/test_api_write.py b/tests/test_api_write.py index 2dce85a3..afe68d13 100644 --- a/tests/test_api_write.py +++ b/tests/test_api_write.py @@ -1236,6 +1236,39 @@ async def test_create_table_error_if_pk_changed(ds_write): } +@pytest.mark.asyncio +async def test_create_table_error_rows_twice_with_duplicates(ds_write): + # Error if you don't send ignore: True or replace: True + token = write_token(ds_write) + input = { + "rows": [{"id": 1, "name": "Row 1"}, {"id": 2, "name": "Row 2"}], + "table": "test_create_twice", + "pk": "id", + } + first_response = await ds_write.client.post( + "/data/-/create", + json=input, + headers={ + "Authorization": "Bearer {}".format(token), + "Content-Type": "application/json", + }, + ) + assert first_response.status_code == 201 + second_response = await ds_write.client.post( + "/data/-/create", + json=input, + headers={ + "Authorization": "Bearer {}".format(token), + "Content-Type": "application/json", + }, + ) + assert second_response.status_code == 400 + assert second_response.json() == { + "ok": False, + "errors": ["UNIQUE constraint failed: test_create_twice.id"], + } + + @pytest.mark.asyncio @pytest.mark.parametrize( "path",