Re: Cursors: getting the number of tuples; moving backwards

From: Martijn van Oosterhout <kleptog(at)svana(dot)org>
To: am(at)fx(dot)ro
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Cursors: getting the number of tuples; moving backwards
Date: 2002-11-01 08:23:29
Message-ID: 20021101082328.GA26000@svana.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-hackers pgsql-jdbc

On Fri, Nov 01, 2002 at 12:43:48PM +0200, am(at)fx(dot)ro wrote:
> Hello everyone!
>
> I have 2 questions:
>
> --1-- Some days ago, I've been trying to get the number of tuples
> that FETCH ALL would return, *before* fetching anything.
> (the program is written in C++, using libpq ; PostgreSQL 7.2.3).

Well, to get an answer, the server needs to execute the entire query. It
won't do that unless you explicitly ask for it.

> The solution i've found was something like:
>
> int nr_tuples;
>
> res = PQexec(conn, "MOVE ALL in CURS");
> sscanf(PQcmdStatus(res),"MOVE %i",&nr_tuples);
> PQclear(res);

That would work. But why do you need to know the total beforehand? You could
just do a FETCH ALL and then use PQntuples to get the number. If you're
using it to decide whether to provide a Next link, just FETCH one more item
than you intend to display and if you get it you display the link.

> I'm wondering: is there any better way to get that number?
>
> ( just an idea: maybe it would be useful to make PQcmdTuples
> work for MOVE commands ... ? )

Interesting idea. I'm not sure whether MOVE actually executes the query or
not.

> --2-- I found out that if i reach the end of the cursor, and want
> to move backwards, i have to increase the MOVE command's argument by 1:

No idea, the cursor has probably moved off the end to indicate the query is
done. So you need the extra one to move it back. That's just a guess though.

Hope this helps,
--
Martijn van Oosterhout <kleptog(at)svana(dot)org> http://svana.org/kleptog/
> There are 10 kinds of people in the world, those that can do binary
> arithmetic and those that can't.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Devrim GÜNDÜZ 2002-11-01 09:35:19 pam_pgsql, Postfix, imap and PostgreSQL
Previous Message Neil Conway 2002-11-01 01:54:12 Re: [GENERAL] my.cnf to postgresql.conf Conversion

Browse pgsql-hackers by date

  From Date Subject
Next Message Jinqiang Han 2002-11-01 08:25:07 about postgresql-7.3.2 rpm
Previous Message Sean Chittenden 2002-11-01 07:57:08 Re: Request for supported platforms

Browse pgsql-jdbc by date

  From Date Subject
Next Message Gary 2002-11-01 09:06:04 Java.lang.ClassNotFoundException:postgresql.Driver
Previous Message Barry Lind 2002-10-31 18:02:42 Re: Errors compiling jdbc