DEV Community

Cover image for Cascade deleting in Prisma (v2)
Pedro Martins
Pedro Martins

Posted on

Cascade deleting in Prisma (v2)

Prisma (v2) is one of the hottest ORM's right now (you can see some of the reason I think so here).

It still has some important holes, though. Cascade delete is one of the most prominent ones, and even though the developers have been aware of this issue, there is no expectation of when it will be solved (see more here and the discussion on the proposal here).

What is cascade delete?

Cascading delete allows you to automatically delete related records, which is important specially in one-to-many relations.

For example, if you delete an Author, you would expect all its Posts to be deleted as well (and any other records related to this author).

The cascade delete is usually configured at the database level and one would expect that it would be available to be expressed in the prisma schema.

Prisma behavior right now

Right now, if you have a required relation (such as Posts need to have an Author) and try to delete an Author with Posts, prisma will return:

The change you are trying to make would violate the required relation 'PostToAuthor' between the `Post` and `Author` models.
Enter fullscreen mode Exit fullscreen mode

Workarounds

1. Configure your database

The most basic option would be to configure your database to perform the cascading delete.

Prisma has a good documentation on how to do this on the most famous RDBMS here

2. Add Cascade Delete to schema (using Pal.js)

Pal.js is a library with a series of helper packages to use with Prisma. One of those, the On Delete plugin allows you to use comments on your schema do define on delete behaviors.

You can check more of it here.

3. Use $transactions to run deletions on a given order

This is what is recommended on Prisma docs (right here). In this solution, you would need to hard code all the deletions, which might be impracticable in some cases.

There is a package that can take care of that, creating all the deletions necessary to cascade delete and perform them on the right order. Check more here;

Conclusions

I hope Prisma team will soon tackle this issue so we can create cascade deletes out of the box. On the meantime, I tend for the option 3 and the prisma-cascade-delete package.

Feel free to ask questions or reach me out on Twitter

Top comments (0)