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 1pD5bl-0001Fq-Ax for pgsql-hackers@arkaria.postgresql.org; Wed, 04 Jan 2023 15:23:13 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1pD5al-0001t3-Rk for pgsql-hackers@arkaria.postgresql.org; Wed, 04 Jan 2023 15:22:11 +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 1pD5al-0001su-II for pgsql-hackers@lists.postgresql.org; Wed, 04 Jan 2023 15:22:11 +0000 Received: from mail.verite.pro ([185.16.44.216]) by magus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1pD5ai-0003T3-Ju for pgsql-hackers@postgresql.org; Wed, 04 Jan 2023 15:22:11 +0000 Received: by mail.verite.pro (Postfix, from userid 1000) id 551AD8C05CF; Wed, 4 Jan 2023 16:22:06 +0100 (CET) Content-Type: text/plain; charset="iso-8859-15" Content-Disposition: inline Content-Transfer-Encoding: quoted-printable MIME-Version: 1.0 Subject: Re: psql's FETCH_COUNT (cursor) is not being respected for CTEs From: "Daniel Verite" To: "Jakub Wartak" Cc: "PostgreSQL Hackers" In-Reply-To: Date: Wed, 04 Jan 2023 16:22:03 +0100 Message-Id: <3a3451a2-7d05-4dd7-b7ac-e75d2accf327@manitou-mail.org> X-Mailer: Manitou v1.7.3 List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Jakub Wartak wrote: > It might be a not so well known fact (?) that CTEs are not executed > with cursor when asked to do so, but instead silently executed with > potential huge memory allocation going on. Patch is attached. My one > doubt is that not every statement starting with "WITH" is WITH(..) > SELECT of course. Yes, that's why WITH queries are currently filtered out by the FETCH_COUNT feature. Case in point: test=3D> begin; BEGIN test=3D> create table tbl(i int); CREATE TABLE test=3D> declare psql_cursor cursor for with r(i) as (values (1)) insert into tbl(i) select i from r; ERROR: syntax error at or near "insert" LINE 3: insert into tbl(i) select i from r; So the fix you're proposing would fail on that kind of queries. A solution would be for psql to use PQsetSingleRowMode() to retrieve results row-by-row, as opposed to using a cursor, and then allocate memory for only FETCH_COUNT rows at a time. Incidentally it solves other problems like queries containing multiple statements, that also fail to work properly with cursors, or UPDATE/INSERT... RETURNING.. on large number of rows that could also benefit from pagination in memory. Best regards, --=20 Daniel V=E9rit=E9 https://postgresql.verite.pro/ Twitter: @DanielVerite