Question

With Oracle is it possible to (with a single database connection):

  1. lock a single row (row1)
  2. then lock another row (row2)
  3. release the lock on row1 (retaining the lock on row2)
  4. obtain a lock on another row (row3)
  5. release the lock on row2 (retaining the lock on row3)
  6. release the lock on row3

I realize Oracle supports many different kinds of locks (I've found this very helpful: http://broadh2o.net/docs/database/oracle/oracleLocks.html ), so perhaps the answer depends on which kind of locks are chosen. I'm interested in exclusive locks - i.e. locks which prevent other connections from updating the row.

I would like to know if I can perform operations 1-6 using a single database connection. I certainly could use a separate database connection for each row. It seems that locks are released using COMMIT/ROLLBACK, so that would suggest releasing the lock on a single row isn't possible.

Was it helpful?

Solution

You cannot selectively release locks on rows. Once you lock row1, that lock will only be released at the end of your transaction. But the end of your transaction will also release any other locks held by your transaction (i.e. the lock on row2).

Depending on the business problem you are trying to solve, potentially you don't really want to lock individual rows. Potentially, you want to use the dbms_lock package to acquire and release some user-defined locks. If you have user-defined locks lock1, lock2, and lock3, then you could acquire and release the three locks just as you've outlined within a single transaction. Setting up user-defined locking, however, can be quite dangerous both because it requires a lot more work from developers who have to protect the right sections of their code with the appropriate locks and because it is possible to request a user-defined lock that will not be released when a transaction commits or is rolled back which makes it possible to really shoot yourself in the foot if you don't handle your exceptions correctly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top