Context - I need help with writing SQL queries and use sqlc for generating corresponding go code to execute them.
My table of items looks like this.
| ID | Name | Position |
|---|---|---|
| 105 | apple | 1 |
| 107 | ball | 2 |
| 110 | cat | 3 |
| 111 | dog | 4 |
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 ball, I would like the table to look like
| ID | Name | Position |
|---|---|---|
| 105 | apple | 1 |
| 110 | cat | 2 |
| 111 | dog | 3 |
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 -
-- GetItem: one
SELECT * from items WHERE id=?;
-- name: DeleteItem:execrows
DELETE FROM items WHERE id = ?;
-- name: UpdatePositions: execrows
UPDATE items SET position = position - 1
WHERE item.position > sqlc.arg(position);
And calling the functions shown -
item, _ := GetItem(id)
_, _ := DeleteItem(id)
_, _ := UpdatePositions(item.position)
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 -
- Can I execute the DELETE and UPDATE commands using a single generated function, which sqlc understands? So, execute two SQL statements with one generated function?
- Can I omit the
GetItemcall by writing a single SQL statement to get and update item positions?
I tried writing an update command which selects the target widget and gets its position, and updates the rows with greater positions than that. But it resulted in an sqlc error.