SET work_mem = '100MB';
DROP TABLE IF EXISTS data CASCADE;
CREATE TABLE data(data text);
CREATE FUNCTION leak_file() RETURNS SETOF data LANGUAGE plpgsql AS $$
DECLARE
    i int;
BEGIN
    FOR i IN 1..3 LOOP
        DECLARE
            r record;
        BEGIN
            -- make sure we need to extend a tempfile past one segment in a subtransaction
            FOR i IN 1..300000 LOOP
                r :=  ('('||repeat('quite a bit of stupid text', 100)||')')::data;
                RETURN NEXT r;
            END LOOP;
            RAISE EXCEPTION 'frakkedifrak';
        EXCEPTION WHEN others THEN
            RAISE NOTICE 'got exception %', sqlerrm;
        END;
    END LOOP;
END
$$

COPY (SELECT * FROM leak_file()) TO '/dev/null';
