--
-- ### Explicit table locking for nested delete 
-- 



drop if exists table worker;
create table worker ( wkid int, wkname string(20) );

drop if exists table employment;
create table employment ( empid int, wkid int, empname string(20) );

drop if exists table empfee;
create table empfee  ( feeid int, empid int, amount decimal(10,2) );

insert into worker values ( 1, 'Worker A');
insert into worker values ( 2, 'Worker B');
insert into worker values ( 3, 'Worker C');

insert into employment values ( 1, 1, 'A job');
insert into employment values ( 2, 1, 'Another job');
insert into employment values ( 3, 2, 'A new job');
insert into employment values ( 4, 3, 'Your job');

insert into empfee values ( 1, 1, '101.99');
insert into empfee values ( 2, 2, '123.33');
insert into empfee values ( 3, 2, '464.78');


drop if exists procedure deleteEmployment;
@
create procedure deleteEmployment(empid in int)
begin
   delete from empfee where empid = :empid;
   delete from employment where empid = :empid;
end;
@

drop if exists procedure deleteWorker;
@
create procedure deleteWorker(wkid in int)
begin
   var empid int;


   -- we aquire an explicit exclusive lock since the cursor empCursor just 
   -- requests a shared lock and we want to perform a delete operation 
   -- in the cursor loop
 
   lock table employment;

   cursor empCur as select empid as empid from employment where wkid = :wkid;
   while fetch empCur into (:empid)
   begin
       deleteEmployment(:empid);
   end;
   close empCur;

   unlock table employment;

   delete from worker where wkid = :wkid;

exception when core_op
then

    unlock table employment;

end;
@

call deleteWorker(1);


