\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_xslt_process_doc AS
SELECT '<doc/>' AS doc,
       '<foo>' ||
       string_agg('<bar attr="value">payload</bar>', '') ||
       '</foo>' AS bad_xsl
FROM generate_series(1, 20000) AS g;

DO $$
DECLARE
    before_rss bigint;
    after_rss  bigint;
    diff       bigint;
    failures   integer;
    errcode    text;
    calls_per_round constant integer := 1;
BEGIN
    FOR i IN 1..10 LOOP
        before_rss := pg_temp.vmrss_kb();
        failures := 0;

        FOR j IN 1..calls_per_round LOOP
            BEGIN
                PERFORM xslt_process(doc, bad_xsl)
                FROM xml2_xslt_process_doc;
            EXCEPTION WHEN others THEN
                GET STACKED DIAGNOSTICS errcode = RETURNED_SQLSTATE;
                IF errcode <> '10608' THEN
                    RAISE;
                END IF;
                failures := failures + 1;
            END;
        END LOOP;

        after_rss := pg_temp.vmrss_kb();
        diff := after_rss - before_rss;
        RAISE NOTICE 'xslt_process i=%, failures=%, total_kb=%, diff_kb=%',
                     i, failures, after_rss, diff;
    END LOOP;
END $$;
