.\" XXX standard disclaimer belongs here....
.\" $Header: RCS/libpq,v 1.7 91/11/13 05:20:12 mer Exp $
.SS "LIBPQ" 6/14/90
.XA 0 "Section 5 \*- Libpq"
.uh NAME
.lp
libpq \*- programmer's interface to \*(PP
.uh DESCRIPTION
.lp
LIBPQ is the programmer's interface to Postgres.  LIBPQ is a set of
library routines which allow queries to pass to the Postgres back-end
and instances to return through an IPC channel.
.lp
This version of the documentation is based on the C library.
.uh "CONTROL AND INITIALIZATION"
.lp
.uh VARIABLES
.lp
The following five environment variables can be used to set
up default values for an environment and to avoid hard-coding
database names into an application program:
.lp
.(l
.bu
\fBPGHOST\fR sets the default server name.
.bu
\fBPGDATABASE\fR sets the default Postgres database name.
.bu
\fBPGPORT\fR sets the default communication port with the POSTGRES back-end.
.bu
\fBPGTTY\fR sets the tty on the PQhost back-end on which debugging messages are displayed.
.bu
\fBPGOPTION\fR contains optional arguements to the POSTGRES back-end.
.)l
.lp
The following internal variables of libpq can be accessed by
the programmer:
.lp
.(1
.nf
char	*PQhost ;	/* the server on which POSTGRES back-end
			   is running. */

char	*PQport = NULL ;	/* The communication port with the
				   POSTGRES back-end. */

char	*PQtty;		/* The tty on the PQhost back-end on which
			   back-end messages are displayed. */

char	*PQoption ;	/* Optional arguements to the back-end */

char	*PQdatabase ;	/* Back-end database to access */

int	PQportset = 0;	/* 1 if communication with back-end is established */

int	PQxactid = 0 ;	/* Transaction ID of the current transaction */

int	PQtracep = 0 ;	/* 1 to print out front-end debugging messages */
.)1
.fi
.uh "QUERY EXECUTION FUNCTIONS"
.lp
The following routines control the execution of queries
from a C program.

.(1
PQsetdb \*- Make the specified database the current database, 

.nf
void PQsetdb ( dbname )
	char	*dbname;

PQsetdb also resets communication via PQreset (see below).

PQdb \*- Return the current database being accessed.

char * PQdb ()
.)1
.fi
.lp
Returns the name of the POSTGRES database
being accessed, or NIL if no database is open.
Only one database can be accessed at a time.  The database
name is a string limited to 16 characters.
.lp
.nf
.(1
PQreset \*- Reset the communication port with the back-end in case of errors.

void PQreset()

.fi
This function will close the IPC socket connection to the backend thereby
causing the next PQexec() call to ask for a new one from the postmaster.
When the backend notices the socket was closed it will exit, and when the
postmaster is asked for the new connection it will start a new back-end.
.nf

PQfinish \*- Close communication ports with the back-end.

void PQfinish ()
.)1
.fi
.lp
Terminates communications and frees up the memory taken up
by the libpq buffer.
.nf

.(1
PQfn \*- Send a function call to the POSTGRES backend.

char *PQfn(fnid, result_buf, result_len, result_is_int, args, nargs)
	int fnid;
	int *result_buf;    /* can't use void, the compiler complains */
	int result_len;
	int result_is_int;
	PQArgBlock *args;
	int nargs;

.fi
PQfn provides access to the POSTGRES fastpath facility, a trapdoor into
the system internals.  See \fBFASTPATH\fR.
.nf

.(1
PQexec \*- Submit a query to POSTGRES.  

char *	PQexec (query)
	char	* query;
.)1
.fi
.lp
This function returns a status indicator or an error message.  If the
query submitted was a retrieve then PQexec returns a string consisting
of a 'P' followed by the portal name.  If no portal was specified the
portal name will be "blank".  When the query was not a retrieve PQexec
will return a string consisting of 'C' followed by the command tag (e.g.
"CREPLACE").  If an error occured during the execution of the query 
PQexec will return "R".  You might be wondering "why an 'R'?"  The answer
is that this stems from libpq's history.  It used to be the case that
when libpq received an error message from the backend it would attempt
to \fIreset\fR communications.  Thus it returned (and still returns) an 'R' 
to the application program.

.uh "PORTAL FUNCTIONS"
.lp
A portal is a POSTGRES buffer from which instances can be fetched.
Each portal has a string name (currently limited to 16 bytes).
A portal is initialized by submitting a retrieve statement
using the PQexec function, for example:
.(l
\fBretrieve portal\fR foo ( EMP.all )
.)l
.lp
The programmer can then move data from the portal into LIBPQ
by executing a \fIfetch\fR statement, e.g:
.(l
\fBfetch 10 in \fIfoo\fR

\fBfetch all in \fIfoo\fR
.)l
.lp
If no portal name is specified in a query, the default
portal name is the string "blank", known as the "blank portal."
All qualifying instances in a blank portal are fetched
immediately, without the need for the programmer to issue a
seperate fetch command.
.lp
Data fetched from a portal into LIBPQ is moved into a portal
buffer.  Portal names are mapped to portal buffers through
an internal table.  Each instance in a portal buffer has
an index number locating its position in the buffer.  In addition,
each field in an instance has a name and a field number.
.lp
A single retrieve command can return multiple types
of instances.
This can happen if a \*(PP function is executed
in the evaluation of a query or if the query
returns multiple instance types from an inheritance
hierarchy.
Consequently, the instances in a portal are set up
in groups.
Instances in the same group are guaranteed to have the
same instance format.
.lp
Portals that are associated with normal user commands
are called synchronous.
In this case, the application program is expected
to issue a retrieval followed by one or more
fetch commands.
The functions that follow can now be used to
manipulate data in the portal.
.(l
PQnportals \*- Return the number of open portals.

int PQnportals ( rule_p )
	int	rule_p ;

If rule_p is not 0, then only return the number of asynchronous portals.

PQnames \*- Return all portal names.

void PQnames  ( pnames, rule_p)
	char	*pnames [MAXPORTALS];
	int	rule_p ;

If rule_p is not 0, then only return the names of asynchronous
portals.

PQparray \*- Return the portal buffer given a portal name.

PortalBuffer * PQparray ( pname )
	char	*pname;

PQclear \*- free storage claimed by named portal.

void PQclear ( pname )
	char	*pname;

PQrulep \*- Return 1 if an asynchronous portal.

int PQrulep	(portal)
	PortalBuffer	*portal;

PQntuples \*- Return the number of instances in a portal buffer.

int PQntuples (portal)
	PortalBuffer	*portal;

PQngroups \*- Return the number of instance groups in a portal buffer.

int PQngroups (portal)
	PortalBuffer *portal

PQntuplesGroup \*- Return the number of instances in an instance group.

int PQntuplesGroup (portal, group_index)
	PortalBuffer	*portal;
	int	group_index;

PQnfieldsGroup \*- Return the number of fields in an instance group.

int PQnfieldsGroup ( portal, group_index)
	PortalBuffer	*portal;
	int	group_index;

PQfnameGroup \*- Return the field name given the group and field index.

char * PQfnameGroup (portal, group_index, field_number )
	PortalBuffer	*portal;
	int	group_index;
	int	field_number;

PQfnumberGroup \*- Return the field number (index) given the group index and field name.

int PQfnumberGroup (portal, group_index, field_name)
	PortalBuffer	*portal;
	int	group_index;
	char	*field_name;

PQgetgroup \*- Returns the index of the group that a particular instance is in.

int PQgetgroup ( portal, tuple_index )
	PortalBuffer	*portal;
	int	tuple_index;

PQnfields \*- Return the number of fields in an instance.

int PQnfields (portal, tuple_index )
	PortalBuffer	*portal;
	int	tuple_index;

PQfnumber \*- Return the field index of a given field name within an instance.

int PQfnumber ( portal, tuple_index, field_name)
	PortalBuffer	*portal;
	int	tuple_index;
	char	*field_name;

PQfname \*- Return the name of a field.

char * PQfname ( portal, tuple_index, field_number )
	PortalBuffer	*portal;
	int	tuple_index;
	int	field_number;

PQftype \*- Return the type of a field.  

int PQftype ( portal, tuple_index, field_number )
	PortalBuffer	*portal;
	int	tuple_index;
	int	field_number;

The type returned is an internal coding of a type.

PQsametype \*- Return 1 if two instances have the same attributes.

int PQsametype ( portal, tuple_index1, tuple_index2 )
	PortalBuffer	*portal;
	int	tuple_index1, tuple_index2;

PQgetvalue \*- Return an attribute (field) value.  
char * PQgetvalue ( portal, tuple_index, field_number )
	PortalBuffer	*portal;
	int	tuple_index;
	int	field_number;
.)1
.lp
All values are returned
as string.  It is the programmer's responsibility to
convert them to the correct type.
.uh "FUNCTIONS ASSOCIATED WITH THE COPY COMMAND"
.lp
The
.i copy
command in POSTGRES has options to read from or write to the network
connection used by LIBPQ.  Therefore, functions are necessary to access
this network connection directly so applications may take full advantage
of this capability.
.lp
For more information about the 
.i copy
command, see copy(postquel).
.lp

.(1
PQgetline(string, length) \*- Reads a null-terminated line into string.

char *string;
int length

PQputline(string) \*- Sends a null-terminated string.

char *string;

int
PQendcopy() \*- Syncs with the back-end.

This function waits until the backend has finished processing the copy.
It should either be issued when the last string has been sent to the
backend using PQputline() or when the last string has been received from
the backend using PGgetline().  It must be issued or the backend may get
"out of sync" with the frontend.  Upon return from this function, the
backend is ready to receive the next query.

The return value is 0 on successful completion, nonzero otherwise.

\fBFor Example:\fR

.nf
PQexec("create foo (a=int4, b=char16, d=float8)");
PQexec("copy foo from stdin");
PQputline("3<TAB>hello world<TAB>4.5\n");
PQputline("4<TAB>goodbye world<TAB>7.11");
...
PQputline(".\en");
PQendcopy();
.fi
.)1

.uh "TRACING FUNCTIONS"
.lp
.(1
PQtrace \*- Enable tracing.

void PQtrace ()

The routine sets the PQtracep variable to 1 which causes debug messages to
be printed.  You should note that the
messages will be printed to stdout by default.  If you would like different
behavior you must set the variable FILE *debug_port to the appropriate stream.

PQuntrace \*- Disable tracing.

void PQuntrace ()
.)1
.uh BUGS
.lp
The query buffer is only 8192 bytes long, and queries over that
length will be silently truncated.

.uh "SAMPLE PROGRAM"
.lp
.(1
.nf
/*
 * testlibpq.c \*-
 * 	Test the C version of Libpq, the POSTGRES frontend library.
 */
#include <stdio.h>
#include "libpq.h"

main ()
{
    int i, j, k, g, n, m, t;
    PortalBuffer *p;
    char pnames[MAXPORTALS][portal_name_length];

    /* Specify the database to access. */
    PQsetdb ("pic_demo");

    /* Start a transaction block for eportal */
    PQexec ("begin");

    /* Fetch instances from the EMP class. */
    PQexec ("retrieve portal eportal (EMP.all)");
    PQexec ("fetch all in eportal");

    /* Examine all the instances fetched. */
    p = PQparray ("eportal");
    g = PQngroups (p);
    t = 0;
    
    for (k = 0; k < g; k++) {
	printf ("\enA new instance group:\en");
	n = PQntuplesGroup (p, k);
	m = PQnfieldsGroup (p, k);

	/* Print out the attribute names. */
	for (i = 0; i < m; i++)
	    printf ("%-15s", PQfnameGroup (p, k, i));
	printf ("\en");
    
	/* Print out the instances. */
	for (i = 0; i < n; i++) {
	    for (j = 0; j < m; j++)
		printf ("%-15s", PQgetvalue (p, t+i, j));
	    printf ("\en");
	}
	t += n;
    }

    /* Close the portal. */
    PQexec ("close eportal");

    /* End the transaction block */
    PQexec("end");

    /* Try out some other functions. */
    
    /* Print out the number of portals. */
    printf ("\enNumber of portals open: %d.\en", PQnportals ());

    /* If any tuples are returned by rules, print out the portal name. */
    if (PQnportals (1)) {
	printf ("Tuples are returned by rules. \en");
	PQpnames (pnames, 1);
	for (i = 0; i < MAXPORTALS; i++)
	    if (pnames[i] != NULL)
		printf ("portal used by rules: %s\en", pnames[i]);
    }

    /* finish execution. */
    PQfinish ();
}
.)1
