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