Replacing table entry in prisma

Viewed 18

I'm using prisma with postgresql. I have this situation where I basically need to replace an entire row of a table. In the new row, every attribute might be different than in the old row. However, the id must be the same. I know this sounds like an update, however, there might attributes with null as a value in the new row and a non null value in the old row, so using something like

prisma.resource.update(where: {
    id: id,
  },
  data: {
    [key 1 of new row]: [value for key 1 in new object],
    ...
    [key n of new row]: [value for key n in new object],  
  },)

won't work unless I also explicitly set to null the remaining attributes of the table not present in the keys of the new row. Setting this attributes to null is not that easy as I don't have a list of the attributes of the table (Although I could write one, I would like my schema.prisma to be the only source of truth and having to update such list every time something changes is something I would like to avoid). I thought about running a transaction where I first delete the old row and then write the new row, but this won't work since the table has foreign keys, so I will get Foreign key constraint failed when trying to delete the old row. So my question is

  • Is there a way to tell to prisma update to set to null in the db the non specified attributes in the data object?
  • Alternatively, I there a way to bypass the Foreign key constraint failed dynamically (Not changing the schema, as this is the only case in which I would like this to happen and not in every other delete)?
  • Is there a better way to achieve this?

Thanks in advance

1 Answers

Setting this attributes to null is not that easy as I don't have a list of the attributes of the table

You can get such a list from Prisma:

const fields = Prisma.dmmf.datamodel.models.find((model) => model.name == "resource")?.fields;

Then - as you suggested - you could set the remaining attributes to null.

Related