#handling connected multiple queries

3 messages · Page 1 of 1 (latest)

hushed brook
#

How do we handle the case that is, if we have 2 or 3 queries that are connected, 2 of them insert successfully into the database into different tables but one of them fails. The successful queries should be rolledback. @ember bough

ember boughBOT
#

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

#

In Convex, you can handle multiple connected queries using mutations. If you have multiple queries that are connected, you can run them all in a single mutation. If any of the queries fail, all changes from the entire function are rolled back and never committed to the database. This is because mutations in Convex run as transactions.

Here's an example of how you can do this:

export const createUser = mutation(async (ctx, args) => {
  const userId = await ctx.db.insert('users', { externalId: args.externalId })
  await ctx.db.insert('foo', { userId })
  throw Error('whoops!')
})

In this example, even though both inserts went fine, the thrown error cancels the whole thing. The result will only be the thrown error in your logs.

Furthermore, because mutations are ACID transactions, you can trust that any data you're reading during the mutation will not be changed by any other concurrently running mutations during execution.

For more information, you can refer to the Convex documentation on mutation functions and transactions (https://docs.convex.dev/functions/mutation-functions#transactions).

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

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