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 1pf3pg-0007hM-GV for pgsql-general@arkaria.postgresql.org; Wed, 22 Mar 2023 19:09:12 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1pf3pf-0006U7-3N for pgsql-general@arkaria.postgresql.org; Wed, 22 Mar 2023 19:09:11 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1pf3pe-0006Tw-Em for pgsql-general@lists.postgresql.org; Wed, 22 Mar 2023 19:09:10 +0000 Received: from mail-pj1-x102d.google.com ([2607:f8b0:4864:20::102d]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.92) (envelope-from ) id 1pf3pa-0005zr-3k for pgsql-general@lists.postgresql.org; Wed, 22 Mar 2023 19:09:09 +0000 Received: by mail-pj1-x102d.google.com with SMTP id f6-20020a17090ac28600b0023b9bf9eb63so20106102pjt.5 for ; Wed, 22 Mar 2023 12:09:05 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=yugabyte.com; s=google; t=1679512145; h=references:to:cc:in-reply-to:date:subject:mime-version:message-id :from:from:to:cc:subject:date:message-id:reply-to; bh=LF1OnQAI46XT0HcFgYT724nfU5PvToJsXY9b9c5ru6o=; b=jJibBLc81tnafpAnaFim2zYJ6ICS7pni+Qgj9OYvA2lOkRFIG1WDTJ5UN0l0rnog5s g1VzulOqZhY58dJVysLAfBdhnp5bQ7Hd4ic92UPOKI0hPgjGROBDnpITqA3zv5Nrev89 y546FuhxwcwjbtymJxToy8p79o7+WXiu8l6Fk= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; t=1679512145; h=references:to:cc:in-reply-to:date:subject:mime-version:message-id :from:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=LF1OnQAI46XT0HcFgYT724nfU5PvToJsXY9b9c5ru6o=; b=3mmMZhtswsEJMPmuvbCUVzXmt7WC2bg8+GoZl5YgA99AbI2Oq+zmMKRoTdSmyjr61W +pycHbLdjWbnAscTU8vbbtgmK5Q0r3/r8pruKwfPZOmhcDTPbvqJbL4iB5cvfy6MhM2v /KZ1WF0ocLZmhEnpcfuAtuAftF4RJP57nDKw769HBeEtkAtLZ4RBA7DgHcYiEN1N0nMR 3mvd3dwHwS5EXHFrn0EpAZnLD9NVpkRjetR2aI/XoYIv+58kWpk1SZx/VYpoL/yEPpaU B7N70nMO4+G957OC+7b6kPFH+WB1BnNxOD4kzXEqimIJztWzU54Z+I5VBrD9r39OgKfI kHfw== X-Gm-Message-State: AO0yUKXcDLf0rxWlkb04K7Ys+C8uGvoHWamAtxexz3Y671LQZh5DQlgn t7U/oOP95exq/yJyBEpA1CjtWE7HoEOkaByWQL4= X-Google-Smtp-Source: AK7set+fcwsxVpwc4e03/GrHFh2DYFVvkYaT/nwOhwFfxEMDKERVTnUKEK2iiQzOGOwM040VvxQm8g== X-Received: by 2002:a17:903:d3:b0:1a0:549d:39a1 with SMTP id x19-20020a17090300d300b001a0549d39a1mr3441511plc.32.1679512144834; Wed, 22 Mar 2023 12:09:04 -0700 (PDT) Received: from smtpclient.apple ([2601:646:101:7fda:6191:a311:d556:7e6c]) by smtp.gmail.com with ESMTPSA id p6-20020a1709028a8600b00194c2f78581sm10909061plo.199.2023.03.22.12.09.03 (version=TLS1_2 cipher=ECDHE-ECDSA-AES128-GCM-SHA256 bits=128/128); Wed, 22 Mar 2023 12:09:04 -0700 (PDT) From: Bryn Llewellyn Message-Id: Content-Type: multipart/alternative; boundary="Apple-Mail=_9E8A9FC5-D170-4BD8-9498-ACA8A4BE8589" Mime-Version: 1.0 (Mac OS X Mail 14.0 \(3654.120.0.1.14\)) Subject: Re: Is the PL/pgSQL refcursor useful in a modern three-tier app? Date: Wed, 22 Mar 2023 12:09:03 -0700 In-Reply-To: <793675c6b0521c127044ac5b557d98154fcfc7c5.camel@cybertec.at> Cc: Adrian Klaver , pgsql-general list To: Laurenz Albe References: <6A73AAEA-7A9F-42C9-A842-88213FA41003@yugabyte.com> <1C63744C-F4B2-44AB-B9EF-3564D2B04049@yugabyte.com> <898378b8-f60a-8b27-31f6-83882040f5b6@aklaver.com> <58b2a298-9cad-47dc-1d07-0601588553c1@aklaver.com> <8659357C-1DC6-4EB7-9451-3ECB04E6E67D@yugabyte.com> <793675c6b0521c127044ac5b557d98154fcfc7c5.camel@cybertec.at> 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=_9E8A9FC5-D170-4BD8-9498-ACA8A4BE8589 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset=utf-8 > laurenz.albe@cybertec.at wrote: >=20 > ...I understand that you ask questions to gain deeper understanding. >=20 >> bryn@yugabyte.com wrote: >>=20 >> ...I had never come across use cases where [scrollability] was = beneficial. I wanted, therefore, to hear about some. I thought that = insights here would help me understand the mechanics. >=20 > I recently used cursor scrollability, so I can show you a use case: >=20 > = github.com/cybertec-postgresql/db_migrator/blob/master/db_migrator--1.0.0.= sql#L49 >=20 > The goal is to get the query result count right away, without having = to run a second query for it: you declare the cursor, move to the end of = the result set, fetch the ROW_COUNT, then move back to the beginning of = the result set and start fetching the result rows. >=20 > ...I personally find that reading the PostgreSQL documentation gets = you far, but only so far: for deep understanding, you have to read the = code. It is usually well > documented and readable, and I have come to see it as an extension of = the documentation that covers the details. Thanks for the link to your SQL file at the line where you get the row = count in the way that you describe. I saw that this is in the PL/pgSQL = source text for function "materialize_foreign_table()" (~200 lines). And = I saw that you use the cursor mechanism that we're discussing here in = only one other function, "db_migrate_refresh()" (~480 lines). But this = second one doesn't use the "move forward all" device to get a row count. = I looked only at these two functions. I noted that neither of these functions has a refcursor formal argument = and that, rather, you open (i.e. create) each of the three cursors that = you use within the two functions that uses them. I noted, too, that for = the three "select" statements that you use to open your refcursors, none = of these has an "order by". I noted that your code implements "create = table destination" and "insert into destination... select from = source..." where order doesn't matter.=20 However, source code famously reveals only what it does and not what the = author's intention, and overall design philosophy, is. I looked at the = README accounts for these two functions here: github.com/cybertec-postgresql/db_migrator#materialize_foreign_table github.com/cybertec-postgresql/db_migrator#db_migrate_refresh But these accounts say nothing about the design of their = implementations. The accounts, and the bigger picture, seem to imply = that read consistency in the presence of concurrent activity from other = sessions is not a concern. I'm guessing that this is accounted for = upstream from how the code that I'm looking at operates=E2=80=94i.e. = that the source database is extracted to staging tables like, say, = export does so that your code operates as the only session that reads = from, creates, and populates the tables that it references. The upshot, therefore, is that I'm afraid that I can only guess at why = you use "open, fetch, close" on a refcursor rather than an ordinary = cursor for loop. After all, you use the technique only to traverse = metadata tables about partitions, subpartitions, and columns. I'd be = astonished if such tables have humongous numbers of rows (like hundreds = of millions). As a sanity test, I did this: create function s.t_count() returns int set search_path =3D pg_catalog, pg_temp language plpgsql as $body$ declare cur refcursor :=3D 'cur'; n int not null :=3D 0; begin open cur for select v from s.t; move forward all in cur; get diagnostics n =3D row_count; move absolute 0 in cur; return n; end; $body$; Then I timed these two alternatives on a test table with ten million = rows. select count(*) from s.t; select s.t_count(); They both got the same answer. But my function took about twice as long = as the native count(*). Mind you, with "only" 10 million rows (and using = a PG cluster in a VM on my Mac Book) the times were tiny: ~600ms versus = ~300ms. Then I tried this: create procedure s.p(tab in text, mode in text) set search_path =3D pg_catalog, pg_temp security definer language plpgsql as $body$ declare cur constant refcursor not null :=3D 'cur'; stmt constant text not null :=3D format('select k, v from = s.%I', tab); cnt_stmt constant text not null :=3D format('select count(*) = from s.%I', tab); kk int not null :=3D 0; vv int not null :=3D 0; k int; v int; n int not null :=3D 0; cnt int not null :=3D 0; begin case mode when 'naive' then execute cnt_stmt into cnt; for kk, vv in execute stmt loop n :=3D n + 1; assert kk =3D n and vv =3D n*2; end loop; assert n =3D cnt; when 'refcursor' then open cur for execute stmt; move forward all in cur; get diagnostics cnt =3D row_count; move absolute 0 in cur; loop fetch cur into k, v; exit when not found; n :=3D n + 1; assert k =3D n and v =3D n*2; end loop; close cur; -- Just as a formality. assert n =3D cnt; end case; end; $body$ I created my 10 million row table like this: with g(v) as (select generate_series(1, 10*1000*1000)) insert into s.t(k, v) select g.v, (g.v)*2 from g; And I timed each mode a few times to get a reasonable average. The naive = mode took ~7.5 sec; and the refcursor mode took ~13 sec. I don't s'pose = that the difference matters much (and anyway, in your use case, all = those "create table" and "insert select" statements would dominate the = times). But it seems safe to say that the refcursor mode doesn't _help_ = performance. Moreover, because the naive mode uses the cursor mechanism = under the covers, the memory consumption discussion is the same for both = approaches. I appreciate that, in the face of concurrent sessions making changes to = the content of "s.t", and using the default "read committed" isolation = level, the before-the-fact separate count(*) might disagree with the = after-the-fact value from counting the rows that are traversed. And you = need the count at the start of the loop so that you can create the right = number of (sub)partitions. So I do see (because other considerations, = including code complexity, are so similar) that the refcursor mode is = more stylish. Maybe that's it. Certainly, it was very useful to think about this and to try the tests = that I did. So thank you very much for showing me your code. =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 Finally, I see how an understanding of internals helps the understanding = of performance-related question. But I find it very hard to accept that = I should read the C implementation of PostgreSQL in order to get the = proper mental model, and the proper terms of art, that I need to = understand it semantics (and the corresponding SQL and PL/pgSQL syntax). = Having said that, I did a little test an saw that this: move last in cur; get diagnostics n =3D row_count; reported just 1=E2=80=94in contrast to what you used: move forward all in cur; I've no idea how it's possible to navigate to the last result in the set = without knowing how many there are. Maybe that fact is there = internally=E2=80=94but with no explicit SQL or PL/pgSQL exposure of the = value. --Apple-Mail=_9E8A9FC5-D170-4BD8-9498-ACA8A4BE8589 Content-Transfer-Encoding: quoted-printable Content-Type: text/html; charset=utf-8
laurenz.albe@cybertec.at wrote:

...I understand that you ask questions to gain deeper = understanding.

bryn@yugabyte.com wrote:

...I had never come across use cases where [scrollability] = was beneficial. I wanted, therefore, to hear about some. I thought = that insights here would help me understand the mechanics.

I = recently used cursor scrollability, so I can show you a use case:

github.com/cybertec-postgresql/db_migrator/blob/master/db_migra= tor--1.0.0.sql#L49

The goal is to get = the query result count right away, without having to run a second = query for it: you declare the cursor, move to the end of the result = set, fetch the ROW_COUNT, then move back to the beginning of the = result set and start fetching the result rows.

...I personally find that reading the PostgreSQL = documentation gets you far, but only so far: for deep = understanding, you have to read the code. It is usually well
documented and readable, and I have come to see it as an = extension of the documentation that covers the details.

Thanks for = the link to your SQL file at the line where you get the row count in the = way that you describe. I saw that this is in the PL/pgSQL source text = for function "materialize_foreign_table()" (~200 lines). And I saw that = you use the cursor mechanism that we're discussing here in only one = other function, "db_migrate_refresh()" (~480 lines). But this second one = doesn't use the "move forward all" device to get a row count. I looked = only at these two functions.

I noted that neither of these functions = has a refcursor formal argument and that, rather, you open (i.e. create) = each of the three cursors that you use within the two functions = that uses them. I noted, too,  that for the three "select" = statements that you use to open your refcursors, none of these has an = "order by". I noted that your code implements "create table destination" = and "insert into destination... select from source..." where order = doesn't matter. 

However, source code famously reveals only what it does and = not what the author's intention, and overall design philosophy, is. I = looked at the README accounts for these two functions here:









  set search_path =3D = pg_catalog, pg_temp
  security definer
  language plpgsql
as $body$
declare
  cur     =   constant refcursor not null :=3D 'cur';
  stmt      constant text  =     not null :=3D format('select k, v from = s.%I',     tab);
  cnt_stmt  constant text    =   not null :=3D format('select count(*) from s.%I', tab);

  kk   int not null = :=3D 0;
  vv   int not null :=3D = 0;
  k    int;
  v    int;
  n    int not null :=3D 0;
  cnt  int not null :=3D 0;
begin
  case mode
  =   when 'naive' then
    =   execute cnt_stmt into cnt;
    =   for kk, vv in execute stmt loop
    =     n :=3D n + 1;
      =   assert kk =3D n and vv =3D n*2;
    =   end loop;
      assert n =3D= cnt;

    when 'refcursor' = then
      open cur for execute = stmt;
      move forward all in = cur;
      get diagnostics cnt =3D = row_count;
      move absolute 0 in = cur;

      loop
        fetch cur into k, v;
        exit when not found;
        n :=3D n + 1;
        assert k =3D n and v =3D = n*2;
      end loop;
      close cur; -- Just as a = formality.
      assert n =3D cnt;
  end case;
end;
$body$

I created my 10 million row table like = this:

with g(v) as (select generate_series(1, = 10*1000*1000))
insert into s.t(k, v) select g.v, (g.v)*2 = from g;

And I timed each mode a few times to get a reasonable = average. The naive mode took ~7.5 sec; and the refcursor mode = took ~13 sec. I don't s'pose that the difference matters much (and = anyway, in your use case, all those "create table" and "insert select" = statements would dominate the times). But it seems safe to say that the = refcursor mode doesn't _help_ performance. Moreover, because the naive = mode uses the cursor mechanism under the covers, the memory consumption = discussion is the same for both approaches.

I appreciate that, in the face of = concurrent sessions making changes to the content of "s.t", and using = the default "read committed" isolation level, the before-the-fact = separate count(*) might disagree with the after-the-fact value from = counting the rows that are traversed. And you need the count at the = start of the loop so that you can create the right number of = (sub)partitions. So I do see (because other considerations, including = code complexity, are so similar) that the refcursor mode is more = stylish. Maybe that's it.

Certainly, it was very useful to think about this and to try = the tests that I did. So thank you very much for showing me your = code.
=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

Finally, I see how an understanding of = internals helps the understanding of performance-related question. = But I find it very hard to accept that I should read the C = implementation of PostgreSQL in order to get the proper mental model, = and the proper terms of art, that I need to understand it semantics (and = the corresponding SQL and PL/pgSQL syntax). Having said that, I did a = little test an saw that this:

move last in = cur;
get = diagnostics n =3D row_count;

reported just 1=E2=80=94in= contrast to what you used:

move forward all in cur;

I've no = idea how it's possible to navigate to the last result in the set without = knowing how many there are. Maybe that fact is there internally=E2=80=94bu= t with no explicit SQL or PL/pgSQL exposure of the value.




= --Apple-Mail=_9E8A9FC5-D170-4BD8-9498-ACA8A4BE8589--