Return-Path: postarch
Received: by postgres.Berkeley.EDU (5.61/1.29)
	id AA08417; Thu, 9 Jan 92 19:04:20 -0800
Message-Id: <9201100304.AA08417@postgres.Berkeley.EDU>
From: postarch (Postgres Mailing Archive)
Subject: Re: PQexec and PQparray questions
To: postgres@postgres.berkeley.edu
Sender: pg_adm@postgres.berkeley.edu
Reply-To: mer@postgres.berkeley.edu
In-Reply-To: Your message of "Thu, 09 Jan 92 15:54:04 PST."
             <9201092354.AA05800@postgres.Berkeley.EDU> 
Date: Thu, 09 Jan 92 19:04:10 PST

you write:
> 
> #include <stdio.h>
> #include "libpq.h"
> 
> void store(obj_type,obj,size,name,uid)
> /*stores an object and returns its unique id */
>    char *obj_type;
>    char *obj;
>    unsigned long size;
>    char *name;
>    unsigned long *uid;
> 
>    {
> 
>    char postquery[512];
>    PortalBuffer *portalbuff;
> 
>    char *res;
>    char result[512];
> 
>    PQsetdb("hb1");
>    sprintf (postquery,"append OBJECTS (name=\"%s\",size=%ld, \
>                        obj_type=\"%s\")",name, size, obj_type);
>    PQexec("begin");
>    PQexec(postquery);
>    sprintf(postquery,"retrieve portal p1 unique (e.oid)      \
>                       from e in OBJECTS where e.name=\"%s\"  \
>                       and e.size=%ld and e.obj_type=\"%s\"", 
>                       name, size, obj_type);
>    res = PQexec(postquery);
> 
>    portalbuff = PQparray(++res);
> 
>    *uid = atoi(PQgetvalue(portalbuff,1,1));

>  so i changed the definition of the variable "res" to char, and
> added a pointer to it to get the portal using PQparray. it was
> compiled, but PQparray doesn't seem to be working, and i'm
> getting a segmentation fault error when executing my program.

There are a few things wrong with the code fragment above.  First, when you
retrieve into a portal you don't get the portal name back.  The return string
(if the query succeeds) is "CRETRIEVE".  You must first fetch the tuples
in the portal:

	res = PQexec("fetch all in p1");

Now the return string should be "Pp1" and you can proceed to get the values.

Second, because the tuple groups and tuples are indexed starting from 0 not 1,
PQgetvalue() will return NULL and you will die in atoi().

	*uid = atoi(PQgetvalue(portalbuff,0,0));

As a general rule you want to make sure that what you get back from 
PQgetvalue is non-null before you pass it to conversion routines.  It's a
good idea to use PQntuples() and PQngroups(). You should also check
the first returned character whenever you do a PQexec to make sure that your
query has executed without problems.


Jeff Meredith
mer@postgres.berkeley.edu
