Upsert mutation with default ids?
See original GitHub issueHello, I am looking for a way to avoid defining both an insert and an update mutation in following your guidelines on upsert. However, in my DB schema, I never ask the client to define the primary key: it is an uuid that is auto-generated on insert by postgres. Therefore I need:
- on insert, to send all the data, without a primary key field
- on update, to send all the data, with the primary field
What I tried until now looks something like this:
mutation upsert_encounter(
$id: uuid
$data: jsonb
) {
insert_encounter(
objects: [
{
id: $id
data: $data
}
]
on_conflict: {
constraint: encounter_pkey
update_columns: [data]
}
) {
affected_rows
}
}
As I dont provide any $id value on insert, it sends an id set to null, and therefore it raises an error that I am violating the non-null constraint on my primary key…
I found a workaround in my javascript client in replacing id: $id
by ${form.id ? 'id: $id' : ''}
but I find this pretty ugly, and I then can’t separate my graphql code from my javascript code…
Another way I thought is to declare the objects to upsert like this: objects: [$object]
, but then I have another problem as I intend to upsert nested relations as well…
Any idea on how to make things cleaner?
Issue Analytics
- State:
- Created 5 years ago
- Reactions:5
- Comments:6 (4 by maintainers)
I’m with you on this one! Just experienced the exact same issue. I want to reduce the number of mutations and try to combine the insert/update operations using a single mutation. The problem though is that I will have to pass in the primary_key even though it is set to auto-increment integer. I am looking for a way to have that auto generated as it should be in case I send a ‘null’ value for the ID (Insert). I suppose this could be considered a missing feature.
Thanks @0x777 for your reply. I don’t understand your last sentence. But overall it makes sense. The issue in having two mutations every time, one insert and one update, is that it will multiply the complexity of my code. I foresee to have to define mutations for approximately 50 tables, including nested mutations. I initially tried the 2 mutations approach, but the complexity of the code exploded, making it very hard to maintain. I strongly believe most of the upsert cases are meant to insert or update rows without knowing if th data already exists or not, as per definition upsert is supposed to let the server decide wether this is an insert or an update, and I will be pleased that we could consider this limitation as a missing feature 😃