-
Notifications
You must be signed in to change notification settings - Fork 923
Executing multiple sql commands with one generated function #2821
-
My table of items looks like this.
I am writing a delete API which deletes an item and should update the positions of the remaining items so there are no gaps. For example, after I delete
In other words - it should delete the target item and reduce the position of all the items with positions greater than that of the target item by one. Below is the way I am currently doing it -
And calling the functions shown -
I am first getting the item to be deleted to get its position, deleting the item, and executing an update command with the position found in the first step. I want to reduce the function calls I make for this delete operation. Questions -
|
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment
-
To execute multiple queries in a single function, you'll want to use a database transaction. Executing multiple queries outside of a transaction may result in race conditions, so you'll want to do this anyways.
If you're using PostgreSQL, you don't need the GetItem
query. Instead you can use RETURNING
. But if you're using MySQL, you're going to need to use the three query approach.
-- name: DeleteItem :one DELETE FROM items WHERE id = ? RETURNING position; -- name: UpdatePositions :execrows UPDATE items SET position = position - 1 WHERE item.position > sqlc.arg(position);
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 1