#Cascade deletion

3 messages · Page 1 of 1 (latest)

hollow leaf
#

Is there ant way to implement cascade deletion, basically when I delete a document (project), I want to delete all documents that are related to it (tasks, chats, messagesz etc)

frozen craterBOT
#

Hi @hollow leaf. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, there are several ways to implement cascade deletion in Convex. Here are the main options:

  1. Using Database Triggers: Convex now supports database triggers, which can be used to implement cascade deletes. Here's an example:
triggers.register("users", async (ctx, change) => {
  if (change.operation === "delete") {
    for await (const message of ctx.db.query("messages")
        .withIndex("owner", q=>q.eq("owner", change.id))) {
      await ctx.db.delete(message._id);
    }
  }
});

This trigger will delete all messages owned by a user when that user is deleted. Source (https://stack.convex.dev/triggers#cascade-deletes)

  1. Manual Implementation: You can manually implement cascade deletion in your mutation function. Here's a basic example:
deleteProject:
  ctx.db.delete(project._id)
  tasks = ctx.db.query("tasks").withIndex(...)
  for (task of tasks) {
    ctx.db.delete(task._id)
  }
  // Repeat for chats, messages, etc.

Source (https://discord.com/channels/1019350475847499849/1240426544225063064)

  1. Using Convex Ents: Convex Ents, a higher-level data modeling library for Convex, provides more advanced options for cascade deletion. However, it's worth noting that Ents is currently in maintenance mode. Source (https://stack.convex.dev/ents)

When implementing cascade deletion, be cautious about deleting a large number of documents in a single transaction, as this can potentially exceed Convex's transaction limits. For large-scale deletions, you might need to consider asynchronous or scheduled deletion strategies. Source (https://stack.convex.dev/ents#cascading-deletes-soft-deletion-and-scheduled-deletion)

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: