This is about storing commands in a database instead of a text file or spreadsheet. I am looking for a solution, which mimics the behavior of line numbers in a text editor.
E.g. Given the table below with the column "Order" as the primary key, when I delete the second row (Order = 2), I would end up with a gap in the order column (1, 3), which needs to be corrected to (1, 2)
| Order | Command | | Order | Command | | Order | Command |
|-------|--------------| |-------|--------------| |-------|--------------|
| 1 | CAM - ON | ==> | 1 | CAM - ON | ==> | 1 | CAM - ON |
| 2 | Turn left | | 3 | Take picture | | 2 | Take picture |
| 3 | Take picture |
I have already experimented with triggers. Before the record gets deleted, a trigger updates the relevant order numbers of the other records. I have also triggers to deal with appending or inserting a new record "before" an existing one.
I know the physical order on disk is different and irrelevant. So, I just manipulate the "Order" column to mimic the behaviour of line numbers.
The same works fine with updating records. E.g. if I want to "move" the "Turn left" command to the first position, implementing a trigger before update to reorder the other records does the trick too. E.g. set the order of the "Turn left" command to 1 and the trigger updates the other records first:
| Order | Command | | Order | Command |
|-------|--------------| |-------|--------------|
| 1 | CAM - ON | ==> | 2 | CAM - ON |
| 2 | Turn left | | 1 | Turn left |
| 3 | Take picture | | 3 | Take picture |
However, this one introduces a problem. Deleting or inserting a record triggers a procedure, which updates records, which now triggers the update procedure. This seems to make things recursive and complicated.
I tried to disable and enable the update trigger from within the other trigger procedures, but (in postgresl) this requires altering the table, which is not allowed during a query..
My question is: Is there a more straight forward solution, which covers all four CRUD Operations? Perhaps involving other data types for the order column instead of integer or completely different techniques?