Skip to content

Instantly share code, notes, and snippets.

@pwilken
Last active July 9, 2019 14:47
Show Gist options
  • Save pwilken/e8d51e3866434b1025668e3de309dc17 to your computer and use it in GitHub Desktop.
Save pwilken/e8d51e3866434b1025668e3de309dc17 to your computer and use it in GitHub Desktop.
Stored Function, cleanup postgresql queries.
create type query_datatype as (pid int, duration text, query text);
drop type query_datatype cascade;
drop function terminate_performance_killer();
create OR REPLACE FUNCTION terminate_performance_killer() RETURNS SETOF query_datatype
LANGUAGE plpgsql
AS $$
DECLARE
items query_datatype;
begin
drop table tabletemp;
create temp table tabletemp
( pid int,
duration text,
query text
);
insert into tabletemp select results.pid, results.duration, results.query from (
select pid, now() - pg_stat_activity.query_start AS duration, query, state
FROM pg_stat_activity
WHERE (now() - pg_stat_activity.query_start) > interval '5 minutes'
) as results;
FOR items IN SELECT * FROM tabletemp LOOP
RAISE NOTICE 'pid: %s, duration: %s, query: %s', items.pid, items.duration, items.query;
perform pg_terminate_backend(items.pid);
END LOOP;
return QUERY select pid, duration, query from tabletemp;
END;
$$;
select terminate_performance_killer();
@pwilken
Copy link
Author

pwilken commented Jul 9, 2019

Cronjob example

https://github.com/citusdata/pg_cron
SELECT cron.schedule('30 * * * *', 'terminate_performance_killer');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment