\set ON_ERROR_STOP on

CREATE EXTENSION IF NOT EXISTS xml2;

CREATE OR REPLACE FUNCTION pg_temp.vmrss_kb()
RETURNS integer
LANGUAGE sql
AS $$
  SELECT ((regexp_match(
             pg_read_file('/proc/' || pg_backend_pid() || '/status'),
             'VmRSS:[[:space:]]+([0-9]+)[[:space:]]+kB'
         ))[1])::integer;
$$;


CREATE TEMP TABLE xml2_leak_table_doc AS
SELECT 1 AS id,
       '<doc>' ||
       string_agg('<n>' || repeat(md5(g::text), 64) || '</n>', '') ||
       '</doc>' AS doc
FROM generate_series(1, 256) AS g;

DO $$
DECLARE
    before_rss bigint;
    after_rss  bigint;
    diff       bigint;
BEGIN
    FOR i IN 1..10 LOOP
        before_rss := pg_temp.vmrss_kb();
        PERFORM count(*)
        FROM xpath_table('id', 'doc', 'xml2_leak_table_doc',
                         '/doc/n/text()', 'true') AS t(id int, value text);
        after_rss := pg_temp.vmrss_kb();
        diff := after_rss - before_rss;
        RAISE NOTICE 'xpath_table i=%, total_kb=%, diff_kb=%',
                     i, after_rss, diff;
    END LOOP;
END $$;
