I write a UDF in PostgreSQL to test my index efficiency, like this
CREATE OR REPLACE PROCEDURE query()
LANGUAGE plpgsql
AS
$$
DECLARE
i int;
exp text;
temprow RECORD;
t timestamp;
cnt int;
sum int;
BEGIN
set max_parallel_workers_per_gather = 0;
set enable_seqscan = false;
drop table if exists query_ranges;
create table query_ranges(box boxndf, ts timestamp, te timestamp);
FOR i IN 1 .. 5000 LOOP
INSERT INTO query_ranges SELECT something;
END LOOP;
sum = 0;
t = clock_timestamp();
FOR temprow IN
SELECT * FROM query_ranges
LOOP
select count(*) from data_table where something into cnt;
sum = sum + cnt;
COMMIT;
END LOOP;
RAISE NOTICE '%', clock_timestamp() - t;
END;
$$;
However I find the memory usage keep growing and then I get a OOM. I guess the query select count(*) from data_table where something into cnt; may alloc some memory. If I simply run one query, the memory will soon be freed. But if I use this UDF, the memory is not freed between loops of queries.
Are there any way to free these allocated memory or avoid OOM?