我要求在postgresql中的指定时间限制内执行查询操作。如果查询未在该时间限制内执行,我们需要捕获异常/操作,并且需要终止阻止此查询操作发生的所有其他操作,并执行我们的升级操作。为此创建的原型如下:
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;
这里从服务器端调用函数时没有执行statement_timeout,但是从客户端调用它时它会被执行。是否还有其他方法可以使statement_timeout从服务器端调用工作,还是有其他方法在给定的时间限制内执行升级操作?
答案 0 :(得分:1)
确实无法在服务器功能中有效地更改statement_timeout
,必须在发送外部查询之前从客户端完成。
在DBA.SE上查看类似的问题: Why “SET LOCAL statement_timeout” does not work as expected with PostgreSQL functions?
或postgres邮件列表中的这个帖子,可追溯到2007年,但否定答案仍然适用于当前版本:
答案 1 :(得分:1)
确实无法在服务器功能中有效地更改statement_timeout
,必须在发送顶级查询之前在客户端完成。
在DBA.SE上查看类似的问题: Why “SET LOCAL statement_timeout” does not work as expected with PostgreSQL functions?
或postgres邮件列表中的这个帖子,可追溯到2007年,但否定答案仍然适用于当前版本: