Skip to content

Commit

Permalink
docs: clarify usage of upsert with surrogate primary keys
Browse files Browse the repository at this point in the history
  • Loading branch information
laurenceisla committed Sep 14, 2024
1 parent a064d0d commit c482cb1
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions docs/references/api/tables_views.rst
Original file line number Diff line number Diff line change
Expand Up @@ -623,18 +623,22 @@ You can make an upsert with :code:`POST` and the :code:`Prefer: resolution=merge
.. code-block:: bash
curl "http://localhost:3000/employees" \
curl "http://localhost:3000/products" \
-X POST -H "Content-Type: application/json" \
-H "Prefer: resolution=merge-duplicates" \
-d @- << EOF
[
{ "id": 1, "name": "Old employee 1", "salary": 30000 },
{ "id": 2, "name": "Old employee 2", "salary": 42000 },
{ "id": 3, "name": "New employee 3", "salary": 50000 }
{ "sku": "CL2031", "name": "T-shirt", "price": 35 },
{ "sku": "CL2040", "name": "Hoodie", "price": 60 },
{ "sku": "AC1022", "name": "Cap", "price": 30 }
]
EOF
By default, upsert operates based on the primary key columns, you must specify all of them. You can also choose to ignore the duplicates with :code:`Prefer: resolution=ignore-duplicates`. This works best when the primary key is natural, but it's also possible to use it if the primary key is surrogate (example: "id serial primary key"). For more details read `this issue <https://github.com/PostgREST/postgrest/issues/1118>`_.
By default, upsert operates based on the primary key columns, so you must specify all of them.
You can also choose to ignore the duplicates with :code:`Prefer: resolution=ignore-duplicates`.
Upsert works best when the primary key is natural (e.g. ``sku``).
However, it can work with surrogate primary keys (e.g. ``id serial primary key``), mostly to update existing entries.
For more details, read `this issue <https://github.com/PostgREST/postgrest/issues/1118>`_.
.. important::
After creating a table or changing its primary key, you must refresh PostgREST schema cache for upsert to work properly. To learn how to refresh the cache see :ref:`schema_reloading`.
Expand Down

0 comments on commit c482cb1

Please sign in to comment.