Search code examples
graphqlmutationhasura

Upsert Graphql Mutation with conflict constraint on nested object


I am trying to do an upsert in a single mutation. Here I have two tables Users table [id,isVerified,type] and Customers table [id,name,deviceToken] Here,Customers.id is a foreign key of Users.Id.
The following is the mutation-

 MyMutation {
  insert_Users(objects: [{isVerified: false, name: "+9100000000", type: "customer", 
    Customers: {data: {deviceToken: "TestToken001"}}}],
      on_conflict: {
            constraint: Users_name_key,
            update_columns: [isVerified]
          }) {
    affected_rows
    returning {
      Customers{
        deviceToken
      }
  }
}
} ```

//But when I run this, I get the exception 

{
  "errors": [
    {
      "extensions": {
        "path": "$.selectionSet.insert_Users.args.objects[0].Customers.data",
        "code": "constraint-violation"
      },
      "message": "Uniqueness violation. duplicate key value violates unique constraint \"Customers_pkey\""
    }
  ]
}

This seems to be because I am not setting conflict constraint on the nested Customers Object. How do I add the conflict constraint for a nested object?


Solution

  • You need to add the constraint object inside the nested data as well. Something like:

    MyMutation {
      insert_Users(objects: [{isVerified: false, name: "+9100000000", type: "customer", 
        Customers: {
           data: {deviceToken: "TestToken001"}, 
           on_conflict: {
                constraint: Customers_pkey,
                update_columns: [deviceToken]
              }         
         }}],
          on_conflict: {
                constraint: Users_name_key,
                update_columns: [isVerified]
              }) {
        affected_rows
        returning {
          Customers{
            deviceToken
          }
      }
    }
    }