--
-- ### Verification of several modifying queries
-- 
--


create table a_sysres ( resid int, instid int);
create table a_sapinst (  instid int, instname string(10));
create table a_sysinst ( instid int, sysid int);
create table a_system ( sysid int, sysname string(10));


drop if exists procedure loadData;
@
create procedure loadData()
begin

   delete from a_system;
   insert into a_system values ( 1, 'SYSA');
   insert into a_system values ( 2, 'SYSB');

   delete from a_sysinst;
   insert into a_sysinst values ( 1, 1);
   insert into a_sysinst values ( 2, 1);
   insert into a_sysinst values ( 3, 1);
   insert into a_sysinst values ( 4, 1);

   delete from a_sapinst;
   insert into a_sapinst values ( 1, 'SAP1');
   insert into a_sapinst values ( 2, 'SAP2');
   insert into a_sapinst values ( 3, 'SAP3');
   insert into a_sapinst values ( 4, 'SAP3');

   delete from a_sysres;
   insert into a_sysres values ( 1, 1 );
end;
@

drop if exists procedure checkMod001;
@
create procedure checkMod001(msg out string(20)) return string(10)
begin

   var res string(10) = 'ERROR';
   var sysid int;

   var numinst int;
   var numsapinst int;
   var numsysres int;
   var numsys int;
   
   :sysid = 1;

   -- delete with nested subselect, since one var reference, should be NOT cached
   delete from a_sysres where instid in ( select instid from a_sysinst where sysid = :sysid );
   -- delete with nested static subselect, should be cached ( not really useful, just for cache testing )
   delete from a_sapinst where instid in ( select instid from a_sysinst where sysid = 1 );
   delete from a_sysinst where sysid = :sysid;
   delete from a_system where sysid = :sysid;

   :numinst = ( select count(*) from a_sysinst );
   :numsapinst = ( select count(*) from a_sapinst );
   :numsysres = ( select count(*) from a_sysres );
   :numsys = ( select count(*) from a_system );

   if :numinst = 0 and :numsapinst = 0 and :numsysres = 0 and :numsys = 1
   then
	:res = 'ok';
   end;

   :msg = 'Delete with sub select in condition';
   return :res;
end;
@

drop if exists procedure checkMod002;
@
create procedure checkMod002(msg out string(20)) return string(10)
begin

   var res string(10) = 'ERROR';
   var sysid int;
   
   :sysid = 1;

   update a_system set sysid = sysid + 1 where sysid = 1 return :sysid = sysid;
   
   if :sysid = 2
   then
	:res = 'ok';
   end;

   :msg = 'Update with return';
   return :res;
end;
@


call loadData();
:r = call checkMod001(:msg);
insert into checklog values ('GATE-D', :msg, :r);

call loadData();
:r = call checkMod002(:msg);
insert into checklog values ('GATE-D', :msg, :r);


drop procedure loadData;
drop procedure checkMod001;
drop procedure checkMod002;

drop if exists table a_sysres;
drop if exists table a_sapinst;
drop if exists table a_sysinst;
drop if exists table a_system;




