]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-exec.c
Change PQconndefaults() to return a malloc'd array, instead of a static
[postgresql] / src / interfaces / libpq / fe-exec.c
1 /*-------------------------------------------------------------------------
2  *
3  * fe-exec.c
4  *        functions related to sending a query down to the backend
5  *
6  * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $Header: /cvsroot/pgsql/src/interfaces/libpq/fe-exec.c,v 1.92 2000/03/11 03:08:36 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include <errno.h>
16 #include <ctype.h>
17 #include <fcntl.h>
18
19 #include "postgres.h"
20 #include "libpq-fe.h"
21 #include "libpq-int.h"
22
23 #ifdef WIN32
24 #include "win32.h"
25 #else
26 #include <unistd.h>
27 #endif
28
29 /* keep this in same order as ExecStatusType in libpq-fe.h */
30 char * const pgresStatus[] = {
31         "PGRES_EMPTY_QUERY",
32         "PGRES_COMMAND_OK",
33         "PGRES_TUPLES_OK",
34         "PGRES_COPY_OUT",
35         "PGRES_COPY_IN",
36         "PGRES_BAD_RESPONSE",
37         "PGRES_NONFATAL_ERROR",
38         "PGRES_FATAL_ERROR"
39 };
40
41
42 /* Note: DONOTICE macro will work if applied to either PGconn or PGresult */
43 #define DONOTICE(conn,message) \
44         ((*(conn)->noticeHook) ((conn)->noticeArg, (message)))
45
46
47 static void pqCatenateResultError(PGresult *res, const char *msg);
48 static void saveErrorResult(PGconn *conn);
49 static PGresult *prepareAsyncResult(PGconn *conn);
50 static int      addTuple(PGresult *res, PGresAttValue *tup);
51 static void parseInput(PGconn *conn);
52 static void handleSendFailure(PGconn *conn);
53 static int      getRowDescriptions(PGconn *conn);
54 static int      getAnotherTuple(PGconn *conn, int binary);
55 static int      getNotify(PGconn *conn);
56 static int      getNotice(PGconn *conn);
57
58
59 /* ----------------
60  * Space management for PGresult.
61  *
62  * Formerly, libpq did a separate malloc() for each field of each tuple
63  * returned by a query.  This was remarkably expensive --- malloc/free
64  * consumed a sizable part of the application's runtime.  And there is
65  * no real need to keep track of the fields separately, since they will
66  * all be freed together when the PGresult is released.  So now, we grab
67  * large blocks of storage from malloc and allocate space for query data
68  * within these blocks, using a trivially simple allocator.  This reduces
69  * the number of malloc/free calls dramatically, and it also avoids
70  * fragmentation of the malloc storage arena.
71  * The PGresult structure itself is still malloc'd separately.  We could
72  * combine it with the first allocation block, but that would waste space
73  * for the common case that no extra storage is actually needed (that is,
74  * the SQL command did not return tuples).
75  * We also malloc the top-level array of tuple pointers separately, because
76  * we need to be able to enlarge it via realloc, and our trivial space
77  * allocator doesn't handle that effectively.  (Too bad the FE/BE protocol
78  * doesn't tell us up front how many tuples will be returned.)
79  * All other subsidiary storage for a PGresult is kept in PGresult_data blocks
80  * of size PGRESULT_DATA_BLOCKSIZE.  The overhead at the start of each block
81  * is just a link to the next one, if any.      Free-space management info is
82  * kept in the owning PGresult.
83  * A query returning a small amount of data will thus require three malloc
84  * calls: one for the PGresult, one for the tuples pointer array, and one
85  * PGresult_data block.
86  * Only the most recently allocated PGresult_data block is a candidate to
87  * have more stuff added to it --- any extra space left over in older blocks
88  * is wasted.  We could be smarter and search the whole chain, but the point
89  * here is to be simple and fast.  Typical applications do not keep a PGresult
90  * around very long anyway, so some wasted space within one is not a problem.
91  *
92  * Tuning constants for the space allocator are:
93  * PGRESULT_DATA_BLOCKSIZE: size of a standard allocation block, in bytes
94  * PGRESULT_ALIGN_BOUNDARY: assumed alignment requirement for binary data
95  * PGRESULT_SEP_ALLOC_THRESHOLD: objects bigger than this are given separate
96  *       blocks, instead of being crammed into a regular allocation block.
97  * Requirements for correct function are:
98  * PGRESULT_ALIGN_BOUNDARY must be a multiple of the alignment requirements
99  *              of all machine data types.      (Currently this is set from configure
100  *              tests, so it should be OK automatically.)
101  * PGRESULT_SEP_ALLOC_THRESHOLD + PGRESULT_BLOCK_OVERHEAD <=
102  *                      PGRESULT_DATA_BLOCKSIZE
103  *              pqResultAlloc assumes an object smaller than the threshold will fit
104  *              in a new block.
105  * The amount of space wasted at the end of a block could be as much as
106  * PGRESULT_SEP_ALLOC_THRESHOLD, so it doesn't pay to make that too large.
107  * ----------------
108  */
109
110 #ifdef MAX
111 #undef MAX
112 #endif
113 #define MAX(a,b)  ((a) > (b) ? (a) : (b))
114
115 #define PGRESULT_DATA_BLOCKSIZE         2048
116 #define PGRESULT_ALIGN_BOUNDARY         MAXIMUM_ALIGNOF         /* from configure */
117 #define PGRESULT_BLOCK_OVERHEAD         MAX(sizeof(PGresult_data), PGRESULT_ALIGN_BOUNDARY)
118 #define PGRESULT_SEP_ALLOC_THRESHOLD    (PGRESULT_DATA_BLOCKSIZE / 2)
119
120
121 /*
122  * PQmakeEmptyPGresult
123  *       returns a newly allocated, initialized PGresult with given status.
124  *       If conn is not NULL and status indicates an error, the conn's
125  *       errorMessage is copied.
126  *
127  * Note this is exported --- you wouldn't think an application would need
128  * to build its own PGresults, but this has proven useful in both libpgtcl
129  * and the Perl5 interface, so maybe it's not so unreasonable.
130  */
131
132 PGresult   *
133 PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
134 {
135         PGresult   *result;
136
137         result = (PGresult *) malloc(sizeof(PGresult));
138
139         result->xconn = conn;           /* might be NULL */
140         result->ntups = 0;
141         result->numAttributes = 0;
142         result->attDescs = NULL;
143         result->tuples = NULL;
144         result->tupArrSize = 0;
145         result->resultStatus = status;
146         result->cmdStatus[0] = '\0';
147         result->binary = 0;
148         result->errMsg = NULL;
149         result->null_field[0] = '\0';
150         result->curBlock = NULL;
151         result->curOffset = 0;
152         result->spaceLeft = 0;
153
154         if (conn)
155         {
156                 result->noticeHook = conn->noticeHook;
157                 result->noticeArg = conn->noticeArg;
158                 /* consider copying conn's errorMessage */
159                 switch (status)
160                 {
161                         case PGRES_EMPTY_QUERY:
162                         case PGRES_COMMAND_OK:
163                         case PGRES_TUPLES_OK:
164                         case PGRES_COPY_OUT:
165                         case PGRES_COPY_IN:
166                                 /* non-error cases */
167                                 break;
168                         default:
169                                 pqSetResultError(result, conn->errorMessage.data);
170                                 break;
171                 }
172         }
173         else
174         {
175                 result->noticeHook = NULL;
176                 result->noticeArg = NULL;
177         }
178
179         return result;
180 }
181
182 /*
183  * pqResultAlloc -
184  *              Allocate subsidiary storage for a PGresult.
185  *
186  * nBytes is the amount of space needed for the object.
187  * If isBinary is true, we assume that we need to align the object on
188  * a machine allocation boundary.
189  * If isBinary is false, we assume the object is a char string and can
190  * be allocated on any byte boundary.
191  */
192 void *
193 pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
194 {
195         char       *space;
196         PGresult_data *block;
197
198         if (!res)
199                 return NULL;
200
201         if (nBytes <= 0)
202                 return res->null_field;
203
204         /*
205          * If alignment is needed, round up the current position to an
206          * alignment boundary.
207          */
208         if (isBinary)
209         {
210                 int                     offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
211
212                 if (offset)
213                 {
214                         res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
215                         res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
216                 }
217         }
218
219         /* If there's enough space in the current block, no problem. */
220         if (nBytes <= res->spaceLeft)
221         {
222                 space = res->curBlock->space + res->curOffset;
223                 res->curOffset += nBytes;
224                 res->spaceLeft -= nBytes;
225                 return space;
226         }
227
228         /*
229          * If the requested object is very large, give it its own block; this
230          * avoids wasting what might be most of the current block to start a
231          * new block.  (We'd have to special-case requests bigger than the
232          * block size anyway.)  The object is always given binary alignment in
233          * this case.
234          */
235         if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
236         {
237                 block = (PGresult_data *) malloc(nBytes + PGRESULT_BLOCK_OVERHEAD);
238                 if (!block)
239                         return NULL;
240                 space = block->space + PGRESULT_BLOCK_OVERHEAD;
241                 if (res->curBlock)
242                 {
243
244                         /*
245                          * Tuck special block below the active block, so that we don't
246                          * have to waste the free space in the active block.
247                          */
248                         block->next = res->curBlock->next;
249                         res->curBlock->next = block;
250                 }
251                 else
252                 {
253                         /* Must set up the new block as the first active block. */
254                         block->next = NULL;
255                         res->curBlock = block;
256                         res->spaceLeft = 0; /* be sure it's marked full */
257                 }
258                 return space;
259         }
260
261         /* Otherwise, start a new block. */
262         block = (PGresult_data *) malloc(PGRESULT_DATA_BLOCKSIZE);
263         if (!block)
264                 return NULL;
265         block->next = res->curBlock;
266         res->curBlock = block;
267         if (isBinary)
268         {
269                 /* object needs full alignment */
270                 res->curOffset = PGRESULT_BLOCK_OVERHEAD;
271                 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - PGRESULT_BLOCK_OVERHEAD;
272         }
273         else
274         {
275                 /* we can cram it right after the overhead pointer */
276                 res->curOffset = sizeof(PGresult_data);
277                 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - sizeof(PGresult_data);
278         }
279
280         space = block->space + res->curOffset;
281         res->curOffset += nBytes;
282         res->spaceLeft -= nBytes;
283         return space;
284 }
285
286 /*
287  * pqResultStrdup -
288  *              Like strdup, but the space is subsidiary PGresult space.
289  */
290 char *
291 pqResultStrdup(PGresult *res, const char *str)
292 {
293         char       *space = (char *) pqResultAlloc(res, strlen(str) + 1, FALSE);
294
295         if (space)
296                 strcpy(space, str);
297         return space;
298 }
299
300 /*
301  * pqSetResultError -
302  *              assign a new error message to a PGresult
303  */
304 void
305 pqSetResultError(PGresult *res, const char *msg)
306 {
307         if (!res)
308                 return;
309         if (msg && *msg)
310                 res->errMsg = pqResultStrdup(res, msg);
311         else
312                 res->errMsg = NULL;
313 }
314
315 /*
316  * pqCatenateResultError -
317  *              concatenate a new error message to the one already in a PGresult
318  */
319 static void
320 pqCatenateResultError(PGresult *res, const char *msg)
321 {
322         PQExpBufferData  errorBuf;
323
324         if (!res || !msg)
325                 return;
326         initPQExpBuffer(&errorBuf);
327         if (res->errMsg)
328                 appendPQExpBufferStr(&errorBuf, res->errMsg);
329         appendPQExpBufferStr(&errorBuf, msg);
330         pqSetResultError(res, errorBuf.data);
331         termPQExpBuffer(&errorBuf);
332 }
333
334 /*
335  * PQclear -
336  *        free's the memory associated with a PGresult
337  */
338 void
339 PQclear(PGresult *res)
340 {
341         PGresult_data *block;
342
343         if (!res)
344                 return;
345
346         /* Free all the subsidiary blocks */
347         while ((block = res->curBlock) != NULL)
348         {
349                 res->curBlock = block->next;
350                 free(block);
351         }
352
353         /* Free the top-level tuple pointer array */
354         if (res->tuples)
355                 free(res->tuples);
356
357         /* Free the PGresult structure itself */
358         free(res);
359 }
360
361 /*
362  * Handy subroutine to deallocate any partially constructed async result.
363  */
364
365 void
366 pqClearAsyncResult(PGconn *conn)
367 {
368         if (conn->result)
369                 PQclear(conn->result);
370         conn->result = NULL;
371         conn->curTuple = NULL;
372 }
373
374 /*
375  * This subroutine deletes any existing async result, sets conn->result
376  * to a PGresult with status PGRES_FATAL_ERROR, and stores the current
377  * contents of conn->errorMessage into that result.  It differs from a
378  * plain call on PQmakeEmptyPGresult() in that if there is already an
379  * async result with status PGRES_FATAL_ERROR, the current error message
380  * is APPENDED to the old error message instead of replacing it.  This
381  * behavior lets us report multiple error conditions properly, if necessary.
382  * (An example where this is needed is when the backend sends an 'E' message
383  * and immediately closes the connection --- we want to report both the
384  * backend error and the connection closure error.)
385  */
386 static void
387 saveErrorResult(PGconn *conn)
388 {
389         /* If no old async result, just let PQmakeEmptyPGresult make one.
390          * Likewise if old result is not an error message.
391          */
392         if (conn->result == NULL ||
393                 conn->result->resultStatus != PGRES_FATAL_ERROR ||
394                 conn->result->errMsg == NULL)
395         {
396                 pqClearAsyncResult(conn);
397                 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
398         }
399         else
400         {
401                 /* Else, concatenate error message to existing async result. */
402                 pqCatenateResultError(conn->result, conn->errorMessage.data);
403         }
404 }
405
406 /*
407  * This subroutine prepares an async result object for return to the caller.
408  * If there is not already an async result object, build an error object
409  * using whatever is in conn->errorMessage.  In any case, clear the async
410  * result storage and make sure PQerrorMessage will agree with the result's
411  * error string.
412  */
413 static PGresult *
414 prepareAsyncResult(PGconn *conn)
415 {
416         PGresult   *res;
417
418         /*
419          * conn->result is the PGresult to return.      If it is NULL
420          * (which probably shouldn't happen) we assume there is an
421          * appropriate error message in conn->errorMessage.
422          */
423         res = conn->result;
424         conn->result = NULL;            /* handing over ownership to caller */
425         conn->curTuple = NULL;          /* just in case */
426         if (!res)
427                 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
428         else
429         {
430                 /*
431                  * Make sure PQerrorMessage agrees with result; it could
432                  * be different if we have concatenated messages.
433                  */
434                 resetPQExpBuffer(&conn->errorMessage);
435                 appendPQExpBufferStr(&conn->errorMessage,
436                                                          PQresultErrorMessage(res));
437         }
438         return res;
439 }
440
441 /*
442  * addTuple
443  *        add a row pointer to the PGresult structure, growing it if necessary
444  *        Returns TRUE if OK, FALSE if not enough memory to add the row
445  */
446 static int
447 addTuple(PGresult *res, PGresAttValue *tup)
448 {
449         if (res->ntups >= res->tupArrSize)
450         {
451
452                 /*
453                  * Try to grow the array.
454                  *
455                  * We can use realloc because shallow copying of the structure is
456                  * okay.  Note that the first time through, res->tuples is NULL.
457                  * While ANSI says that realloc() should act like malloc() in that
458                  * case, some old C libraries (like SunOS 4.1.x) coredump instead.
459                  * On failure realloc is supposed to return NULL without damaging
460                  * the existing allocation. Note that the positions beyond
461                  * res->ntups are garbage, not necessarily NULL.
462                  */
463                 int                     newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
464                 PGresAttValue **newTuples;
465
466                 if (res->tuples == NULL)
467                         newTuples = (PGresAttValue **)
468                                 malloc(newSize * sizeof(PGresAttValue *));
469                 else
470                         newTuples = (PGresAttValue **)
471                                 realloc(res->tuples, newSize * sizeof(PGresAttValue *));
472                 if (!newTuples)
473                         return FALSE;           /* malloc or realloc failed */
474                 res->tupArrSize = newSize;
475                 res->tuples = newTuples;
476         }
477         res->tuples[res->ntups] = tup;
478         res->ntups++;
479         return TRUE;
480 }
481
482
483 /*
484  * PQsendQuery
485  *       Submit a query, but don't wait for it to finish
486  *
487  * Returns: 1 if successfully submitted
488  *                      0 if error (conn->errorMessage is set)
489  */
490
491 int
492 PQsendQuery(PGconn *conn, const char *query)
493 {
494         if (!conn)
495                 return 0;
496
497         /* clear the error string */
498         resetPQExpBuffer(&conn->errorMessage);
499
500         if (!query)
501         {
502                 printfPQExpBuffer(&conn->errorMessage,
503                                                   "PQsendQuery() -- query pointer is null.\n");
504                 return 0;
505         }
506
507         /* Don't try to send if we know there's no live connection. */
508         if (conn->status != CONNECTION_OK)
509         {
510                 printfPQExpBuffer(&conn->errorMessage,
511                                                   "PQsendQuery() -- There is no connection "
512                                                   "to the backend.\n");
513                 return 0;
514         }
515         /* Can't send while already busy, either. */
516         if (conn->asyncStatus != PGASYNC_IDLE)
517         {
518                 printfPQExpBuffer(&conn->errorMessage,
519                                                   "PQsendQuery() -- another query already in progress.\n");
520                 return 0;
521         }
522
523         /* initialize async result-accumulation state */
524         conn->result = NULL;
525         conn->curTuple = NULL;
526
527         /* send the query to the backend; */
528
529         /*
530          * in order to guarantee that we don't send a partial query 
531          * where we would become out of sync with the backend and/or
532          * block during a non-blocking connection we must first flush
533          * the send buffer before sending more data
534          *
535          * an alternative is to implement 'queue reservations' where
536          * we are able to roll up a transaction 
537          * (the 'Q' along with our query) and make sure we have
538          * enough space for it all in the send buffer.
539          */
540         if (pqIsnonblocking(conn))
541         {
542                 /*
543                  * the buffer must have emptied completely before we allow
544                  * a new query to be buffered
545                  */
546                 if (pqFlush(conn))
547                         return 0;
548                 /* 'Q' == queries */
549                 /* XXX: if we fail here we really ought to not block */
550                 if (pqPutnchar("Q", 1, conn) ||
551                         pqPuts(query, conn))
552                 {
553                         handleSendFailure(conn);        
554                         return 0;
555                 }
556                 /*
557                  * give the data a push, ignore the return value as
558                  * ConsumeInput() will do any aditional flushing if needed
559                  */
560                 (void) pqFlush(conn);   
561         }
562         else
563         {
564                 /* 
565                  * the frontend-backend protocol uses 'Q' to 
566                  * designate queries 
567                  */
568                 if (pqPutnchar("Q", 1, conn) ||
569                         pqPuts(query, conn) ||
570                         pqFlush(conn))
571                 {
572                         handleSendFailure(conn);
573                         return 0;
574                 }
575         }
576
577         /* OK, it's launched! */
578         conn->asyncStatus = PGASYNC_BUSY;
579         return 1;
580 }
581
582 /*
583  * handleSendFailure: try to clean up after failure to send command.
584  *
585  * Primarily, what we want to accomplish here is to process an async
586  * NOTICE message that the backend might have sent just before it died.
587  *
588  * NOTE: this routine should only be called in PGASYNC_IDLE state.
589  */
590
591 static void
592 handleSendFailure(PGconn *conn)
593 {
594         /*
595          * Accept any available input data, ignoring errors.  Note that if
596          * pqReadData decides the backend has closed the channel, it will
597          * close our side of the socket --- that's just what we want here.
598          */
599         while (pqReadData(conn) > 0)
600                 /* loop until no more data readable */ ;
601
602         /*
603          * Parse any available input messages.  Since we are in PGASYNC_IDLE
604          * state, only NOTICE and NOTIFY messages will be eaten.
605          */
606         parseInput(conn);
607 }
608
609 /*
610  * Consume any available input from the backend
611  * 0 return: some kind of trouble
612  * 1 return: no problem
613  */
614
615 int
616 PQconsumeInput(PGconn *conn)
617 {
618         if (!conn)
619                 return 0;
620
621         /*
622          * Load more data, if available. We do this no matter what state we
623          * are in, since we are probably getting called because the
624          * application wants to get rid of a read-select condition. Note that
625          * we will NOT block waiting for more input.
626          */
627         if (pqReadData(conn) < 0)
628         {
629                 /*
630                  * for non-blocking connections
631                  * try to flush the send-queue otherwise we may never get a 
632                  * responce for something that may not have already been sent
633                  * because it's in our write buffer!
634                  */
635                 if (pqIsnonblocking(conn))
636                         (void) pqFlush(conn);
637                 return 0;
638         }
639         /* Parsing of the data waits till later. */
640         return 1;
641 }
642
643
644 /*
645  * parseInput: if appropriate, parse input data from backend
646  * until input is exhausted or a stopping state is reached.
647  * Note that this function will NOT attempt to read more data from the backend.
648  */
649
650 static void
651 parseInput(PGconn *conn)
652 {
653         char            id;
654         char            noticeWorkspace[128];
655
656         /*
657          * Loop to parse successive complete messages available in the buffer.
658          */
659         for (;;)
660         {
661
662                 /*
663                  * Quit if in COPY_OUT state: we expect raw data from the server
664                  * until PQendcopy is called.  Don't try to parse it according to
665                  * the normal protocol.  (This is bogus.  The data lines ought to
666                  * be part of the protocol and have identifying leading
667                  * characters.)
668                  */
669                 if (conn->asyncStatus == PGASYNC_COPY_OUT)
670                         return;
671
672                 /*
673                  * OK to try to read a message type code.
674                  */
675                 conn->inCursor = conn->inStart;
676                 if (pqGetc(&id, conn))
677                         return;
678
679                 /*
680                  * NOTIFY and NOTICE messages can happen in any state besides COPY
681                  * OUT; always process them right away.
682                  *
683                  * Most other messages should only be processed while in BUSY state.
684                  * (In particular, in READY state we hold off further parsing until
685                  * the application collects the current PGresult.)
686                  *
687                  * However, if the state is IDLE then we got trouble; we need to
688                  * deal with the unexpected message somehow.
689                  */
690                 if (id == 'A')
691                 {
692                         if (getNotify(conn))
693                                 return;
694                 }
695                 else if (id == 'N')
696                 {
697                         if (getNotice(conn))
698                                 return;
699                 }
700                 else if (conn->asyncStatus != PGASYNC_BUSY)
701                 {
702                         /* If not IDLE state, just wait ... */
703                         if (conn->asyncStatus != PGASYNC_IDLE)
704                                 return;
705                         /*
706                          * Unexpected message in IDLE state; need to recover somehow.
707                          * ERROR messages are displayed using the notice processor;
708                          * anything else is just dropped on the floor after displaying
709                          * a suitable warning notice.  (An ERROR is very possibly the
710                          * backend telling us why it is about to close the connection,
711                          * so we don't want to just discard it...)
712                          */
713                         if (id == 'E')
714                         {
715                                 if (getNotice(conn))
716                                         return;
717                         }
718                         else
719                         {
720                                 sprintf(noticeWorkspace,
721                                                 "Backend message type 0x%02x arrived while idle\n",
722                                                 id);
723                                 DONOTICE(conn, noticeWorkspace);
724                                 /* Discard the unexpected message; good idea?? */
725                                 conn->inStart = conn->inEnd;
726                                 break;
727                         }
728                 }
729                 else
730                 {
731                         /*
732                          * In BUSY state, we can process everything.
733                          */
734                         switch (id)
735                         {
736                                 case 'C':               /* command complete */
737                                         if (pqGets(&conn->workBuffer, conn))
738                                                 return;
739                                         if (conn->result == NULL)
740                                                 conn->result = PQmakeEmptyPGresult(conn,
741                                                                                                                    PGRES_COMMAND_OK);
742                                         strncpy(conn->result->cmdStatus, conn->workBuffer.data,
743                                                         CMDSTATUS_LEN);
744                                         conn->asyncStatus = PGASYNC_READY;
745                                         break;
746                                 case 'E':               /* error return */
747                                         if (pqGets(& conn->errorMessage, conn))
748                                                 return;
749                                         /* build an error result holding the error message */
750                                         saveErrorResult(conn);
751                                         conn->asyncStatus = PGASYNC_READY;
752                                         break;
753                                 case 'Z':               /* backend is ready for new query */
754                                         conn->asyncStatus = PGASYNC_IDLE;
755                                         break;
756                                 case 'I':               /* empty query */
757                                         /* read and throw away the closing '\0' */
758                                         if (pqGetc(&id, conn))
759                                                 return;
760                                         if (id != '\0')
761                                         {
762                                                 sprintf(noticeWorkspace,
763                                                                 "unexpected character %c following 'I'\n",
764                                                                 id);
765                                                 DONOTICE(conn, noticeWorkspace);
766                                         }
767                                         if (conn->result == NULL)
768                                                 conn->result = PQmakeEmptyPGresult(conn,
769                                                                                                           PGRES_EMPTY_QUERY);
770                                         conn->asyncStatus = PGASYNC_READY;
771                                         break;
772                                 case 'K':               /* secret key data from the backend */
773
774                                         /*
775                                          * This is expected only during backend startup, but
776                                          * it's just as easy to handle it as part of the main
777                                          * loop.  Save the data and continue processing.
778                                          */
779                                         if (pqGetInt(&(conn->be_pid), 4, conn))
780                                                 return;
781                                         if (pqGetInt(&(conn->be_key), 4, conn))
782                                                 return;
783                                         break;
784                                 case 'P':               /* synchronous (normal) portal */
785                                         if (pqGets(&conn->workBuffer, conn))
786                                                 return;
787                                         /* We pretty much ignore this message type... */
788                                         break;
789                                 case 'T':               /* row descriptions (start of query
790                                                                  * results) */
791                                         if (conn->result == NULL)
792                                         {
793                                                 /* First 'T' in a query sequence */
794                                                 if (getRowDescriptions(conn))
795                                                         return;
796                                         }
797                                         else
798                                         {
799
800                                                 /*
801                                                  * A new 'T' message is treated as the start of
802                                                  * another PGresult.  (It is not clear that this
803                                                  * is really possible with the current backend.)
804                                                  * We stop parsing until the application accepts
805                                                  * the current result.
806                                                  */
807                                                 conn->asyncStatus = PGASYNC_READY;
808                                                 return;
809                                         }
810                                         break;
811                                 case 'D':               /* ASCII data tuple */
812                                         if (conn->result != NULL)
813                                         {
814                                                 /* Read another tuple of a normal query response */
815                                                 if (getAnotherTuple(conn, FALSE))
816                                                         return;
817                                         }
818                                         else
819                                         {
820                                                 sprintf(noticeWorkspace,
821                                                                 "Backend sent D message without prior T\n");
822                                                 DONOTICE(conn, noticeWorkspace);
823                                                 /* Discard the unexpected message; good idea?? */
824                                                 conn->inStart = conn->inEnd;
825                                                 return;
826                                         }
827                                         break;
828                                 case 'B':               /* Binary data tuple */
829                                         if (conn->result != NULL)
830                                         {
831                                                 /* Read another tuple of a normal query response */
832                                                 if (getAnotherTuple(conn, TRUE))
833                                                         return;
834                                         }
835                                         else
836                                         {
837                                                 sprintf(noticeWorkspace,
838                                                                 "Backend sent B message without prior T\n");
839                                                 DONOTICE(conn, noticeWorkspace);
840                                                 /* Discard the unexpected message; good idea?? */
841                                                 conn->inStart = conn->inEnd;
842                                                 return;
843                                         }
844                                         break;
845                                 case 'G':               /* Start Copy In */
846                                         conn->asyncStatus = PGASYNC_COPY_IN;
847                                         break;
848                                 case 'H':               /* Start Copy Out */
849                                         conn->asyncStatus = PGASYNC_COPY_OUT;
850                                         break;
851                                 default:
852                                         printfPQExpBuffer(&conn->errorMessage,
853                                                 "Unknown protocol character '%c' read from backend.  "
854                                                 "(The protocol character is the first character the "
855                                                 "backend sends in response to a query it receives).\n",
856                                                 id);
857                                         /* build an error result holding the error message */
858                                         saveErrorResult(conn);
859                                         /* Discard the unexpected message; good idea?? */
860                                         conn->inStart = conn->inEnd;
861                                         conn->asyncStatus = PGASYNC_READY;
862                                         return;
863                         }                                       /* switch on protocol character */
864                 }
865                 /* Successfully consumed this message */
866                 conn->inStart = conn->inCursor;
867         }
868 }
869
870
871 /*
872  * parseInput subroutine to read a 'T' (row descriptions) message.
873  * We build a PGresult structure containing the attribute data.
874  * Returns: 0 if completed message, EOF if not enough data yet.
875  *
876  * Note that if we run out of data, we have to release the partially
877  * constructed PGresult, and rebuild it again next time.  Fortunately,
878  * that shouldn't happen often, since 'T' messages usually fit in a packet.
879  */
880
881 static int
882 getRowDescriptions(PGconn *conn)
883 {
884         PGresult   *result;
885         int                     nfields;
886         int                     i;
887
888         result = PQmakeEmptyPGresult(conn, PGRES_TUPLES_OK);
889
890         /* parseInput already read the 'T' label. */
891         /* the next two bytes are the number of fields  */
892         if (pqGetInt(&(result->numAttributes), 2, conn))
893         {
894                 PQclear(result);
895                 return EOF;
896         }
897         nfields = result->numAttributes;
898
899         /* allocate space for the attribute descriptors */
900         if (nfields > 0)
901         {
902                 result->attDescs = (PGresAttDesc *)
903                         pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
904                 MemSet((char *) result->attDescs, 0, nfields * sizeof(PGresAttDesc));
905         }
906
907         /* get type info */
908         for (i = 0; i < nfields; i++)
909         {
910                 int                     typid;
911                 int                     typlen;
912                 int                     atttypmod;
913
914                 if (pqGets(&conn->workBuffer, conn) ||
915                         pqGetInt(&typid, 4, conn) ||
916                         pqGetInt(&typlen, 2, conn) ||
917                         pqGetInt(&atttypmod, 4, conn))
918                 {
919                         PQclear(result);
920                         return EOF;
921                 }
922
923                 /*
924                  * Since pqGetInt treats 2-byte integers as unsigned, we need to
925                  * coerce the special value "-1" to signed form.  (-1 is sent for
926                  * variable-length fields.)  Formerly, libpq effectively did a
927                  * sign-extension on the 2-byte value by storing it in a signed
928                  * short. Now we only coerce the single value 65535 == -1; values
929                  * 32768..65534 are taken as valid field lengths.
930                  */
931                 if (typlen == 0xFFFF)
932                         typlen = -1;
933                 result->attDescs[i].name = pqResultStrdup(result,
934                                                                                                   conn->workBuffer.data);
935                 result->attDescs[i].typid = typid;
936                 result->attDescs[i].typlen = typlen;
937                 result->attDescs[i].atttypmod = atttypmod;
938         }
939
940         /* Success! */
941         conn->result = result;
942         return 0;
943 }
944
945 /*
946  * parseInput subroutine to read a 'B' or 'D' (row data) message.
947  * We add another tuple to the existing PGresult structure.
948  * Returns: 0 if completed message, EOF if error or not enough data yet.
949  *
950  * Note that if we run out of data, we have to suspend and reprocess
951  * the message after more data is received.  We keep a partially constructed
952  * tuple in conn->curTuple, and avoid reallocating already-allocated storage.
953  */
954
955 static int
956 getAnotherTuple(PGconn *conn, int binary)
957 {
958         PGresult   *result = conn->result;
959         int                     nfields = result->numAttributes;
960         PGresAttValue *tup;
961         /* the backend sends us a bitmap of which attributes are null */
962         char            std_bitmap[64]; /* used unless it doesn't fit */
963         char       *bitmap = std_bitmap;
964         int                     i;
965         size_t          nbytes;                 /* the number of bytes in bitmap  */
966         char            bmap;                   /* One byte of the bitmap */
967         int                     bitmap_index;   /* Its index */
968         int                     bitcnt;                 /* number of bits examined in current byte */
969         int                     vlen;                   /* length of the current field value */
970
971         result->binary = binary;
972
973         /* Allocate tuple space if first time for this data message */
974         if (conn->curTuple == NULL)
975         {
976                 conn->curTuple = (PGresAttValue *)
977                         pqResultAlloc(result, nfields * sizeof(PGresAttValue), TRUE);
978                 if (conn->curTuple == NULL)
979                         goto outOfMemory;
980                 MemSet((char *) conn->curTuple, 0, nfields * sizeof(PGresAttValue));
981         }
982         tup = conn->curTuple;
983
984         /* Get the null-value bitmap */
985         nbytes = (nfields + BYTELEN - 1) / BYTELEN;
986         /* malloc() only for unusually large field counts... */
987         if (nbytes > sizeof(std_bitmap))
988                 bitmap = (char *) malloc(nbytes);
989
990         if (pqGetnchar(bitmap, nbytes, conn))
991                 goto EOFexit;
992
993         /* Scan the fields */
994         bitmap_index = 0;
995         bmap = bitmap[bitmap_index];
996         bitcnt = 0;
997
998         for (i = 0; i < nfields; i++)
999         {
1000                 if (!(bmap & 0200))
1001                 {
1002                         /* if the field value is absent, make it a null string */
1003                         tup[i].value = result->null_field;
1004                         tup[i].len = NULL_LEN;
1005                 }
1006                 else
1007                 {
1008                         /* get the value length (the first four bytes are for length) */
1009                         if (pqGetInt(&vlen, 4, conn))
1010                                 goto EOFexit;
1011                         if (binary == 0)
1012                                 vlen = vlen - 4;
1013                         if (vlen < 0)
1014                                 vlen = 0;
1015                         if (tup[i].value == NULL)
1016                         {
1017                                 tup[i].value = (char *) pqResultAlloc(result, vlen + 1, binary);
1018                                 if (tup[i].value == NULL)
1019                                         goto outOfMemory;
1020                         }
1021                         tup[i].len = vlen;
1022                         /* read in the value */
1023                         if (vlen > 0)
1024                                 if (pqGetnchar((char *) (tup[i].value), vlen, conn))
1025                                         goto EOFexit;
1026                         /* we have to terminate this ourselves */
1027                         tup[i].value[vlen] = '\0';
1028                 }
1029                 /* advance the bitmap stuff */
1030                 bitcnt++;
1031                 if (bitcnt == BYTELEN)
1032                 {
1033                         bitmap_index++;
1034                         bmap = bitmap[bitmap_index];
1035                         bitcnt = 0;
1036                 }
1037                 else
1038                         bmap <<= 1;
1039         }
1040
1041         /* Success!  Store the completed tuple in the result */
1042         if (!addTuple(result, tup))
1043                 goto outOfMemory;
1044         /* and reset for a new message */
1045         conn->curTuple = NULL;
1046
1047         if (bitmap != std_bitmap)
1048                 free(bitmap);
1049         return 0;
1050
1051 outOfMemory:
1052         /* Replace partially constructed result with an error result */
1053         /* we do NOT use saveErrorResult() here, because of the likelihood
1054          * that there's not enough memory to concatenate messages...
1055          */
1056         pqClearAsyncResult(conn);
1057         printfPQExpBuffer(&conn->errorMessage,
1058                                           "getAnotherTuple() -- out of memory for result\n");
1059         conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1060         conn->asyncStatus = PGASYNC_READY;
1061         /* Discard the failed message --- good idea? */
1062         conn->inStart = conn->inEnd;
1063
1064 EOFexit:
1065         if (bitmap != std_bitmap)
1066                 free(bitmap);
1067         return EOF;
1068 }
1069
1070
1071 /*
1072  * PQisBusy
1073  *       Return TRUE if PQgetResult would block waiting for input.
1074  */
1075
1076 int
1077 PQisBusy(PGconn *conn)
1078 {
1079         if (!conn)
1080                 return FALSE;
1081
1082         /* Parse any available data, if our state permits. */
1083         parseInput(conn);
1084
1085         /* PQgetResult will return immediately in all states except BUSY. */
1086         return conn->asyncStatus == PGASYNC_BUSY;
1087 }
1088
1089
1090 /*
1091  * PQgetResult
1092  *        Get the next PGresult produced by a query.
1093  *        Returns NULL if and only if no query work remains.
1094  */
1095
1096 PGresult   *
1097 PQgetResult(PGconn *conn)
1098 {
1099         PGresult   *res;
1100
1101         if (!conn)
1102                 return NULL;
1103
1104         /* Parse any available data, if our state permits. */
1105         parseInput(conn);
1106
1107         /* If not ready to return something, block until we are. */
1108         while (conn->asyncStatus == PGASYNC_BUSY)
1109         {
1110                 /* Wait for some more data, and load it. */
1111                 if (pqWait(TRUE, FALSE, conn) ||
1112                         pqReadData(conn) < 0)
1113                 {
1114                         /* conn->errorMessage has been set by pqWait or pqReadData.
1115                          * We want to append it to any already-received error message.
1116                          */
1117                         saveErrorResult(conn);
1118                         conn->asyncStatus = PGASYNC_IDLE;
1119                         return prepareAsyncResult(conn);
1120                 }
1121                 /* Parse it. */
1122                 parseInput(conn);
1123         }
1124
1125         /* Return the appropriate thing. */
1126         switch (conn->asyncStatus)
1127         {
1128                 case PGASYNC_IDLE:
1129                         res = NULL;                     /* query is complete */
1130                         break;
1131                 case PGASYNC_READY:
1132                         res = prepareAsyncResult(conn);
1133                         /* Set the state back to BUSY, allowing parsing to proceed. */
1134                         conn->asyncStatus = PGASYNC_BUSY;
1135                         break;
1136                 case PGASYNC_COPY_IN:
1137                         res = PQmakeEmptyPGresult(conn, PGRES_COPY_IN);
1138                         break;
1139                 case PGASYNC_COPY_OUT:
1140                         res = PQmakeEmptyPGresult(conn, PGRES_COPY_OUT);
1141                         break;
1142                 default:
1143                         printfPQExpBuffer(&conn->errorMessage,
1144                                                           "PQgetResult: Unexpected asyncStatus %d\n",
1145                                                           (int) conn->asyncStatus);
1146                         res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1147                         break;
1148         }
1149
1150         return res;
1151 }
1152
1153
1154 /*
1155  * PQexec
1156  *        send a query to the backend and package up the result in a PGresult
1157  *
1158  * If the query was not even sent, return NULL; conn->errorMessage is set to
1159  * a relevant message.
1160  * If the query was sent, a new PGresult is returned (which could indicate
1161  * either success or failure).
1162  * The user is responsible for freeing the PGresult via PQclear()
1163  * when done with it.
1164  */
1165
1166 PGresult   *
1167 PQexec(PGconn *conn, const char *query)
1168 {
1169         PGresult   *result;
1170         PGresult   *lastResult;
1171         bool    savedblocking;
1172
1173         /*
1174          * we assume anyone calling PQexec wants blocking behaviour,
1175          * we force the blocking status of the connection to blocking
1176          * for the duration of this function and restore it on return
1177          */
1178         savedblocking = pqIsnonblocking(conn);
1179         if (PQsetnonblocking(conn, FALSE) == -1)
1180                 return NULL;
1181
1182         /*
1183          * Silently discard any prior query result that application didn't
1184          * eat. This is probably poor design, but it's here for backward
1185          * compatibility.
1186          */
1187         while ((result = PQgetResult(conn)) != NULL)
1188         {
1189                 if (result->resultStatus == PGRES_COPY_IN ||
1190                         result->resultStatus == PGRES_COPY_OUT)
1191                 {
1192                         PQclear(result);
1193                         printfPQExpBuffer(&conn->errorMessage,
1194                                 "PQexec: you gotta get out of a COPY state yourself.\n");
1195                         /* restore blocking status */
1196                         goto errout;
1197                 }
1198                 PQclear(result);
1199         }
1200
1201         /* OK to send the message */
1202         if (!PQsendQuery(conn, query))
1203                 goto errout;    /* restore blocking status */
1204
1205         /*
1206          * For backwards compatibility, return the last result if there are
1207          * more than one --- but merge error messages if we get more than one
1208          * error result.
1209          *
1210          * We have to stop if we see copy in/out, however.
1211          * We will resume parsing when application calls PQendcopy.
1212          */
1213         lastResult = NULL;
1214         while ((result = PQgetResult(conn)) != NULL)
1215         {
1216                 if (lastResult)
1217                 {
1218                         if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
1219                                 result->resultStatus == PGRES_FATAL_ERROR)
1220                         {
1221                                 pqCatenateResultError(lastResult, result->errMsg);
1222                                 PQclear(result);
1223                                 result = lastResult;
1224                                 /* Make sure PQerrorMessage agrees with catenated result */
1225                                 resetPQExpBuffer(&conn->errorMessage);
1226                                 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
1227                         }
1228                         else
1229                                 PQclear(lastResult);
1230                 }
1231                 lastResult = result;
1232                 if (result->resultStatus == PGRES_COPY_IN ||
1233                         result->resultStatus == PGRES_COPY_OUT)
1234                         break;
1235         }
1236
1237         if (PQsetnonblocking(conn, savedblocking) == -1)
1238                 return NULL;
1239         return lastResult;
1240
1241 errout:
1242         if (PQsetnonblocking(conn, savedblocking) == -1)
1243                 return NULL;
1244         return NULL;
1245 }
1246
1247
1248 /*
1249  * Attempt to read a Notice response message.
1250  * This is possible in several places, so we break it out as a subroutine.
1251  * Entry: 'N' flag character has already been consumed.
1252  * Exit: returns 0 if successfully consumed Notice message.
1253  *               returns EOF if not enough data.
1254  */
1255 static int
1256 getNotice(PGconn *conn)
1257 {
1258         /* Since the Notice might be pretty long, we create a temporary
1259          * PQExpBuffer rather than using conn->workBuffer.  workBuffer is
1260          * intended for stuff that is expected to be short.
1261          */
1262         PQExpBufferData  noticeBuf;
1263
1264         initPQExpBuffer(&noticeBuf);
1265         if (pqGets(&noticeBuf, conn))
1266         {
1267                 termPQExpBuffer(&noticeBuf);
1268                 return EOF;
1269         }
1270         DONOTICE(conn, noticeBuf.data);
1271         termPQExpBuffer(&noticeBuf);
1272         return 0;
1273 }
1274
1275 /*
1276  * Attempt to read a Notify response message.
1277  * This is possible in several places, so we break it out as a subroutine.
1278  * Entry: 'A' flag character has already been consumed.
1279  * Exit: returns 0 if successfully consumed Notify message.
1280  *               returns EOF if not enough data.
1281  */
1282 static int
1283 getNotify(PGconn *conn)
1284 {
1285         int                     be_pid;
1286         PGnotify   *newNotify;
1287
1288         if (pqGetInt(&be_pid, 4, conn))
1289                 return EOF;
1290         if (pqGets(&conn->workBuffer, conn))
1291                 return EOF;
1292         newNotify = (PGnotify *) malloc(sizeof(PGnotify));
1293         strncpy(newNotify->relname, conn->workBuffer.data, NAMEDATALEN);
1294         newNotify->be_pid = be_pid;
1295         DLAddTail(conn->notifyList, DLNewElem(newNotify));
1296         return 0;
1297 }
1298
1299 /*
1300  * PQnotifies
1301  *        returns a PGnotify* structure of the latest async notification
1302  * that has not yet been handled
1303  *
1304  * returns NULL, if there is currently
1305  * no unhandled async notification from the backend
1306  *
1307  * the CALLER is responsible for FREE'ing the structure returned
1308  */
1309
1310 PGnotify   *
1311 PQnotifies(PGconn *conn)
1312 {
1313         Dlelem     *e;
1314         PGnotify   *event;
1315
1316         if (!conn)
1317                 return NULL;
1318
1319         /* Parse any available data to see if we can extract NOTIFY messages. */
1320         parseInput(conn);
1321
1322         /* RemHead returns NULL if list is empty */
1323         e = DLRemHead(conn->notifyList);
1324         if (!e)
1325                 return NULL;
1326         event = (PGnotify *) DLE_VAL(e);
1327         DLFreeElem(e);
1328         return event;
1329 }
1330
1331 /*
1332  * PQgetline - gets a newline-terminated string from the backend.
1333  *
1334  * Chiefly here so that applications can use "COPY <rel> to stdout"
1335  * and read the output string.  Returns a null-terminated string in s.
1336  *
1337  * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
1338  * the terminating \n (like gets(3)).
1339  *
1340  * CAUTION: the caller is responsible for detecting the end-of-copy signal
1341  * (a line containing just "\.") when using this routine.
1342  *
1343  * RETURNS:
1344  *              EOF if it is detected or invalid arguments are given
1345  *              0 if EOL is reached (i.e., \n has been read)
1346  *                              (this is required for backward-compatibility -- this
1347  *                               routine used to always return EOF or 0, assuming that
1348  *                               the line ended within maxlen bytes.)
1349  *              1 in other cases (i.e., the buffer was filled before \n is reached)
1350  */
1351 int
1352 PQgetline(PGconn *conn, char *s, int maxlen)
1353 {
1354         int                     result = 1;             /* return value if buffer overflows */
1355
1356         if (!s || maxlen <= 0)
1357                 return EOF;
1358
1359         if (!conn || conn->sock < 0)
1360         {
1361                 *s = '\0';
1362                 return EOF;
1363         }
1364
1365         /*
1366          * Since this is a purely synchronous routine, we don't bother to
1367          * maintain conn->inCursor; there is no need to back up.
1368          */
1369         while (maxlen > 1)
1370         {
1371                 if (conn->inStart < conn->inEnd)
1372                 {
1373                         char            c = conn->inBuffer[conn->inStart++];
1374
1375                         if (c == '\n')
1376                         {
1377                                 result = 0;             /* success exit */
1378                                 break;
1379                         }
1380                         *s++ = c;
1381                         maxlen--;
1382                 }
1383                 else
1384                 {
1385                         /* need to load more data */
1386                         if (pqWait(TRUE, FALSE, conn) ||
1387                                 pqReadData(conn) < 0)
1388                         {
1389                                 result = EOF;
1390                                 break;
1391                         }
1392                 }
1393         }
1394         *s = '\0';
1395
1396         return result;
1397 }
1398
1399 /*
1400  * PQgetlineAsync - gets a newline-terminated string without blocking.
1401  *
1402  * This routine is for applications that want to do "COPY <rel> to stdout"
1403  * asynchronously, that is without blocking.  Having issued the COPY command
1404  * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
1405  * and this routine until the end-of-data signal is detected.  Unlike
1406  * PQgetline, this routine takes responsibility for detecting end-of-data.
1407  *
1408  * On each call, PQgetlineAsync will return data if a complete newline-
1409  * terminated data line is available in libpq's input buffer, or if the
1410  * incoming data line is too long to fit in the buffer offered by the caller.
1411  * Otherwise, no data is returned until the rest of the line arrives.
1412  *
1413  * If -1 is returned, the end-of-data signal has been recognized (and removed
1414  * from libpq's input buffer).  The caller *must* next call PQendcopy and
1415  * then return to normal processing.
1416  *
1417  * RETURNS:
1418  *       -1    if the end-of-copy-data marker has been recognized
1419  *       0         if no data is available
1420  *       >0    the number of bytes returned.
1421  * The data returned will not extend beyond a newline character.  If possible
1422  * a whole line will be returned at one time.  But if the buffer offered by
1423  * the caller is too small to hold a line sent by the backend, then a partial
1424  * data line will be returned.  This can be detected by testing whether the
1425  * last returned byte is '\n' or not.
1426  * The returned string is *not* null-terminated.
1427  */
1428
1429 int
1430 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
1431 {
1432         int                     avail;
1433
1434         if (!conn || conn->asyncStatus != PGASYNC_COPY_OUT)
1435                 return -1;                              /* we are not doing a copy... */
1436
1437         /*
1438          * Move data from libpq's buffer to the caller's. We want to accept
1439          * data only in units of whole lines, not partial lines.  This ensures
1440          * that we can recognize the terminator line "\\.\n".  (Otherwise, if
1441          * it happened to cross a packet/buffer boundary, we might hand the
1442          * first one or two characters off to the caller, which we shouldn't.)
1443          */
1444
1445         conn->inCursor = conn->inStart;
1446
1447         avail = bufsize;
1448         while (avail > 0 && conn->inCursor < conn->inEnd)
1449         {
1450                 char            c = conn->inBuffer[conn->inCursor++];
1451
1452                 *buffer++ = c;
1453                 --avail;
1454                 if (c == '\n')
1455                 {
1456                         /* Got a complete line; mark the data removed from libpq */
1457                         conn->inStart = conn->inCursor;
1458                         /* Is it the endmarker line? */
1459                         if (bufsize - avail == 3 && buffer[-3] == '\\' && buffer[-2] == '.')
1460                                 return -1;
1461                         /* No, return the data line to the caller */
1462                         return bufsize - avail;
1463                 }
1464         }
1465
1466         /*
1467          * We don't have a complete line. We'd prefer to leave it in libpq's
1468          * buffer until the rest arrives, but there is a special case: what if
1469          * the line is longer than the buffer the caller is offering us?  In
1470          * that case we'd better hand over a partial line, else we'd get into
1471          * an infinite loop. Do this in a way that ensures we can't
1472          * misrecognize a terminator line later: leave last 3 characters in
1473          * libpq buffer.
1474          */
1475         if (avail == 0 && bufsize > 3)
1476         {
1477                 conn->inStart = conn->inCursor - 3;
1478                 return bufsize - 3;
1479         }
1480         return 0;
1481 }
1482
1483 /*
1484  * PQputline -- sends a string to the backend.
1485  * Returns 0 if OK, EOF if not.
1486  *
1487  * Chiefly here so that applications can use "COPY <rel> from stdin".
1488  */
1489 int
1490 PQputline(PGconn *conn, const char *s)
1491 {
1492         if (!conn || conn->sock < 0)
1493                 return EOF;
1494         return pqPutnchar(s, strlen(s), conn);
1495 }
1496
1497 /*
1498  * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
1499  * Returns 0 if OK, EOF if not.
1500  */
1501 int
1502 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
1503 {
1504         if (!conn || conn->sock < 0)
1505                 return EOF;
1506         return pqPutnchar(buffer, nbytes, conn);
1507 }
1508
1509 /*
1510  * PQendcopy
1511  *              After completing the data transfer portion of a copy in/out,
1512  *              the application must call this routine to finish the command protocol.
1513  *
1514  * RETURNS:
1515  *              0 on success
1516  *              1 on failure
1517  */
1518 int
1519 PQendcopy(PGconn *conn)
1520 {
1521         PGresult   *result;
1522
1523         if (!conn)
1524                 return 0;
1525
1526         if (conn->asyncStatus != PGASYNC_COPY_IN &&
1527                 conn->asyncStatus != PGASYNC_COPY_OUT)
1528         {
1529                 printfPQExpBuffer(&conn->errorMessage,
1530                          "PQendcopy() -- I don't think there's a copy in progress.\n");
1531                 return 1;
1532         }
1533
1534         /*
1535          * make sure no data is waiting to be sent, 
1536          * abort if we are non-blocking and the flush fails
1537          */
1538         if (pqFlush(conn) && pqIsnonblocking(conn))
1539                 return (1);
1540
1541         /* non blocking connections may have to abort at this point. */
1542         if (pqIsnonblocking(conn) && PQisBusy(conn))
1543                 return (1);
1544
1545         /* Return to active duty */
1546         conn->asyncStatus = PGASYNC_BUSY;
1547         resetPQExpBuffer(&conn->errorMessage);
1548
1549         /* Wait for the completion response */
1550         result = PQgetResult(conn);
1551
1552         /* Expecting a successful result */
1553         if (result && result->resultStatus == PGRES_COMMAND_OK)
1554         {
1555                 PQclear(result);
1556                 return 0;
1557         }
1558
1559         /*
1560          * Trouble. The worst case is that we've lost sync with the backend
1561          * entirely due to application screwup of the copy in/out protocol. To
1562          * recover, reset the connection (talk about using a sledgehammer...)
1563          */
1564         PQclear(result);
1565
1566         if (conn->errorMessage.len > 0)
1567                 DONOTICE(conn, conn->errorMessage.data);
1568
1569         DONOTICE(conn, "PQendcopy: resetting connection\n");
1570
1571         PQreset(conn);
1572
1573         return 1;
1574 }
1575
1576
1577 /* ----------------
1578  *              PQfn -  Send a function call to the POSTGRES backend.
1579  *
1580  *              conn                    : backend connection
1581  *              fnid                    : function id
1582  *              result_buf              : pointer to result buffer (&int if integer)
1583  *              result_len              : length of return value.
1584  *              actual_result_len: actual length returned. (differs from result_len
1585  *                                                for varlena structures.)
1586  *              result_type             : If the result is an integer, this must be 1,
1587  *                                                otherwise this should be 0
1588  *              args                    : pointer to an array of function arguments.
1589  *                                                (each has length, if integer, and value/pointer)
1590  *              nargs                   : # of arguments in args array.
1591  *
1592  * RETURNS
1593  *              PGresult with status = PGRES_COMMAND_OK if successful.
1594  *                      *actual_result_len is > 0 if there is a return value, 0 if not.
1595  *              PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
1596  *              NULL on communications failure.  conn->errorMessage will be set.
1597  * ----------------
1598  */
1599
1600 PGresult   *
1601 PQfn(PGconn *conn,
1602          int fnid,
1603          int *result_buf,
1604          int *actual_result_len,
1605          int result_is_int,
1606          const PQArgBlock *args,
1607          int nargs)
1608 {
1609         bool            needInput = false;
1610         ExecStatusType status = PGRES_FATAL_ERROR;
1611         char            id;
1612         int                     i;
1613
1614         *actual_result_len = 0;
1615
1616         if (!conn)
1617                 return NULL;
1618
1619         /* clear the error string */
1620         resetPQExpBuffer(&conn->errorMessage);
1621
1622         if (conn->sock < 0 || conn->asyncStatus != PGASYNC_IDLE ||
1623                 conn->result != NULL)
1624         {
1625                 printfPQExpBuffer(&conn->errorMessage,
1626                                                   "PQfn() -- connection in wrong state\n");
1627                 return NULL;
1628         }
1629
1630         if (pqPuts("F ", conn) ||                       /* function */
1631                 pqPutInt(fnid, 4, conn) ||              /* function id */
1632                 pqPutInt(nargs, 4, conn))               /* # of args */
1633         {
1634                 handleSendFailure(conn);
1635                 return NULL;
1636         }
1637
1638         for (i = 0; i < nargs; ++i)
1639         {                                                       /* len.int4 + contents     */
1640                 if (pqPutInt(args[i].len, 4, conn))
1641                 {
1642                         handleSendFailure(conn);
1643                         return NULL;
1644                 }
1645
1646                 if (args[i].isint)
1647                 {
1648                         if (pqPutInt(args[i].u.integer, 4, conn))
1649                         {
1650                                 handleSendFailure(conn);
1651                                 return NULL;
1652                         }
1653                 }
1654                 else
1655                 {
1656                         if (pqPutnchar((char *) args[i].u.ptr, args[i].len, conn))
1657                         {
1658                                 handleSendFailure(conn);
1659                                 return NULL;
1660                         }
1661                 }
1662         }
1663         if (pqFlush(conn))
1664         {
1665                 handleSendFailure(conn);
1666                 return NULL;
1667         }
1668
1669         for (;;)
1670         {
1671                 if (needInput)
1672                 {
1673                         /* Wait for some data to arrive (or for the channel to close) */
1674                         if (pqWait(TRUE, FALSE, conn) ||
1675                                 pqReadData(conn) < 0)
1676                                 break;
1677                 }
1678
1679                 /*
1680                  * Scan the message. If we run out of data, loop around to try
1681                  * again.
1682                  */
1683                 conn->inCursor = conn->inStart;
1684                 needInput = true;
1685
1686                 if (pqGetc(&id, conn))
1687                         continue;
1688
1689                 /*
1690                  * We should see V or E response to the command, but might get N
1691                  * and/or A notices first. We also need to swallow the final Z
1692                  * before returning.
1693                  */
1694                 switch (id)
1695                 {
1696                         case 'V':                       /* function result */
1697                                 if (pqGetc(&id, conn))
1698                                         continue;
1699                                 if (id == 'G')
1700                                 {
1701                                         /* function returned nonempty value */
1702                                         if (pqGetInt(actual_result_len, 4, conn))
1703                                                 continue;
1704                                         if (result_is_int)
1705                                         {
1706                                                 if (pqGetInt(result_buf, 4, conn))
1707                                                         continue;
1708                                         }
1709                                         else
1710                                         {
1711                                                 if (pqGetnchar((char *) result_buf,
1712                                                                            *actual_result_len,
1713                                                                            conn))
1714                                                         continue;
1715                                         }
1716                                         if (pqGetc(&id, conn))          /* get the last '0' */
1717                                                 continue;
1718                                 }
1719                                 if (id == '0')
1720                                 {
1721                                         /* correctly finished function result message */
1722                                         status = PGRES_COMMAND_OK;
1723                                 }
1724                                 else
1725                                 {
1726                                         /* The backend violates the protocol. */
1727                                         printfPQExpBuffer(&conn->errorMessage,
1728                                                                           "FATAL: PQfn: protocol error: id=0x%x\n",
1729                                                                           id);
1730                                         saveErrorResult(conn);
1731                                         conn->inStart = conn->inCursor;
1732                                         return prepareAsyncResult(conn);
1733                                 }
1734                                 break;
1735                         case 'E':                       /* error return */
1736                                 if (pqGets(&conn->errorMessage, conn))
1737                                         continue;
1738                                 /* build an error result holding the error message */
1739                                 saveErrorResult(conn);
1740                                 status = PGRES_FATAL_ERROR;
1741                                 break;
1742                         case 'A':                       /* notify message */
1743                                 /* handle notify and go back to processing return values */
1744                                 if (getNotify(conn))
1745                                         continue;
1746                                 break;
1747                         case 'N':                       /* notice */
1748                                 /* handle notice and go back to processing return values */
1749                                 if (getNotice(conn))
1750                                         continue;
1751                                 break;
1752                         case 'Z':                       /* backend is ready for new query */
1753                                 /* consume the message and exit */
1754                                 conn->inStart = conn->inCursor;
1755                                 /* if we saved a result object (probably an error), use it */
1756                                 if (conn->result)
1757                                         return prepareAsyncResult(conn);
1758                                 return PQmakeEmptyPGresult(conn, status);
1759                         default:
1760                                 /* The backend violates the protocol. */
1761                                 printfPQExpBuffer(&conn->errorMessage,
1762                                                                   "FATAL: PQfn: protocol error: id=0x%x\n",
1763                                                                   id);
1764                                 saveErrorResult(conn);
1765                                 conn->inStart = conn->inCursor;
1766                                 return prepareAsyncResult(conn);
1767                 }
1768                 /* Completed this message, keep going */
1769                 conn->inStart = conn->inCursor;
1770                 needInput = false;
1771         }
1772
1773         /* We fall out of the loop only upon failing to read data.
1774          * conn->errorMessage has been set by pqWait or pqReadData.
1775          * We want to append it to any already-received error message.
1776          */
1777         saveErrorResult(conn);
1778         return prepareAsyncResult(conn);
1779 }
1780
1781
1782 /* ====== accessor funcs for PGresult ======== */
1783
1784 ExecStatusType
1785 PQresultStatus(const PGresult *res)
1786 {
1787         if (!res)
1788                 return PGRES_NONFATAL_ERROR;
1789         return res->resultStatus;
1790 }
1791
1792 char *
1793 PQresStatus(ExecStatusType status)
1794 {
1795         if (status < 0 || status >= sizeof pgresStatus / sizeof pgresStatus[0])
1796                 return "Invalid ExecStatusType code";
1797         return pgresStatus[status];
1798 }
1799
1800 char *
1801 PQresultErrorMessage(const PGresult *res)
1802 {
1803         if (!res || !res->errMsg)
1804                 return "";
1805         return res->errMsg;
1806 }
1807
1808 int
1809 PQntuples(const PGresult *res)
1810 {
1811         if (!res)
1812                 return 0;
1813         return res->ntups;
1814 }
1815
1816 int
1817 PQnfields(const PGresult *res)
1818 {
1819         if (!res)
1820                 return 0;
1821         return res->numAttributes;
1822 }
1823
1824 int
1825 PQbinaryTuples(const PGresult *res)
1826 {
1827         if (!res)
1828                 return 0;
1829         return res->binary;
1830 }
1831
1832 /*
1833  * Helper routines to range-check field numbers and tuple numbers.
1834  * Return TRUE if OK, FALSE if not
1835  */
1836
1837 static int
1838 check_field_number(const char *routineName, const PGresult *res, int field_num)
1839 {
1840         char noticeBuf[128];
1841
1842         if (!res)
1843                 return FALSE;                   /* no way to display error message... */
1844         if (field_num < 0 || field_num >= res->numAttributes)
1845         {
1846                 if (res->noticeHook)
1847                 {
1848                         sprintf(noticeBuf,
1849                                         "%s: ERROR! field number %d is out of range 0..%d\n",
1850                                         routineName, field_num, res->numAttributes - 1);
1851                         DONOTICE(res, noticeBuf);
1852                 }
1853                 return FALSE;
1854         }
1855         return TRUE;
1856 }
1857
1858 static int
1859 check_tuple_field_number(const char *routineName, const PGresult *res,
1860                                                  int tup_num, int field_num)
1861 {
1862         char noticeBuf[128];
1863
1864         if (!res)
1865                 return FALSE;                   /* no way to display error message... */
1866         if (tup_num < 0 || tup_num >= res->ntups)
1867         {
1868                 if (res->noticeHook)
1869                 {
1870                         sprintf(noticeBuf,
1871                                         "%s: ERROR! tuple number %d is out of range 0..%d\n",
1872                                         routineName, tup_num, res->ntups - 1);
1873                         DONOTICE(res, noticeBuf);
1874                 }
1875                 return FALSE;
1876         }
1877         if (field_num < 0 || field_num >= res->numAttributes)
1878         {
1879                 if (res->noticeHook)
1880                 {
1881                         sprintf(noticeBuf,
1882                                         "%s: ERROR! field number %d is out of range 0..%d\n",
1883                                         routineName, field_num, res->numAttributes - 1);
1884                         DONOTICE(res, noticeBuf);
1885                 }
1886                 return FALSE;
1887         }
1888         return TRUE;
1889 }
1890
1891 /*
1892    returns NULL if the field_num is invalid
1893 */
1894 char *
1895 PQfname(const PGresult *res, int field_num)
1896 {
1897         if (!check_field_number("PQfname", res, field_num))
1898                 return NULL;
1899         if (res->attDescs)
1900                 return res->attDescs[field_num].name;
1901         else
1902                 return NULL;
1903 }
1904
1905 /*
1906    returns -1 on a bad field name
1907 */
1908 int
1909 PQfnumber(const PGresult *res, const char *field_name)
1910 {
1911         int                     i;
1912         char       *field_case;
1913
1914         if (!res)
1915                 return -1;
1916
1917         if (field_name == NULL ||
1918                 field_name[0] == '\0' ||
1919                 res->attDescs == NULL)
1920                 return -1;
1921
1922         field_case = strdup(field_name);
1923         if (*field_case == '"')
1924         {
1925                 strcpy(field_case, field_case + 1);
1926                 *(field_case + strlen(field_case) - 1) = '\0';
1927         }
1928         else
1929                 for (i = 0; field_case[i]; i++)
1930                         if (isascii((unsigned char) field_case[i]) &&
1931                                 isupper(field_case[i]))
1932                                 field_case[i] = tolower(field_case[i]);
1933
1934         for (i = 0; i < res->numAttributes; i++)
1935         {
1936                 if (strcmp(field_case, res->attDescs[i].name) == 0)
1937                 {
1938                         free(field_case);
1939                         return i;
1940                 }
1941         }
1942         free(field_case);
1943         return -1;
1944 }
1945
1946 Oid
1947 PQftype(const PGresult *res, int field_num)
1948 {
1949         if (!check_field_number("PQftype", res, field_num))
1950                 return InvalidOid;
1951         if (res->attDescs)
1952                 return res->attDescs[field_num].typid;
1953         else
1954                 return InvalidOid;
1955 }
1956
1957 int
1958 PQfsize(const PGresult *res, int field_num)
1959 {
1960         if (!check_field_number("PQfsize", res, field_num))
1961                 return 0;
1962         if (res->attDescs)
1963                 return res->attDescs[field_num].typlen;
1964         else
1965                 return 0;
1966 }
1967
1968 int
1969 PQfmod(const PGresult *res, int field_num)
1970 {
1971         if (!check_field_number("PQfmod", res, field_num))
1972                 return 0;
1973         if (res->attDescs)
1974                 return res->attDescs[field_num].atttypmod;
1975         else
1976                 return 0;
1977 }
1978
1979 char *
1980 PQcmdStatus(PGresult *res)
1981 {
1982         if (!res)
1983                 return NULL;
1984         return res->cmdStatus;
1985 }
1986
1987 /*
1988    PQoidStatus -
1989         if the last command was an INSERT, return the oid string
1990         if not, return ""
1991 */
1992 char *
1993 PQoidStatus(const PGresult *res)
1994 {
1995         /* 
1996          * This must be enough to hold the result. Don't laugh, this is
1997          * better than what this function used to do.
1998          */
1999         static char buf[24];
2000
2001         size_t len;
2002
2003         if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2004                 return "";
2005
2006         len = strspn(res->cmdStatus + 7, "0123456789");
2007         if (len > 23)
2008                 len = 23;
2009         strncpy(buf, res->cmdStatus + 7, len);
2010         buf[23] = '\0';
2011
2012         return buf;
2013 }
2014
2015 /*
2016   PQoidValue -
2017         a perhaps preferable form of the above which just returns
2018         an Oid type
2019 */
2020 Oid
2021 PQoidValue(const PGresult *res)
2022 {
2023     char * endptr = NULL;
2024     long int result;
2025
2026     if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2027         return InvalidOid;
2028
2029     errno = 0;
2030     result = strtoul(res->cmdStatus + 7, &endptr, 10);
2031
2032     if (!endptr || (*endptr != ' ' && *endptr != '\0') || errno == ERANGE)
2033         return InvalidOid;
2034     else
2035         return (Oid)result;
2036 }
2037
2038 /*
2039    PQcmdTuples -
2040         if the last command was an INSERT/UPDATE/DELETE, return number
2041         of inserted/affected tuples, if not, return ""
2042 */
2043 char *
2044 PQcmdTuples(PGresult *res)
2045 {
2046         char noticeBuf[128];
2047
2048         if (!res)
2049                 return "";
2050
2051         if (strncmp(res->cmdStatus, "INSERT", 6) == 0 ||
2052                 strncmp(res->cmdStatus, "DELETE", 6) == 0 ||
2053                 strncmp(res->cmdStatus, "UPDATE", 6) == 0)
2054         {
2055                 char       *p = res->cmdStatus + 6;
2056
2057                 if (*p == 0)
2058                 {
2059                         if (res->noticeHook)
2060                         {
2061                                 sprintf(noticeBuf,
2062                                                 "PQcmdTuples (%s) -- bad input from server\n",
2063                                                 res->cmdStatus);
2064                                 DONOTICE(res, noticeBuf);
2065                         }
2066                         return "";
2067                 }
2068                 p++;
2069                 if (*(res->cmdStatus) != 'I')   /* UPDATE/DELETE */
2070                         return p;
2071                 while (*p != ' ' && *p)
2072                         p++;                            /* INSERT: skip oid */
2073                 if (*p == 0)
2074                 {
2075                         if (res->noticeHook)
2076                         {
2077                                 sprintf(noticeBuf,
2078                                          "PQcmdTuples (INSERT) -- there's no # of tuples\n");
2079                                 DONOTICE(res, noticeBuf);
2080                         }
2081                         return "";
2082                 }
2083                 p++;
2084                 return p;
2085         }
2086         return "";
2087 }
2088
2089 /*
2090    PQgetvalue:
2091         return the value of field 'field_num' of row 'tup_num'
2092
2093         If res is binary, then the value returned is NOT a null-terminated
2094         ASCII string, but the binary representation in the server's native
2095         format.
2096
2097         if res is not binary, a null-terminated ASCII string is returned.
2098 */
2099 char *
2100 PQgetvalue(const PGresult *res, int tup_num, int field_num)
2101 {
2102         if (!check_tuple_field_number("PQgetvalue", res, tup_num, field_num))
2103                 return NULL;
2104         return res->tuples[tup_num][field_num].value;
2105 }
2106
2107 /* PQgetlength:
2108          returns the length of a field value in bytes.  If res is binary,
2109          i.e. a result of a binary portal, then the length returned does
2110          NOT include the size field of the varlena.  (The data returned
2111          by PQgetvalue doesn't either.)
2112 */
2113 int
2114 PQgetlength(const PGresult *res, int tup_num, int field_num)
2115 {
2116         if (!check_tuple_field_number("PQgetlength", res, tup_num, field_num))
2117                 return 0;
2118         if (res->tuples[tup_num][field_num].len != NULL_LEN)
2119                 return res->tuples[tup_num][field_num].len;
2120         else
2121                 return 0;
2122 }
2123
2124 /* PQgetisnull:
2125          returns the null status of a field value.
2126 */
2127 int
2128 PQgetisnull(const PGresult *res, int tup_num, int field_num)
2129 {
2130         if (!check_tuple_field_number("PQgetisnull", res, tup_num, field_num))
2131                 return 1;                               /* pretend it is null */
2132         if (res->tuples[tup_num][field_num].len == NULL_LEN)
2133                 return 1;
2134         else
2135                 return 0;
2136 }
2137
2138 /* PQsetnonblocking:
2139          sets the PGconn's database connection non-blocking if the arg is TRUE
2140          or makes it non-blocking if the arg is FALSE, this will not protect
2141          you from PQexec(), you'll only be safe when using the non-blocking
2142          API
2143          Needs to be called only on a connected database connection.
2144 */
2145
2146 int
2147 PQsetnonblocking(PGconn *conn, int arg)
2148 {
2149
2150         arg = (arg == TRUE) ? 1 : 0;
2151         /* early out if the socket is already in the state requested */
2152         if (arg == conn->nonblocking)
2153                 return (0);
2154
2155         /*
2156          * to guarantee constancy for flushing/query/result-polling behavior
2157          * we need to flush the send queue at this point in order to guarantee
2158          * proper behavior.
2159          * this is ok because either they are making a transition
2160          *  _from_ or _to_ blocking mode, either way we can block them.
2161          */
2162         /* if we are going from blocking to non-blocking flush here */
2163         if (pqFlush(conn))
2164                 return (-1);
2165
2166         conn->nonblocking = arg;
2167
2168         return (0);
2169 }
2170
2171 /* return the blocking status of the database connection, TRUE == nonblocking,
2172          FALSE == blocking
2173 */
2174 int
2175 PQisnonblocking(const PGconn *conn)
2176 {
2177
2178         return (pqIsnonblocking(conn));
2179 }
2180
2181 /* try to force data out, really only useful for non-blocking users */
2182 int
2183 PQflush(PGconn *conn)
2184 {
2185
2186         return (pqFlush(conn));
2187 }