Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1piKWs-0004XB-1X for pgsql-general@arkaria.postgresql.org; Fri, 31 Mar 2023 19:35:18 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1piKWq-0007IZ-Uh for pgsql-general@arkaria.postgresql.org; Fri, 31 Mar 2023 19:35:16 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1piKWq-0007IQ-Fq for pgsql-general@lists.postgresql.org; Fri, 31 Mar 2023 19:35:16 +0000 Received: from mail-pl1-x631.google.com ([2607:f8b0:4864:20::631]) by magus.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (Exim 4.94.2) (envelope-from ) id 1piKWn-0007sh-At for pgsql-general@lists.postgresql.org; Fri, 31 Mar 2023 19:35:15 +0000 Received: by mail-pl1-x631.google.com with SMTP id kc4so22230514plb.10 for ; Fri, 31 Mar 2023 12:35:12 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=yugabyte.com; s=google; t=1680291311; h=to:cc:date:message-id:subject:mime-version:from:from:to:cc:subject :date:message-id:reply-to; bh=mRkIX9MJH3ijwFugpj1aTZjf1CcUrLFab/Y00t0H3WY=; b=RnrqljB2CERwPcC8+eDNe7dzzxepzIs8iVIsryxyVf3ab2U6f/er7ENVRw123OgNIY V/I9YDF7IiF6aR3zNa4XFQn+RNX3TK5XMnkMqfnmFSkScR9PClQ5dMfV1Aws2xyZICXB 4RpOoIdQ4EHVpphehtrnjaDLczdaew+lxVMio= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; t=1680291311; h=to:cc:date:message-id:subject:mime-version:from:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=mRkIX9MJH3ijwFugpj1aTZjf1CcUrLFab/Y00t0H3WY=; b=YxYbfvtnNpI+sfAFZxtvTq8+o6mhDIpckxeuCekvgz+TftLxXrrmbDSuhg25uWpKH6 ixDY3XL/7EnN6GvlfFEEzZ6F94bmwgQJbBj3xUxnhh8fiplwcTFjMIb6wll6h3zu4DYp 0UVwghcLGDrXzICFbqDrLI3aJZDiJv6nEH9QPXBMUT7I5XC+pIj2JEtslGVvsAbg+xzM Bfg4JTJAKXmnhpg8TNw+wRGLR84doM7vE7Ki6DM48V8BP0W0I55ISIBtMd1xv2CIwSUS HAKTT7Y0eZlZXClqmAPo4y+qYgHhBZHmaPhKHhQlEHRHn/EST6DpdpkfnSuLBSmlCkMU VRnQ== X-Gm-Message-State: AAQBX9cvv7JOE7YzSEiTdIwRTXFOYcrx6I/c7fGzhqVUtXDQYKzZJLOx PqRkAz3mGL6vcXVLLxfLLJJzvr/RWv5Fknamc/0= X-Google-Smtp-Source: AKy350bzvGLLWSvUgjem6LyS8bPa+t71QQOYDNWW0IDuN4fsJmUMSilSjidYcptbiZUCyZcXEuLfTw== X-Received: by 2002:a17:90b:3811:b0:23b:3d6e:1ed with SMTP id mq17-20020a17090b381100b0023b3d6e01edmr30854488pjb.13.1680291310549; Fri, 31 Mar 2023 12:35:10 -0700 (PDT) Received: from smtpclient.apple ([2601:646:101:7fda:451b:f395:1620:c6d3]) by smtp.gmail.com with ESMTPSA id r17-20020a170902e3d100b001a076025715sm1927907ple.117.2023.03.31.12.35.09 (version=TLS1_2 cipher=ECDHE-ECDSA-AES128-GCM-SHA256 bits=128/128); Fri, 31 Mar 2023 12:35:10 -0700 (PDT) From: Bryn Llewellyn Content-Type: multipart/alternative; boundary="Apple-Mail=_FF3B6181-7365-4DD9-82D7-885949540C30" Mime-Version: 1.0 (Mac OS X Mail 14.0 \(3654.120.0.1.14\)) Subject: My tests show that a WITH HOLD cursor has subtly different semantics from a WITHOUT HOLD cursor Message-Id: <76A5F3E1-DB5F-4DA7-AF29-687D511E3948@yugabyte.com> Date: Fri, 31 Mar 2023 12:35:08 -0700 Cc: laurenz.albe@cybertec.at To: pgsql-general list X-Mailer: Apple Mail (2.3654.120.0.1.14) List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk --Apple-Mail=_FF3B6181-7365-4DD9-82D7-885949540C30 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset=utf-8 *Summary* My tests show that, when a WITHOUT HOLD cursor has to cache results (see = Note 1), then the WHERE clause (if present) is stripped off the cursor's = defining SELECT statement and the entire unrestricted result set is = cached. But when a WITH HOLD cursor is used, then it=E2=80=99s the = *restricted* result set that=E2=80=99s cached. I do see that this wouldn't have a detectable effect when the cursor's = defining query doesn't involve any volatile functions. But it does seem = that too much data is cached in the "not holdable" case=E2=80=94and this = seems to be a bad thing for space use and for speed. I'd like to know the rationale for this design choice but I've been = unable to find any mention of it in the PG doc (see Note 2). My test design used this statement: select v from rndm_series() [where rndm_filter()] And I used a trivial table function "cursor_rows()=E2=80=9D that simply = iterated over all the rows that the cursor defined, from first through = last, to display the cursor's result set three times in succession. This lead to four runs: "WITH or WITHOUT HOLD" by "with or without the = WHERE clause". I might just as well have used a simple "series()" function wrapped = around "generate_series()" that used "raise info" to report that it was = called together with a simple "filter()" function that always returned = true and, again, that used "raise info" to report that it was called. = But I find it too hard to divert "raise info" output to a spool file and = have it interleave properly with regular SQL output. So I used a = volatile "rndm_series() that always returned ten rows but (using the = random() built-in function) produced a different set of values on each = call. And I used a volatile "rndm_filter()" function that similarly = randomly returned TRUE or FALSE. These devices dramatized the effect I'm = that reporting here and made it simple to record the results ordinarily = with the \o meta-command. I'm assuming that my PL/pgSQL functions are opaque to the planner and so = that it cannot run the execution plan in backwards order and must, = therefore, cash the cursor's result set. I would have expected the *restricted* result set to be cached for both = flavors of cursor=E2=80=94holdable and not. After all, we're taught to = expect nonsense results when a volatile function's results are = cached=E2=80=94so a cursor should be no different w.r.t. this thinking. (Of course, I've read the CAUTION in the PG doc for the DECLARE = statement that says =C2=AB Scrollable cursors may give unexpected = results if they invoke any volatile functions =C2=BB and I wouldn't use = a volatile function in real life.) = =E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2= =80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80= =94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94= =E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94 *Note 1* I read Laurenz's blogpost "WITH HOLD cursors and transactions in = PostgreSQL" = (www.cybertec-postgresql.com/en/with-hold-cursors-and-transactions-in-post= gresql/) and I noted this: =C2=AB [Some] execution plans [for a WITHOUT HOLD cursor] require the explicit = keyword SCROLL for the cursor to become scrollable. Such cursors incur = an overhead, because the server must cache the entire result set. =C2=BB and then this: =C2=AB PostgreSQL must calculate the complete result set [for a WITH HOLD = cursor] at COMMIT time and cache it on the server. =C2=BB In other words, both a WITH HOLD cursor (always) and a WITHOUT HOLD = cursor (sometimes) must cache the entire result set. = =E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2= =80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80= =94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94= =E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94 *Note 2* Laurenz also wrote this in the "Is the PL/pgSQL refcursor useful in a = modern three-tier app?" thread that I started: =C2=AB I understand your confusion, and I believe that the documentation could = be improved... I personally find that reading the PostgreSQL = documentation gets you far, but only so far: for deep understanding, you = have to read the code... I have come to see it as an extension of the = documentation that covers the details. =C2=BB = =E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2= =80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80= =94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94= =E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94 *Testcase* I used PG Version 15.2. The code that follows is self-contained. You = need just to connect as an ordinary user to a database where it has the = CREATE privilege. Copy it into, say, "t.sql" and start it in psql. (Make = sure that you have the usual =C2=AB AUTOCOMMIT =3D 'on' =C2=BB setting.) \c :db :u1 drop schema if exists s1 cascade; create schema s1; set search_path =3D s1, pg_catalog, pg_temp; create procedure init_rndm() set search_path =3D pg_catalog, pg_temp language plpgsql as $body$ begin perform setseed(0.0::double precision); end; $body$; create function rndm_filter() returns boolean set search_path =3D pg_catalog, pg_temp language sql as $body$ select (random() > 0.7::float8); $body$; -- Ensure that the planner cannot know how the rows are delivered. create function rndm_series() returns table(v int) set search_path =3D s1, pg_catalog, pg_temp language plpgsql as $body$ declare val int not null :=3D 0; ctr int not null :=3D 0; begin loop val :=3D val + 1; if (random() > 0.9::float8) then ctr :=3D ctr + 1; exit when ctr > 10; v :=3D val; return next; end if; end loop; end; $body$; create procedure open_holdable_cursor(holdable in boolean, filter_series = in boolean, caption inout text) language plpgsql as $body$ declare cur constant refcursor not null :=3D 'cur'; without_filter constant text not null :=3D 'declare cur scroll cursor without hold for '|| 'select v from rndm_series()'; with_filter constant text not null :=3D without_filter||' where rndm_filter()'; without_filter_holdable constant text not null :=3D replace(without_filter, 'without', 'with'); with_filter_holdable constant text not null :=3D replace(with_filter, 'without', 'with'); begin begin close cur; exception when invalid_cursor_name then null; end; case holdable when false then case filter_series when false then execute without_filter; when true then execute with_filter; end case; when true then case filter_series when false then execute without_filter_holdable; when true then execute with_filter_holdable; end case; end case; declare holdable text not null :=3D ''; stmt text not null :=3D ''; begin select case is_holdable when true then 'with hold' when false then 'without hold' end, statement into holdable, stmt from pg_cursors where name =3D 'cur'; stmt :=3D replace(stmt, ' without hold', ''); stmt :=3D replace(stmt, ' with hold', ''); stmt :=3D replace(stmt, 'declare cur scroll cursor for ', ''); caption :=3D rpad(holdable||':', 14)||stmt; end; end; $body$; create function cursor_rows() returns table(z int) set search_path =3D s1, pg_catalog, pg_temp language plpgsql as $body$ declare cur constant refcursor not null :=3D 'cur'; begin move absolute 0 in cur; loop fetch next from cur into z; exit when not found; return next; end loop; end; $body$; = --------------------------------------------------------------------------= ------ \t on \o spool.txt start transaction; call init_rndm(); call open_holdable_cursor(false, false, ''); select z from cursor_rows(); select z from cursor_rows(); select z from cursor_rows(); rollback; start transaction; call init_rndm(); call open_holdable_cursor(false, true, ''); select z from cursor_rows(); select z from cursor_rows(); select z from cursor_rows(); rollback; call init_rndm(); call open_holdable_cursor(true, false, ''); select z from cursor_rows(); select z from cursor_rows(); select z from cursor_rows(); call init_rndm(); call open_holdable_cursor(true, true, ''); select z from cursor_rows(); select z from cursor_rows(); select z from cursor_rows(); \o \t off = --------------------------------------------------------------------------= ------ Here's what my "spool.txt" contained: without hold: select v from rndm_series() 9 34 35 39 40 47 91 101 136 137 9 34 35 39 40 47 91 101 136 137 9 34 35 39 40 47 91 101 136 137 without hold: select v from rndm_series() where rndm_filter() 9 91 9 34 39 47 91 35 136 137 with hold: select v from rndm_series() 9 34 35 39 40 47 91 101 136 137 9 34 35 39 40 47 91 101 136 137 9 34 35 39 40 47 91 101 136 137 with hold: select v from rndm_series() where rndm_filter() 9 91 9 91 9 91 = --------------------------------------------------------------------------= ------ --Apple-Mail=_FF3B6181-7365-4DD9-82D7-885949540C30 Content-Transfer-Encoding: quoted-printable Content-Type: text/html; charset=utf-8 *Summary*

My tests show that, when a WITHOUT HOLD = cursor has to cache results (see Note 1), then the WHERE clause (if = present) is stripped off the cursor's defining SELECT statement and = the entire unrestricted result set is cached. But when a WITH = HOLD cursor is used, then it=E2=80=99s the *restricted* result set = that=E2=80=99s cached.

I do see that this wouldn't have a detectable effect when the = cursor's defining query doesn't involve any volatile functions. But it = does seem that too much data is cached in the "not holdable" case=E2=80=94= and this seems to be a bad thing for space use and for speed.

I'd like to know the rationale for this design choice but = I've been unable to find any mention of it in the PG doc (see Note = 2).

My test = design used this statement:

select v from = rndm_series() [where rndm_filter()]
And I used a trivial table function = "cursor_rows()=E2=80=9D that simply iterated over all the rows that the = cursor defined, from first through last, to display the cursor's result = set three times in succession.

This lead to four runs: "WITH or = WITHOUT HOLD" by "with or without the WHERE clause".

I might just as well = have used a simple "series()" function wrapped around = "generate_series()" that used "raise info" to report that it was called = together with a simple "filter()" function that always returned true = and, again, that used "raise info" to report that it was called. But I = find it too hard to divert "raise info" output to a spool file and have = it interleave properly with regular SQL output. So I used a volatile = "rndm_series() that always returned ten rows but (using the random() = built-in function) produced a different set of values on each call. And = I used a volatile "rndm_filter()" function that similarly randomly = returned TRUE or FALSE. These devices dramatized the effect I'm that = reporting here and made it simple to record the results ordinarily with = the \o meta-command.

I'm assuming that my PL/pgSQL functions are opaque to the = planner and so that it cannot run the execution plan in backwards order = and must, therefore, cash the cursor's result set.

I would have expected = the *restricted* result set to be cached for both flavors of = cursor=E2=80=94holdable and not. After all, we're taught to expect = nonsense results when a volatile function's results are cached=E2=80=94so = a cursor should be no different w.r.t. this thinking.

(Of = course, I've read the CAUTION in the PG doc for the = DECLARE statement that says =C2=AB Scrollable cursors may give = unexpected results if they invoke any volatile functions =C2=BB and I = wouldn't use a volatile function in real life.)
=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94= =E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2= =80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80= =94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94

*Note = 1*

I read Laurenz's blogpost "WITH HOLD = cursors and transactions in PostgreSQL" (www.cybertec-postgresql.com/en/with-hold-cursors-and-transa= ctions-in-postgresql/) and I noted this:

=C2=AB
[Some] execution plans [for a WITHOUT = HOLD cursor] require the explicit keyword SCROLL for the cursor to = become scrollable. Such cursors incur an overhead, because the = server must cache the entire result set.
=C2=BB

and then this:

=C2=AB
PostgreSQL must calculate the complete = result set [for a WITH HOLD cursor] at COMMIT time and cache it on the = server.
=C2=BB

In other words, both a WITH HOLD cursor = (always) and a WITHOUT HOLD cursor (sometimes) must cache the entire = result set.
=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94= =E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2= =80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80= =94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94

*Note 2*

Laurenz also wrote this in the "Is the PL/pgSQL refcursor = useful in a modern three-tier app?" thread that I started:

=C2=AB
 I understand your = confusion, and I believe that the documentation could be improved... I = personally find that reading the PostgreSQL documentation gets you = far, but only so far: for deep understanding, you have to read the = code... I have come to see it as an extension of the documentation = that covers the details.
=C2=BB
=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94= =E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2= =80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80= =94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94=E2=80=94

*Testcase*

I used PG Version 15.2. The code that = follows is self-contained. You need just to connect as an ordinary user = to a database where it has the CREATE privilege. Copy it into, say, = "t.sql" and start it in psql. (Make sure that you have the usual = =C2=AB AUTOCOMMIT =3D 'on' =C2=BB setting.)

\c :db :u1

drop schema if = exists s1 cascade;
create schema s1;
set search_path =3D s1, = pg_catalog, pg_temp;

create procedure = init_rndm()
  set search_path =3D pg_catalog, pg_temp
  language plpgsql
as $body$
begin
  perform = setseed(0.0::double precision);
end;
$body$;

create function = rndm_filter()
  returns boolean
  set search_path =3D = pg_catalog, pg_temp
  language sql
as $body$
  select (random() > = 0.7::float8);
$body$;

-- Ensure that the planner cannot = know how the rows are delivered.
create function = rndm_series()
  returns table(v int)
  set search_path =3D = s1, pg_catalog, pg_temp
  language plpgsql
as $body$
declare
  val int not null :=3D = 0;
  ctr int not null :=3D 0;
begin
  loop
  =   val :=3D val + 1;
    if (random() = > 0.9::float8) then
      ctr :=3D ctr + 1;
    =   exit when ctr > 10;
      v :=3D = val; return next;
    end if;
  end loop;
end;
$body$;

create procedure open_holdable_cursor(holdable in boolean, = filter_series in boolean, caption inout text)
  language = plpgsql
as $body$
declare
  cur constant refcursor not null :=3D = 'cur';

  without_filter constant text not null = :=3D
   'declare cur scroll cursor without hold for = '||
   'select v from rndm_series()';

  with_filter constant text not null :=3D
  =  without_filter||' where rndm_filter()';

  without_filter_holdable constant text not null = :=3D
    replace(without_filter, 'without', = 'with');

  with_filter_holdable constant text not = null :=3D
    replace(with_filter, 'without', = 'with');
begin
  begin
    close = cur;
  exception when invalid_cursor_name then
  =   null;
  end;

  case = holdable
    when false then
      case = filter_series
        when false = then   execute without_filter;
      =   when true  then   execute = with_filter;
      end case;

  =   when true then
      case filter_series
    =     when false then   execute = without_filter_holdable;
        when = true  then   execute = with_filter_holdable;
      end case;
  end = case;

  declare
    holdable text = not null :=3D '';
    stmt     text not null = :=3D '';
  begin
  =   select
      case is_holdable
    =     when true  then 'with hold'
    =     when false then 'without hold'
    =   end,
      statement
    into holdable, = stmt
    from pg_cursors where name =3D = 'cur';

    stmt :=3D replace(stmt, ' without = hold', '');
    stmt :=3D replace(stmt, ' with hold', = '');
    stmt :=3D replace(stmt, 'declare cur = scroll cursor for ', '');
    caption :=3D rpad(holdable||':', = 14)||stmt;
  end;
end;
$body$;

create function = cursor_rows()
  returns table(z int)
  set search_path =3D = s1, pg_catalog, pg_temp
  language plpgsql
as $body$
declare
  cur constant refcursor = not null :=3D 'cur';
begin
  move absolute 0 in cur;
  loop
    fetch next from cur into = z;
 =   exit when not found;
    return = next;
  end loop;
end;
$body$;
---------------------------------------------------------------= -----------------

\t on
\o spool.txt

start transaction;
  call = init_rndm();
  call open_holdable_cursor(false, false, = '');
  select z from cursor_rows();
  select = z from cursor_rows();
  select z from cursor_rows();
rollback;
start transaction;
  call = init_rndm();
  call open_holdable_cursor(false, true, = '');
  select z from cursor_rows();
  select = z from cursor_rows();
  select z from cursor_rows();
rollback;
call init_rndm();
call open_holdable_cursor(true, = false, '');
select z from cursor_rows();
select z from = cursor_rows();
select z from cursor_rows();

call = init_rndm();
call open_holdable_cursor(true, true, '');
select z from = cursor_rows();
select z from cursor_rows();
select z from = cursor_rows();

\o
\t off

---------------------------------------------------------------= -----------------

Here's what my "spool.txt" contained:

 without = hold: select v from rndm_series()

  =  9
  34
  35
  39
  40
  47
  91
 101
 136
 137

   9
  34
  35
  39
  40
  47
  91
 101
 136
 137

   9
  34
  35
  39
  40
  47
  91
 101
 136
 137

 without hold: select v from rndm_series() where = rndm_filter()

  9
 91

  9
 34
 39
 47
 91

  35
 136
 137

 with hold:    select v from = rndm_series()

   9
  34
  35
  39
  40
  47
  91
 101
 136
 137

   9
  34
  35
  39
  40
  47
  91
 101
 136
 137

   9
  34
  35
  39
  40
  47
  91
 101
 136
 137

 with hold:    select v from = rndm_series() where rndm_filter()

  9
 91

  9
 91

  9
 91


---------------------------------------------------------------= -----------------

= --Apple-Mail=_FF3B6181-7365-4DD9-82D7-885949540C30--