Batching individual updates #1400
-
Hello! I noticed my code running slowly and narrowed it down to me doing many small updates, the majority of which can probably be put into a batch. The problem is that I'm struggling to figure out a 'good' way to do it. Essentially I have two tables, one referencing the other. Let's say there's CREATE TABLE trees (
treeId INT NULL, -- filled in from backend
treeUuid TEXT NOT NULL PRIMARY KEY -- not in backend, filled in, used as key in app
);
CREATE TABLE apples (
...,
treeId INT NULL, -- filled in from backend
treeUuid TEXT NULL REFERENCES trees(treeUuid) -- not in backend, needs to be filled in by update
); What the update should do, is update all My current approach looks a bit like the following: List<Tree> trees = await this.allTrees().get();
// for each tree
for (Tree tree in trees) {
// update all apples for this particular tree
update(apples)
..where((apple) => apple.treeId.equals(tree.treeId))
..write(ApplesCompanion(treeUuid: Value(tree.treeUuid)));
} How can I go about doing this in a batch? Should I use a custom query to join the apples and trees and use that to update? Since there's quite a few combinations of tables I need to process, that'd require quite a bit of manual query writing, which isn't ideal (but if it's the best solution then so be it). Thanks in advance for the help :) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 9 replies
-
This should work:
This would probably be even faster, though its SQL only (I don't think moor support UPDATE apples
SET
tree_uuid = tree.tree_uuid
FROM trees
WHERE trees.tree_id = apples.tree_id However, I think the better solution is to just remove |
Beta Was this translation helpful? Give feedback.
This should work:
This would probably be even faster, though its SQL only (I don't think moor support
UPDATE FROM
):However, I think the better solution is to just remove
apples.tree_id
and instead get thetree_id
from thetrees
table.