I have a simple table with a primary key. Most of the read operations fetch one row by the exact value of the key.
The data in each row maintains some relationship with rows before and after it in the key order. So when I insert a new row I need to read the 2 rows between which it is going to enter, make some computation and then to insert.
The concern, clearly, is that at the same time another connection may add a row with a key value in the same interval. I am covered if it is exactly the same value of the key as the second insert would fail, but if the key value is different but in the same interval the relationship may be broken.
The solution seems to be to lock the whole table for writing when I decide to add a new row, or (if possible, which I doubt) to lock an interval of key values. Yet I'd prefer that read-only transactions would not be blocked at that time.
I am using ODBC with libodbc++ wrapper for C++ in the client program and IBM DB2 free edition (although the DB choice may still change). This is what I thought of doing:
- start the connection in the auto-commit and default isolation mode
- when need to add a new row, set auto-commit to false and isolation mode to serialized
- read the rows before and after the new key value
- compute and insert the new row
- commit
- return back to the auto-commit and default isolation mode
Will this do the job? Will other transactions be allowed to read at the same time? Are there other/better ways to do it?
BTW, I don't see in the libodbc++ i/f a way to specify a read-only transaction. Is it possible in odbc?
EDIT: thanks for the very useful answers, I had trouble selecting one.