-- Initialize a temporary table with 1000 rows and a gist index.
CREATE TEMPORARY TABLE tt (a integer);
CREATE INDEX i_tt ON tt USING gist (a);
INSERT INTO tt SELECT generate_series(1,1000);

-- Fetch n tuples from "tt", and write them to table called "resultset"
CREATE OR REPLACE FUNCTION fetchfunc(n int) RETURNS bool AS $$
declare
  r record;
  c refcursor;
begin
  c:= 'foocur';
  FOR i IN 1..n LOOP
    FETCH FROM c INTO r;
    IF r IS NULL THEN RETURN true; END IF;
    INSERT INTO resultset VALUES (r.a);
  END LOOP;
  RETURN false;
end;
$$ LANGUAGE plpgsql;

-- ensure that we use a plain index scan.
set enable_bitmapscan=off;
set enable_seqscan=off;

CREATE TEMPORARY TABLE resultset (a integer);

-- Fetch all rows from tt into resultset, with no inserts in the middle
BEGIN;
DECLARE  foocur CURSOR FOR SELECT a FROM tt WHERE a > 100;
SELECT fetchfunc(100);
SELECT fetchfunc(1000);
COMMIT;
SELECT COUNT(*) FROM resultset; -- Display result

truncate resultset;

-- Do the same, but insert new tuples in the middle of the scan. The result
-- should be the same.
BEGIN;
DECLARE  foocur CURSOR FOR SELECT a FROM tt WHERE a > 100;
SELECT fetchfunc(100);
INSERT INTO tt SELECT a% 10 FROM generate_series(1,1000) a;
SELECT fetchfunc(1000);
COMMIT;
SELECT COUNT(*) FROM resultset; -- Display result
