I have a requirement to perform a query operation in a specified time limit in postgresql. If the query is not performed in that time limit, we need to catch a exception/a action and need to kill all other operations which are blocking this query operation to take place, and perform our upgrade operation. For this a prototype as been created as follows:
CREATE OR REPLACE FUNCTION execute_upgrade_statement(upgrade_stat text) RETURNS int as $$
BEGIN
EXECUTE upgrade_stat;
return 1;
END;
$$
LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION upgrade_function(upgrade_statement text,upgrading_table text) RETURNS void as $$
DECLARE
pid INTEGER;
return_value INTEGER;
pid_values INTEGER[];
BEGIN
SET statement_timeout TO 6000;
LOOP
BEGIN
select execute_upgrade_statement(upgrade_statement) into return_value;
if return_value = 1 THEN
raise notice 'Upgrade query performed';
return;
else
continue;
end if;
END;
END LOOP;
exception when query_canceled then
select into pid_values array_agg(p1.pid) from pg_locks p1 LEFT JOIN pg_stat_activity psa on p1.pid=psa.pid where p1.relation=(select relid from pg_stat_all_tables where relname=upgrading_table) and p1.pid <> pg_backend_pid();
FOREACH pid IN ARRAY pid_values
LOOP
raise notice 'pid value : %',pid;
perform pg_terminate_backend(pid);
END LOOP;
END;
$$
LANGUAGE plpgsql;
begin;
select upgrade_function('statement','table_name');
commit;
Here statement_timeout is not getting executed when function is called from server side, but it is getting executed when it is called from client side. Is there any other way to make statement_timeout work from server side call or is there any other way to perform my upgrade operation in given time limit ?