Last active
July 9, 2019 14:47
-
-
Save pwilken/e8d51e3866434b1025668e3de309dc17 to your computer and use it in GitHub Desktop.
Stored Function, cleanup postgresql queries.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cronjob example
https://github.com/citusdata/pg_cron
SELECT cron.schedule('30 * * * *', 'terminate_performance_killer');