Question

I have a situation where I must:

  1. Disable FK constraints for some tables,
  2. Change field values for primary keys which are referenced by foreign keys (which are also updated to match),
  3. Re-enable FK constraints from step 1.

The problem is that re-enabling the constraints in step 3 might fail if changes from step 2 done to primary key fields are not consistent with fields referenced by foreign keys. I'd like to catch that case and rollback the changes done in step 2. As far as I know, running a DDL statement like enabling a constraint would first issue a commit, after which I cannot rollback the changes made in step 2.

Is there any way to achieve this in one standalone script? The process should either completely pass or rollback as if nothing happened. Or is there an alternative to transactions which could revert to the previous state, without doing backup/restore of the whole database?

Was it helpful?

Solution

The way I'd work around this would be to lock each table before doing the update, run queries to manually check for any violations before re-enabling the constraint. If there are any violations you can rollback the update, otherwise the constraint re-enable will do the commit and release the table lock.

OTHER TIPS

You could try doing the DDL in an autonomous transaction. That way, it will be isolated from your DML. If the DDL fails, you could still rollback the DML. However, if the DDL has to "see" the uncommitted DML changes, then you're stuck. I don't think you can get where you want to go.

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