Web Dev Cody
Web Dev Cody2y ago

Query from actions

so is it not possible to query the database from an action? I understand doing database writes must live in mutations
3 Replies
ballingt
ballingt2y ago
You can run as many queries and mutations as you need from an action (we suggest you use internal queries and mutations) with ctx.runQuery(internal.messages.list) so queries here are like database accessors
Web Dev Cody
Web Dev CodyOP2y ago
ahh I guess my question was more of a technical one of why not have access to the db object inside actions to allow us to query the db directly, but now that i think about it, forcing that to live in a query function would feel more consistent
lee
lee2y ago
just chiming in with more detail: 1. we could make a DatabaseReader available in actions for oneoff queries, but actions aren't transactional so the consistency guarantees would be different, which may cause unintentional bugs. 2. for Node.js actions it would be slower because we would have to shuttle each document from the convex database & runtime (which are closely coupled) to node (which is separate). 3. queries are fast so they don't keep the transaction open long or hit conflicts, but actions can take minutes. if we allow const q = db.query('tbl') at the start of the action and await q.next() several minutes later, we might not be able to make a single db.query transactional within itself.

Did you find this page helpful?