Trouble with FETCH_COUNT and combined queries in psql - Mailing list pgsql-hackers

From Daniel Verite
Subject Trouble with FETCH_COUNT and combined queries in psql
Date
Msg-id a0a854b6-563c-4a11-bf1c-d6c6f924004d@manitou-mail.org
Whole thread Raw
Responses Re: Trouble with FETCH_COUNT and combined queries in psql
List pgsql-hackers
  Hi,

When FETCH_COUNT is set, queries combined in a single request don't work
as expected:

 \set FETCH_COUNT 10
 select pg_sleep(2) \; select 1;

No result is displayed, the pg_sleep(2) is not run, and no error
is shown. That's disconcerting.

The sequence that is sent under the hood is:

#1 BEGIN
#2  DECLARE _psql_cursor NO SCROLL CURSOR FOR
    select pg_sleep(2) ; select 1;
#3 CLOSE _psql_cursor
#4 ROLLBACK

The root problem is in deciding that a statement can be run
through a cursor if the query text starts with "select" or "values"
(in is_select_command() in common.c), but not knowing about multiple
queries in the buffer, which are not compatible with the cursor thing.

When sending #2, psql expects the PQexec("DECLARE...") to yield a
PGRES_COMMAND_OK, but it gets a PGRES_TUPLES_OK instead. Given
that, it abandons the cursor, rollbacks the transaction (if
it opened it), and clears out the results of the second select
without displaying them.

If there was already a transaction open, the problem is worse because
it doesn't rollback and we're silently missing an SQL statement that
was possibly meant to change the state of the data, as in
 BEGIN; SELECT compute_something() \; select get_results(); END;

Does anyone have thoughts about how to fix this?
ATM I don't see a plausible fix that does not involve the parser
to store the information that it's a multiple-query command and pass
it down somehow to is_select_command().
Or a more modern approach could be to give up on the
cursor-based method in favor of  PQsetSingleRowMode().
That might be too big a change for a bug fix though,


Best regards,
--
Daniel Vérité
PostgreSQL-powered mailer: http://www.manitou-mail.org
Twitter: @DanielVerite



pgsql-hackers by date:

Previous
From: Bruce Momjian
Date:
Subject: Optimizer items in the release notes
Next
From: Andres Freund
Date:
Subject: Re: Unhappy about API changes in the no-fsm-for-small-rels patch