I need some advice on a DB I’m working in.
I have the DB, and now I’m working on procedures, functions and triggers (PL/SQL). There are three entities, two of which inherit from the third one (as per the conceptual data model), so that means there are two tables referencing to the third one. I have to simultaneously insert data in the “parent” table and the “children” table, so I thought on making a procedure that inserted in the parent table, and another one that inserted in the child one, which can call the former one.
My problem is, what would happen if I tried to insert to the parent table, and then to the child one, and for some reason I’m inserting data in the child table that doesn’t satisfy the constraints? In other words, despite the constraints, do I still have to verify the input data in the function? What are your suggestions?
It depends.
Assuming there is a foreign key constraint between the child table and the parent table, if you try to insert a row in the child table using a key that does not exist in the parent table, the
INSERTwill throw an exception indicating that the constraint was violated. You don’t need to check anything if you simply want theINSERToperation to fail with a constraint violation exception.On the other hand, you may want to code validations in order to provide better exceptions to the caller. For example, it’s relatively common that a table will have multiple foreign keys that reference various other tables. It may be beneficial to check whether the parameters are valid so that you can tell the caller more specifically which parameter was invalid.
If you are asking how to ensure that either both the insert into the parent table and the insert into the child table succeed or that both fail, then you’re talking about how to establish proper transactional boundaries. You’d do something like
Note that your PL/SQL applications always have to explicitly either commit or rollback. And those transaction control statements should be at the highest level possible. You wouldn’t want to have transaction control statements in the
insert_into_parentprocedure, for example, because then you could never use the procedure if you wanted more extensive transaction scope.