CREATE OR REPLACE FUNCTION cleanInstances(tid INT, bpel_inst_state INT)
RETURNS void AS $$
BEGIN

	CREATE TABLE TEMP_CLEAN_INS AS SELECT ID FROM ODE_PROCESS_INSTANCE WHERE INSTANCE_STATE = bpel_inst_state AND ID = tid;
	CREATE TABLE TEMP_CLEAN_SCOPE AS SELECT os.SCOPE_ID FROM ODE_SCOPE os INNER JOIN TEMP_CLEAN_INS tc ON os.PROCESS_INSTANCE_ID = tc.ID;
	CREATE TABLE TEMP_CLEAN_MEX AS SELECT mex.MESSAGE_EXCHANGE_ID FROM ODE_MESSAGE_EXCHANGE mex INNER JOIN TEMP_CLEAN_INS tc ON mex.PROCESS_INSTANCE_ID = tc.ID;
	DELETE FROM ODE_EVENT AS o USING TEMP_CLEAN_INS AS tc WHERE o.INSTANCE_ID = tc.ID;
	DELETE FROM ODE_CORSET_PROP WHERE CORRSET_ID IN ( SELECT cs.CORRELATION_SET_ID FROM ODE_CORRELATION_SET cs INNER JOIN TEMP_CLEAN_SCOPE ts ON cs.SCOPE_ID = ts.SCOPE_ID);
	DELETE FROM ODE_CORRELATION_SET AS cs USING TEMP_CLEAN_SCOPE ts WHERE cs.SCOPE_ID = ts.SCOPE_ID;
	DELETE FROM ODE_PARTNER_LINK AS cs USING TEMP_CLEAN_SCOPE ts WHERE cs.SCOPE_ID = ts.SCOPE_ID;
	DELETE FROM ODE_XML_DATA_PROP WHERE XML_DATA_ID IN ( SELECT xd.XML_DATA_ID FROM ODE_XML_DATA xd INNER JOIN TEMP_CLEAN_SCOPE ts ON xd.SCOPE_ID = ts.SCOPE_ID);
	DELETE FROM ODE_XML_DATA AS cs USING TEMP_CLEAN_SCOPE ts WHERE cs.SCOPE_ID = ts.SCOPE_ID;
	DELETE FROM ODE_SCOPE AS o USING TEMP_CLEAN_INS tc WHERE o.PROCESS_INSTANCE_ID = tc.ID;
	DELETE FROM ODE_MEX_PROP AS om USING TEMP_CLEAN_MEX tc WHERE om.MEX_ID= tc.MESSAGE_EXCHANGE_ID;
	DELETE FROM ODE_MESSAGE AS om USING TEMP_CLEAN_MEX tc WHERE om.MESSAGE_EXCHANGE_ID = tc.MESSAGE_EXCHANGE_ID;
	DELETE FROM ODE_MESSAGE_EXCHANGE AS mex USING TEMP_CLEAN_INS tc WHERE mex.PROCESS_INSTANCE_ID = tc.ID;
	DELETE FROM ODE_MESSAGE_ROUTE AS mr USING TEMP_CLEAN_INS tc WHERE mr.PROCESS_INSTANCE_ID = tc.ID;
	DELETE FROM ODE_PROCESS_INSTANCE AS o USING TEMP_CLEAN_INS tc WHERE o.ID = tc.ID;
	DROP TABLE TEMP_CLEAN_INS;
	DROP TABLE TEMP_CLEAN_SCOPE;
	DROP TABLE TEMP_CLEAN_MEX;

END;
$$
LANGUAGE plpgsql;

BEGIN;
--deletes given bpel instance
--instance id to be removed - ex: 0
--default instance state to delete - 30

SELECT cleanInstances(0, 30);
COMMIT;
