]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-exec.c
Add PQdescribePrepared, PQdescribePortal, and related functions to libpq
[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-2006, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/interfaces/libpq/fe-exec.c,v 1.190 2006/08/18 19:52:39 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres_fe.h"
16
17 #include <ctype.h>
18 #include <fcntl.h>
19
20 #include "libpq-fe.h"
21 #include "libpq-int.h"
22
23 #include "mb/pg_wchar.h"
24
25 #ifdef WIN32
26 #include "win32.h"
27 #else
28 #include <unistd.h>
29 #endif
30
31 /* keep this in same order as ExecStatusType in libpq-fe.h */
32 char       *const pgresStatus[] = {
33         "PGRES_EMPTY_QUERY",
34         "PGRES_COMMAND_OK",
35         "PGRES_TUPLES_OK",
36         "PGRES_COPY_OUT",
37         "PGRES_COPY_IN",
38         "PGRES_BAD_RESPONSE",
39         "PGRES_NONFATAL_ERROR",
40         "PGRES_FATAL_ERROR"
41 };
42
43 /*
44  * static state needed by PQescapeString and PQescapeBytea; initialize to
45  * values that result in backward-compatible behavior
46  */
47 static int      static_client_encoding = PG_SQL_ASCII;
48 static bool     static_std_strings = false;
49
50
51 static bool PQsendQueryStart(PGconn *conn);
52 static int PQsendQueryGuts(PGconn *conn,
53                                 const char *command,
54                                 const char *stmtName,
55                                 int nParams,
56                                 const Oid *paramTypes,
57                                 const char *const * paramValues,
58                                 const int *paramLengths,
59                                 const int *paramFormats,
60                                 int resultFormat);
61 static void parseInput(PGconn *conn);
62 static bool PQexecStart(PGconn *conn);
63 static PGresult *PQexecFinish(PGconn *conn);
64 static int      PQsendDescribe(PGconn *conn, char desc_type,
65                                                    const char *desc_target);
66
67
68 /* ----------------
69  * Space management for PGresult.
70  *
71  * Formerly, libpq did a separate malloc() for each field of each tuple
72  * returned by a query.  This was remarkably expensive --- malloc/free
73  * consumed a sizable part of the application's runtime.  And there is
74  * no real need to keep track of the fields separately, since they will
75  * all be freed together when the PGresult is released.  So now, we grab
76  * large blocks of storage from malloc and allocate space for query data
77  * within these blocks, using a trivially simple allocator.  This reduces
78  * the number of malloc/free calls dramatically, and it also avoids
79  * fragmentation of the malloc storage arena.
80  * The PGresult structure itself is still malloc'd separately.  We could
81  * combine it with the first allocation block, but that would waste space
82  * for the common case that no extra storage is actually needed (that is,
83  * the SQL command did not return tuples).
84  *
85  * We also malloc the top-level array of tuple pointers separately, because
86  * we need to be able to enlarge it via realloc, and our trivial space
87  * allocator doesn't handle that effectively.  (Too bad the FE/BE protocol
88  * doesn't tell us up front how many tuples will be returned.)
89  * All other subsidiary storage for a PGresult is kept in PGresult_data blocks
90  * of size PGRESULT_DATA_BLOCKSIZE.  The overhead at the start of each block
91  * is just a link to the next one, if any.      Free-space management info is
92  * kept in the owning PGresult.
93  * A query returning a small amount of data will thus require three malloc
94  * calls: one for the PGresult, one for the tuples pointer array, and one
95  * PGresult_data block.
96  *
97  * Only the most recently allocated PGresult_data block is a candidate to
98  * have more stuff added to it --- any extra space left over in older blocks
99  * is wasted.  We could be smarter and search the whole chain, but the point
100  * here is to be simple and fast.  Typical applications do not keep a PGresult
101  * around very long anyway, so some wasted space within one is not a problem.
102  *
103  * Tuning constants for the space allocator are:
104  * PGRESULT_DATA_BLOCKSIZE: size of a standard allocation block, in bytes
105  * PGRESULT_ALIGN_BOUNDARY: assumed alignment requirement for binary data
106  * PGRESULT_SEP_ALLOC_THRESHOLD: objects bigger than this are given separate
107  *       blocks, instead of being crammed into a regular allocation block.
108  * Requirements for correct function are:
109  * PGRESULT_ALIGN_BOUNDARY must be a multiple of the alignment requirements
110  *              of all machine data types.      (Currently this is set from configure
111  *              tests, so it should be OK automatically.)
112  * PGRESULT_SEP_ALLOC_THRESHOLD + PGRESULT_BLOCK_OVERHEAD <=
113  *                      PGRESULT_DATA_BLOCKSIZE
114  *              pqResultAlloc assumes an object smaller than the threshold will fit
115  *              in a new block.
116  * The amount of space wasted at the end of a block could be as much as
117  * PGRESULT_SEP_ALLOC_THRESHOLD, so it doesn't pay to make that too large.
118  * ----------------
119  */
120
121 #define PGRESULT_DATA_BLOCKSIZE         2048
122 #define PGRESULT_ALIGN_BOUNDARY         MAXIMUM_ALIGNOF         /* from configure */
123 #define PGRESULT_BLOCK_OVERHEAD         Max(sizeof(PGresult_data), PGRESULT_ALIGN_BOUNDARY)
124 #define PGRESULT_SEP_ALLOC_THRESHOLD    (PGRESULT_DATA_BLOCKSIZE / 2)
125
126
127 /*
128  * PQmakeEmptyPGresult
129  *       returns a newly allocated, initialized PGresult with given status.
130  *       If conn is not NULL and status indicates an error, the conn's
131  *       errorMessage is copied.
132  *
133  * Note this is exported --- you wouldn't think an application would need
134  * to build its own PGresults, but this has proven useful in both libpgtcl
135  * and the Perl5 interface, so maybe it's not so unreasonable.
136  */
137
138 PGresult *
139 PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
140 {
141         PGresult   *result;
142
143         result = (PGresult *) malloc(sizeof(PGresult));
144         if (!result)
145                 return NULL;
146
147         result->ntups = 0;
148         result->numAttributes = 0;
149         result->attDescs = NULL;
150         result->tuples = NULL;
151         result->tupArrSize = 0;
152         result->numParameters = 0;
153         result->paramDescs = NULL;
154         result->resultStatus = status;
155         result->cmdStatus[0] = '\0';
156         result->binary = 0;
157         result->errMsg = NULL;
158         result->errFields = NULL;
159         result->null_field[0] = '\0';
160         result->curBlock = NULL;
161         result->curOffset = 0;
162         result->spaceLeft = 0;
163
164         if (conn)
165         {
166                 /* copy connection data we might need for operations on PGresult */
167                 result->noticeHooks = conn->noticeHooks;
168                 result->client_encoding = conn->client_encoding;
169
170                 /* consider copying conn's errorMessage */
171                 switch (status)
172                 {
173                         case PGRES_EMPTY_QUERY:
174                         case PGRES_COMMAND_OK:
175                         case PGRES_TUPLES_OK:
176                         case PGRES_COPY_OUT:
177                         case PGRES_COPY_IN:
178                                 /* non-error cases */
179                                 break;
180                         default:
181                                 pqSetResultError(result, conn->errorMessage.data);
182                                 break;
183                 }
184         }
185         else
186         {
187                 /* defaults... */
188                 result->noticeHooks.noticeRec = NULL;
189                 result->noticeHooks.noticeRecArg = NULL;
190                 result->noticeHooks.noticeProc = NULL;
191                 result->noticeHooks.noticeProcArg = NULL;
192                 result->client_encoding = PG_SQL_ASCII;
193         }
194
195         return result;
196 }
197
198 /*
199  * pqResultAlloc -
200  *              Allocate subsidiary storage for a PGresult.
201  *
202  * nBytes is the amount of space needed for the object.
203  * If isBinary is true, we assume that we need to align the object on
204  * a machine allocation boundary.
205  * If isBinary is false, we assume the object is a char string and can
206  * be allocated on any byte boundary.
207  */
208 void *
209 pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
210 {
211         char       *space;
212         PGresult_data *block;
213
214         if (!res)
215                 return NULL;
216
217         if (nBytes <= 0)
218                 return res->null_field;
219
220         /*
221          * If alignment is needed, round up the current position to an alignment
222          * boundary.
223          */
224         if (isBinary)
225         {
226                 int                     offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
227
228                 if (offset)
229                 {
230                         res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
231                         res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
232                 }
233         }
234
235         /* If there's enough space in the current block, no problem. */
236         if (nBytes <= (size_t) res->spaceLeft)
237         {
238                 space = res->curBlock->space + res->curOffset;
239                 res->curOffset += nBytes;
240                 res->spaceLeft -= nBytes;
241                 return space;
242         }
243
244         /*
245          * If the requested object is very large, give it its own block; this
246          * avoids wasting what might be most of the current block to start a new
247          * block.  (We'd have to special-case requests bigger than the block size
248          * anyway.)  The object is always given binary alignment in this case.
249          */
250         if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
251         {
252                 block = (PGresult_data *) malloc(nBytes + PGRESULT_BLOCK_OVERHEAD);
253                 if (!block)
254                         return NULL;
255                 space = block->space + PGRESULT_BLOCK_OVERHEAD;
256                 if (res->curBlock)
257                 {
258                         /*
259                          * Tuck special block below the active block, so that we don't
260                          * have to waste the free space in the active block.
261                          */
262                         block->next = res->curBlock->next;
263                         res->curBlock->next = block;
264                 }
265                 else
266                 {
267                         /* Must set up the new block as the first active block. */
268                         block->next = NULL;
269                         res->curBlock = block;
270                         res->spaceLeft = 0; /* be sure it's marked full */
271                 }
272                 return space;
273         }
274
275         /* Otherwise, start a new block. */
276         block = (PGresult_data *) malloc(PGRESULT_DATA_BLOCKSIZE);
277         if (!block)
278                 return NULL;
279         block->next = res->curBlock;
280         res->curBlock = block;
281         if (isBinary)
282         {
283                 /* object needs full alignment */
284                 res->curOffset = PGRESULT_BLOCK_OVERHEAD;
285                 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - PGRESULT_BLOCK_OVERHEAD;
286         }
287         else
288         {
289                 /* we can cram it right after the overhead pointer */
290                 res->curOffset = sizeof(PGresult_data);
291                 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - sizeof(PGresult_data);
292         }
293
294         space = block->space + res->curOffset;
295         res->curOffset += nBytes;
296         res->spaceLeft -= nBytes;
297         return space;
298 }
299
300 /*
301  * pqResultStrdup -
302  *              Like strdup, but the space is subsidiary PGresult space.
303  */
304 char *
305 pqResultStrdup(PGresult *res, const char *str)
306 {
307         char       *space = (char *) pqResultAlloc(res, strlen(str) + 1, FALSE);
308
309         if (space)
310                 strcpy(space, str);
311         return space;
312 }
313
314 /*
315  * pqSetResultError -
316  *              assign a new error message to a PGresult
317  */
318 void
319 pqSetResultError(PGresult *res, const char *msg)
320 {
321         if (!res)
322                 return;
323         if (msg && *msg)
324                 res->errMsg = pqResultStrdup(res, msg);
325         else
326                 res->errMsg = NULL;
327 }
328
329 /*
330  * pqCatenateResultError -
331  *              concatenate a new error message to the one already in a PGresult
332  */
333 void
334 pqCatenateResultError(PGresult *res, const char *msg)
335 {
336         PQExpBufferData errorBuf;
337
338         if (!res || !msg)
339                 return;
340         initPQExpBuffer(&errorBuf);
341         if (res->errMsg)
342                 appendPQExpBufferStr(&errorBuf, res->errMsg);
343         appendPQExpBufferStr(&errorBuf, msg);
344         pqSetResultError(res, errorBuf.data);
345         termPQExpBuffer(&errorBuf);
346 }
347
348 /*
349  * PQclear -
350  *        free's the memory associated with a PGresult
351  */
352 void
353 PQclear(PGresult *res)
354 {
355         PGresult_data *block;
356
357         if (!res)
358                 return;
359
360         /* Free all the subsidiary blocks */
361         while ((block = res->curBlock) != NULL)
362         {
363                 res->curBlock = block->next;
364                 free(block);
365         }
366
367         /* Free the top-level tuple pointer array */
368         if (res->tuples)
369                 free(res->tuples);
370
371         /* zero out the pointer fields to catch programming errors */
372         res->attDescs = NULL;
373         res->tuples = NULL;
374         res->paramDescs = NULL;
375         res->errFields = NULL;
376         /* res->curBlock was zeroed out earlier */
377
378         /* Free the PGresult structure itself */
379         free(res);
380 }
381
382 /*
383  * Handy subroutine to deallocate any partially constructed async result.
384  */
385
386 void
387 pqClearAsyncResult(PGconn *conn)
388 {
389         if (conn->result)
390                 PQclear(conn->result);
391         conn->result = NULL;
392         conn->curTuple = NULL;
393 }
394
395 /*
396  * This subroutine deletes any existing async result, sets conn->result
397  * to a PGresult with status PGRES_FATAL_ERROR, and stores the current
398  * contents of conn->errorMessage into that result.  It differs from a
399  * plain call on PQmakeEmptyPGresult() in that if there is already an
400  * async result with status PGRES_FATAL_ERROR, the current error message
401  * is APPENDED to the old error message instead of replacing it.  This
402  * behavior lets us report multiple error conditions properly, if necessary.
403  * (An example where this is needed is when the backend sends an 'E' message
404  * and immediately closes the connection --- we want to report both the
405  * backend error and the connection closure error.)
406  */
407 void
408 pqSaveErrorResult(PGconn *conn)
409 {
410         /*
411          * If no old async result, just let PQmakeEmptyPGresult make one. Likewise
412          * if old result is not an error message.
413          */
414         if (conn->result == NULL ||
415                 conn->result->resultStatus != PGRES_FATAL_ERROR ||
416                 conn->result->errMsg == NULL)
417         {
418                 pqClearAsyncResult(conn);
419                 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
420         }
421         else
422         {
423                 /* Else, concatenate error message to existing async result. */
424                 pqCatenateResultError(conn->result, conn->errorMessage.data);
425         }
426 }
427
428 /*
429  * This subroutine prepares an async result object for return to the caller.
430  * If there is not already an async result object, build an error object
431  * using whatever is in conn->errorMessage.  In any case, clear the async
432  * result storage and make sure PQerrorMessage will agree with the result's
433  * error string.
434  */
435 PGresult *
436 pqPrepareAsyncResult(PGconn *conn)
437 {
438         PGresult   *res;
439
440         /*
441          * conn->result is the PGresult to return.      If it is NULL (which probably
442          * shouldn't happen) we assume there is an appropriate error message in
443          * conn->errorMessage.
444          */
445         res = conn->result;
446         conn->result = NULL;            /* handing over ownership to caller */
447         conn->curTuple = NULL;          /* just in case */
448         if (!res)
449                 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
450         else
451         {
452                 /*
453                  * Make sure PQerrorMessage agrees with result; it could be different
454                  * if we have concatenated messages.
455                  */
456                 resetPQExpBuffer(&conn->errorMessage);
457                 appendPQExpBufferStr(&conn->errorMessage,
458                                                          PQresultErrorMessage(res));
459         }
460         return res;
461 }
462
463 /*
464  * pqInternalNotice - produce an internally-generated notice message
465  *
466  * A format string and optional arguments can be passed.  Note that we do
467  * libpq_gettext() here, so callers need not.
468  *
469  * The supplied text is taken as primary message (ie., it should not include
470  * a trailing newline, and should not be more than one line).
471  */
472 void
473 pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
474 {
475         char            msgBuf[1024];
476         va_list         args;
477         PGresult   *res;
478
479         if (hooks->noticeRec == NULL)
480                 return;                                 /* nobody home to receive notice? */
481
482         /* Format the message */
483         va_start(args, fmt);
484         vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
485         va_end(args);
486         msgBuf[sizeof(msgBuf) - 1] = '\0';      /* make real sure it's terminated */
487
488         /* Make a PGresult to pass to the notice receiver */
489         res = PQmakeEmptyPGresult(NULL, PGRES_NONFATAL_ERROR);
490         if (!res)
491                 return;
492         res->noticeHooks = *hooks;
493
494         /*
495          * Set up fields of notice.
496          */
497         pqSaveMessageField(res, PG_DIAG_MESSAGE_PRIMARY, msgBuf);
498         pqSaveMessageField(res, PG_DIAG_SEVERITY, libpq_gettext("NOTICE"));
499         /* XXX should provide a SQLSTATE too? */
500
501         /*
502          * Result text is always just the primary message + newline. If we can't
503          * allocate it, don't bother invoking the receiver.
504          */
505         res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, FALSE);
506         if (res->errMsg)
507         {
508                 sprintf(res->errMsg, "%s\n", msgBuf);
509
510                 /*
511                  * Pass to receiver, then free it.
512                  */
513                 (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
514         }
515         PQclear(res);
516 }
517
518 /*
519  * pqAddTuple
520  *        add a row pointer to the PGresult structure, growing it if necessary
521  *        Returns TRUE if OK, FALSE if not enough memory to add the row
522  */
523 int
524 pqAddTuple(PGresult *res, PGresAttValue *tup)
525 {
526         if (res->ntups >= res->tupArrSize)
527         {
528                 /*
529                  * Try to grow the array.
530                  *
531                  * We can use realloc because shallow copying of the structure is
532                  * okay. Note that the first time through, res->tuples is NULL. While
533                  * ANSI says that realloc() should act like malloc() in that case,
534                  * some old C libraries (like SunOS 4.1.x) coredump instead. On
535                  * failure realloc is supposed to return NULL without damaging the
536                  * existing allocation. Note that the positions beyond res->ntups are
537                  * garbage, not necessarily NULL.
538                  */
539                 int                     newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
540                 PGresAttValue **newTuples;
541
542                 if (res->tuples == NULL)
543                         newTuples = (PGresAttValue **)
544                                 malloc(newSize * sizeof(PGresAttValue *));
545                 else
546                         newTuples = (PGresAttValue **)
547                                 realloc(res->tuples, newSize * sizeof(PGresAttValue *));
548                 if (!newTuples)
549                         return FALSE;           /* malloc or realloc failed */
550                 res->tupArrSize = newSize;
551                 res->tuples = newTuples;
552         }
553         res->tuples[res->ntups] = tup;
554         res->ntups++;
555         return TRUE;
556 }
557
558 /*
559  * pqSaveMessageField - save one field of an error or notice message
560  */
561 void
562 pqSaveMessageField(PGresult *res, char code, const char *value)
563 {
564         PGMessageField *pfield;
565
566         pfield = (PGMessageField *)
567                 pqResultAlloc(res,
568                                           sizeof(PGMessageField) + strlen(value),
569                                           TRUE);
570         if (!pfield)
571                 return;                                 /* out of memory? */
572         pfield->code = code;
573         strcpy(pfield->contents, value);
574         pfield->next = res->errFields;
575         res->errFields = pfield;
576 }
577
578 /*
579  * pqSaveParameterStatus - remember parameter status sent by backend
580  */
581 void
582 pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
583 {
584         pgParameterStatus *pstatus;
585         pgParameterStatus *prev;
586
587         if (conn->Pfdebug)
588                 fprintf(conn->Pfdebug, "pqSaveParameterStatus: '%s' = '%s'\n",
589                                 name, value);
590
591         /*
592          * Forget any old information about the parameter
593          */
594         for (pstatus = conn->pstatus, prev = NULL;
595                  pstatus != NULL;
596                  prev = pstatus, pstatus = pstatus->next)
597         {
598                 if (strcmp(pstatus->name, name) == 0)
599                 {
600                         if (prev)
601                                 prev->next = pstatus->next;
602                         else
603                                 conn->pstatus = pstatus->next;
604                         free(pstatus);          /* frees name and value strings too */
605                         break;
606                 }
607         }
608
609         /*
610          * Store new info as a single malloc block
611          */
612         pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
613                                                                                    strlen(name) +strlen(value) + 2);
614         if (pstatus)
615         {
616                 char       *ptr;
617
618                 ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
619                 pstatus->name = ptr;
620                 strcpy(ptr, name);
621                 ptr += strlen(name) + 1;
622                 pstatus->value = ptr;
623                 strcpy(ptr, value);
624                 pstatus->next = conn->pstatus;
625                 conn->pstatus = pstatus;
626         }
627
628         /*
629          * Special hacks: remember client_encoding and standard_conforming_strings,
630          * and convert server version to a numeric form.  We keep the first two of
631          * these in static variables as well, so that PQescapeString and
632          * PQescapeBytea can behave somewhat sanely (at least in single-
633          * connection-using programs).
634          */
635         if (strcmp(name, "client_encoding") == 0)
636         {
637                 conn->client_encoding = pg_char_to_encoding(value);
638                 static_client_encoding = conn->client_encoding;
639         }
640         else if (strcmp(name, "standard_conforming_strings") == 0)
641         {
642                 conn->std_strings = (strcmp(value, "on") == 0);
643                 static_std_strings = conn->std_strings;
644         }
645         else if (strcmp(name, "server_version") == 0)
646         {
647                 int                     cnt;
648                 int                     vmaj,
649                                         vmin,
650                                         vrev;
651
652                 cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
653
654                 if (cnt < 2)
655                         conn->sversion = 0; /* unknown */
656                 else
657                 {
658                         if (cnt == 2)
659                                 vrev = 0;
660                         conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
661                 }
662         }
663 }
664
665
666 /*
667  * PQsendQuery
668  *       Submit a query, but don't wait for it to finish
669  *
670  * Returns: 1 if successfully submitted
671  *                      0 if error (conn->errorMessage is set)
672  */
673 int
674 PQsendQuery(PGconn *conn, const char *query)
675 {
676         if (!PQsendQueryStart(conn))
677                 return 0;
678
679         if (!query)
680         {
681                 printfPQExpBuffer(&conn->errorMessage,
682                                                 libpq_gettext("command string is a null pointer\n"));
683                 return 0;
684         }
685
686         /* construct the outgoing Query message */
687         if (pqPutMsgStart('Q', false, conn) < 0 ||
688                 pqPuts(query, conn) < 0 ||
689                 pqPutMsgEnd(conn) < 0)
690         {
691                 pqHandleSendFailure(conn);
692                 return 0;
693         }
694
695         /* remember we are using simple query protocol */
696         conn->queryclass = PGQUERY_SIMPLE;
697
698         /* and remember the query text too, if possible */
699         /* if insufficient memory, last_query just winds up NULL */
700         if (conn->last_query)
701                 free(conn->last_query);
702         conn->last_query = strdup(query);
703
704         /*
705          * Give the data a push.  In nonblock mode, don't complain if we're unable
706          * to send it all; PQgetResult() will do any additional flushing needed.
707          */
708         if (pqFlush(conn) < 0)
709         {
710                 pqHandleSendFailure(conn);
711                 return 0;
712         }
713
714         /* OK, it's launched! */
715         conn->asyncStatus = PGASYNC_BUSY;
716         return 1;
717 }
718
719 /*
720  * PQsendQueryParams
721  *              Like PQsendQuery, but use protocol 3.0 so we can pass parameters
722  */
723 int
724 PQsendQueryParams(PGconn *conn,
725                                   const char *command,
726                                   int nParams,
727                                   const Oid *paramTypes,
728                                   const char *const * paramValues,
729                                   const int *paramLengths,
730                                   const int *paramFormats,
731                                   int resultFormat)
732 {
733         if (!PQsendQueryStart(conn))
734                 return 0;
735
736         if (!command)
737         {
738                 printfPQExpBuffer(&conn->errorMessage,
739                                                 libpq_gettext("command string is a null pointer\n"));
740                 return 0;
741         }
742
743         return PQsendQueryGuts(conn,
744                                                    command,
745                                                    "",  /* use unnamed statement */
746                                                    nParams,
747                                                    paramTypes,
748                                                    paramValues,
749                                                    paramLengths,
750                                                    paramFormats,
751                                                    resultFormat);
752 }
753
754 /*
755  * PQsendPrepare
756  *       Submit a Parse message, but don't wait for it to finish
757  *
758  * Returns: 1 if successfully submitted
759  *                      0 if error (conn->errorMessage is set)
760  */
761 int
762 PQsendPrepare(PGconn *conn,
763                           const char *stmtName, const char *query,
764                           int nParams, const Oid *paramTypes)
765 {
766         if (!PQsendQueryStart(conn))
767                 return 0;
768
769         if (!stmtName)
770         {
771                 printfPQExpBuffer(&conn->errorMessage,
772                                                 libpq_gettext("statement name is a null pointer\n"));
773                 return 0;
774         }
775
776         if (!query)
777         {
778                 printfPQExpBuffer(&conn->errorMessage,
779                                                 libpq_gettext("command string is a null pointer\n"));
780                 return 0;
781         }
782
783         /* This isn't gonna work on a 2.0 server */
784         if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
785         {
786                 printfPQExpBuffer(&conn->errorMessage,
787                  libpq_gettext("function requires at least protocol version 3.0\n"));
788                 return 0;
789         }
790
791         /* construct the Parse message */
792         if (pqPutMsgStart('P', false, conn) < 0 ||
793                 pqPuts(stmtName, conn) < 0 ||
794                 pqPuts(query, conn) < 0)
795                 goto sendFailed;
796
797         if (nParams > 0 && paramTypes)
798         {
799                 int                     i;
800
801                 if (pqPutInt(nParams, 2, conn) < 0)
802                         goto sendFailed;
803                 for (i = 0; i < nParams; i++)
804                 {
805                         if (pqPutInt(paramTypes[i], 4, conn) < 0)
806                                 goto sendFailed;
807                 }
808         }
809         else
810         {
811                 if (pqPutInt(0, 2, conn) < 0)
812                         goto sendFailed;
813         }
814         if (pqPutMsgEnd(conn) < 0)
815                 goto sendFailed;
816
817         /* construct the Sync message */
818         if (pqPutMsgStart('S', false, conn) < 0 ||
819                 pqPutMsgEnd(conn) < 0)
820                 goto sendFailed;
821
822         /* remember we are doing just a Parse */
823         conn->queryclass = PGQUERY_PREPARE;
824
825         /* and remember the query text too, if possible */
826         /* if insufficient memory, last_query just winds up NULL */
827         if (conn->last_query)
828                 free(conn->last_query);
829         conn->last_query = strdup(query);
830
831         /*
832          * Give the data a push.  In nonblock mode, don't complain if we're unable
833          * to send it all; PQgetResult() will do any additional flushing needed.
834          */
835         if (pqFlush(conn) < 0)
836                 goto sendFailed;
837
838         /* OK, it's launched! */
839         conn->asyncStatus = PGASYNC_BUSY;
840         return 1;
841
842 sendFailed:
843         pqHandleSendFailure(conn);
844         return 0;
845 }
846
847 /*
848  * PQsendQueryPrepared
849  *              Like PQsendQuery, but execute a previously prepared statement,
850  *              using protocol 3.0 so we can pass parameters
851  */
852 int
853 PQsendQueryPrepared(PGconn *conn,
854                                         const char *stmtName,
855                                         int nParams,
856                                         const char *const * paramValues,
857                                         const int *paramLengths,
858                                         const int *paramFormats,
859                                         int resultFormat)
860 {
861         if (!PQsendQueryStart(conn))
862                 return 0;
863
864         if (!stmtName)
865         {
866                 printfPQExpBuffer(&conn->errorMessage,
867                                                 libpq_gettext("statement name is a null pointer\n"));
868                 return 0;
869         }
870
871         return PQsendQueryGuts(conn,
872                                                    NULL,        /* no command to parse */
873                                                    stmtName,
874                                                    nParams,
875                                                    NULL,        /* no param types */
876                                                    paramValues,
877                                                    paramLengths,
878                                                    paramFormats,
879                                                    resultFormat);
880 }
881
882 /*
883  * Common startup code for PQsendQuery and sibling routines
884  */
885 static bool
886 PQsendQueryStart(PGconn *conn)
887 {
888         if (!conn)
889                 return false;
890
891         /* clear the error string */
892         resetPQExpBuffer(&conn->errorMessage);
893
894         /* Don't try to send if we know there's no live connection. */
895         if (conn->status != CONNECTION_OK)
896         {
897                 printfPQExpBuffer(&conn->errorMessage,
898                                                   libpq_gettext("no connection to the server\n"));
899                 return false;
900         }
901         /* Can't send while already busy, either. */
902         if (conn->asyncStatus != PGASYNC_IDLE)
903         {
904                 printfPQExpBuffer(&conn->errorMessage,
905                                   libpq_gettext("another command is already in progress\n"));
906                 return false;
907         }
908
909         /* initialize async result-accumulation state */
910         conn->result = NULL;
911         conn->curTuple = NULL;
912
913         /* ready to send command message */
914         return true;
915 }
916
917 /*
918  * PQsendQueryGuts
919  *              Common code for protocol-3.0 query sending
920  *              PQsendQueryStart should be done already
921  *
922  * command may be NULL to indicate we use an already-prepared statement
923  */
924 static int
925 PQsendQueryGuts(PGconn *conn,
926                                 const char *command,
927                                 const char *stmtName,
928                                 int nParams,
929                                 const Oid *paramTypes,
930                                 const char *const * paramValues,
931                                 const int *paramLengths,
932                                 const int *paramFormats,
933                                 int resultFormat)
934 {
935         int                     i;
936
937         /* This isn't gonna work on a 2.0 server */
938         if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
939         {
940                 printfPQExpBuffer(&conn->errorMessage,
941                  libpq_gettext("function requires at least protocol version 3.0\n"));
942                 return 0;
943         }
944
945         /*
946          * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync,
947          * using specified statement name and the unnamed portal.
948          */
949
950         if (command)
951         {
952                 /* construct the Parse message */
953                 if (pqPutMsgStart('P', false, conn) < 0 ||
954                         pqPuts(stmtName, conn) < 0 ||
955                         pqPuts(command, conn) < 0)
956                         goto sendFailed;
957                 if (nParams > 0 && paramTypes)
958                 {
959                         if (pqPutInt(nParams, 2, conn) < 0)
960                                 goto sendFailed;
961                         for (i = 0; i < nParams; i++)
962                         {
963                                 if (pqPutInt(paramTypes[i], 4, conn) < 0)
964                                         goto sendFailed;
965                         }
966                 }
967                 else
968                 {
969                         if (pqPutInt(0, 2, conn) < 0)
970                                 goto sendFailed;
971                 }
972                 if (pqPutMsgEnd(conn) < 0)
973                         goto sendFailed;
974         }
975
976         /* construct the Bind message */
977         if (pqPutMsgStart('B', false, conn) < 0 ||
978                 pqPuts("", conn) < 0 ||
979                 pqPuts(stmtName, conn) < 0)
980                 goto sendFailed;
981
982         if (nParams > 0 && paramFormats)
983         {
984                 if (pqPutInt(nParams, 2, conn) < 0)
985                         goto sendFailed;
986                 for (i = 0; i < nParams; i++)
987                 {
988                         if (pqPutInt(paramFormats[i], 2, conn) < 0)
989                                 goto sendFailed;
990                 }
991         }
992         else
993         {
994                 if (pqPutInt(0, 2, conn) < 0)
995                         goto sendFailed;
996         }
997
998         if (pqPutInt(nParams, 2, conn) < 0)
999                 goto sendFailed;
1000
1001         for (i = 0; i < nParams; i++)
1002         {
1003                 if (paramValues && paramValues[i])
1004                 {
1005                         int                     nbytes;
1006
1007                         if (paramFormats && paramFormats[i] != 0)
1008                         {
1009                                 /* binary parameter */
1010                                 if (paramLengths)
1011                                         nbytes = paramLengths[i];
1012                                 else
1013                                 {
1014                                         printfPQExpBuffer(&conn->errorMessage,
1015                                                                           libpq_gettext("length must be given for binary parameter\n"));
1016                                         goto sendFailed;
1017                                 }
1018                         }
1019                         else
1020                         {
1021                                 /* text parameter, do not use paramLengths */
1022                                 nbytes = strlen(paramValues[i]);
1023                         }
1024                         if (pqPutInt(nbytes, 4, conn) < 0 ||
1025                                 pqPutnchar(paramValues[i], nbytes, conn) < 0)
1026                                 goto sendFailed;
1027                 }
1028                 else
1029                 {
1030                         /* take the param as NULL */
1031                         if (pqPutInt(-1, 4, conn) < 0)
1032                                 goto sendFailed;
1033                 }
1034         }
1035         if (pqPutInt(1, 2, conn) < 0 ||
1036                 pqPutInt(resultFormat, 2, conn))
1037                 goto sendFailed;
1038         if (pqPutMsgEnd(conn) < 0)
1039                 goto sendFailed;
1040
1041         /* construct the Describe Portal message */
1042         if (pqPutMsgStart('D', false, conn) < 0 ||
1043                 pqPutc('P', conn) < 0 ||
1044                 pqPuts("", conn) < 0 ||
1045                 pqPutMsgEnd(conn) < 0)
1046                 goto sendFailed;
1047
1048         /* construct the Execute message */
1049         if (pqPutMsgStart('E', false, conn) < 0 ||
1050                 pqPuts("", conn) < 0 ||
1051                 pqPutInt(0, 4, conn) < 0 ||
1052                 pqPutMsgEnd(conn) < 0)
1053                 goto sendFailed;
1054
1055         /* construct the Sync message */
1056         if (pqPutMsgStart('S', false, conn) < 0 ||
1057                 pqPutMsgEnd(conn) < 0)
1058                 goto sendFailed;
1059
1060         /* remember we are using extended query protocol */
1061         conn->queryclass = PGQUERY_EXTENDED;
1062
1063         /* and remember the query text too, if possible */
1064         /* if insufficient memory, last_query just winds up NULL */
1065         if (conn->last_query)
1066                 free(conn->last_query);
1067         if (command)
1068                 conn->last_query = strdup(command);
1069         else
1070                 conn->last_query = NULL;
1071
1072         /*
1073          * Give the data a push.  In nonblock mode, don't complain if we're unable
1074          * to send it all; PQgetResult() will do any additional flushing needed.
1075          */
1076         if (pqFlush(conn) < 0)
1077                 goto sendFailed;
1078
1079         /* OK, it's launched! */
1080         conn->asyncStatus = PGASYNC_BUSY;
1081         return 1;
1082
1083 sendFailed:
1084         pqHandleSendFailure(conn);
1085         return 0;
1086 }
1087
1088 /*
1089  * pqHandleSendFailure: try to clean up after failure to send command.
1090  *
1091  * Primarily, what we want to accomplish here is to process an async
1092  * NOTICE message that the backend might have sent just before it died.
1093  *
1094  * NOTE: this routine should only be called in PGASYNC_IDLE state.
1095  */
1096 void
1097 pqHandleSendFailure(PGconn *conn)
1098 {
1099         /*
1100          * Accept any available input data, ignoring errors.  Note that if
1101          * pqReadData decides the backend has closed the channel, it will close
1102          * our side of the socket --- that's just what we want here.
1103          */
1104         while (pqReadData(conn) > 0)
1105                  /* loop until no more data readable */ ;
1106
1107         /*
1108          * Parse any available input messages.  Since we are in PGASYNC_IDLE
1109          * state, only NOTICE and NOTIFY messages will be eaten.
1110          */
1111         parseInput(conn);
1112 }
1113
1114 /*
1115  * Consume any available input from the backend
1116  * 0 return: some kind of trouble
1117  * 1 return: no problem
1118  */
1119 int
1120 PQconsumeInput(PGconn *conn)
1121 {
1122         if (!conn)
1123                 return 0;
1124
1125         /*
1126          * for non-blocking connections try to flush the send-queue, otherwise we
1127          * may never get a response for something that may not have already been
1128          * sent because it's in our write buffer!
1129          */
1130         if (pqIsnonblocking(conn))
1131         {
1132                 if (pqFlush(conn) < 0)
1133                         return 0;
1134         }
1135
1136         /*
1137          * Load more data, if available. We do this no matter what state we are
1138          * in, since we are probably getting called because the application wants
1139          * to get rid of a read-select condition. Note that we will NOT block
1140          * waiting for more input.
1141          */
1142         if (pqReadData(conn) < 0)
1143                 return 0;
1144
1145         /* Parsing of the data waits till later. */
1146         return 1;
1147 }
1148
1149
1150 /*
1151  * parseInput: if appropriate, parse input data from backend
1152  * until input is exhausted or a stopping state is reached.
1153  * Note that this function will NOT attempt to read more data from the backend.
1154  */
1155 static void
1156 parseInput(PGconn *conn)
1157 {
1158         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1159                 pqParseInput3(conn);
1160         else
1161                 pqParseInput2(conn);
1162 }
1163
1164 /*
1165  * PQisBusy
1166  *       Return TRUE if PQgetResult would block waiting for input.
1167  */
1168
1169 int
1170 PQisBusy(PGconn *conn)
1171 {
1172         if (!conn)
1173                 return FALSE;
1174
1175         /* Parse any available data, if our state permits. */
1176         parseInput(conn);
1177
1178         /* PQgetResult will return immediately in all states except BUSY. */
1179         return conn->asyncStatus == PGASYNC_BUSY;
1180 }
1181
1182
1183 /*
1184  * PQgetResult
1185  *        Get the next PGresult produced by a query.  Returns NULL if no
1186  *        query work remains or an error has occurred (e.g. out of
1187  *        memory).
1188  */
1189
1190 PGresult *
1191 PQgetResult(PGconn *conn)
1192 {
1193         PGresult   *res;
1194
1195         if (!conn)
1196                 return NULL;
1197
1198         /* Parse any available data, if our state permits. */
1199         parseInput(conn);
1200
1201         /* If not ready to return something, block until we are. */
1202         while (conn->asyncStatus == PGASYNC_BUSY)
1203         {
1204                 int                     flushResult;
1205
1206                 /*
1207                  * If data remains unsent, send it.  Else we might be waiting for the
1208                  * result of a command the backend hasn't even got yet.
1209                  */
1210                 while ((flushResult = pqFlush(conn)) > 0)
1211                 {
1212                         if (pqWait(FALSE, TRUE, conn))
1213                         {
1214                                 flushResult = -1;
1215                                 break;
1216                         }
1217                 }
1218
1219                 /* Wait for some more data, and load it. */
1220                 if (flushResult ||
1221                         pqWait(TRUE, FALSE, conn) ||
1222                         pqReadData(conn) < 0)
1223                 {
1224                         /*
1225                          * conn->errorMessage has been set by pqWait or pqReadData. We
1226                          * want to append it to any already-received error message.
1227                          */
1228                         pqSaveErrorResult(conn);
1229                         conn->asyncStatus = PGASYNC_IDLE;
1230                         return pqPrepareAsyncResult(conn);
1231                 }
1232
1233                 /* Parse it. */
1234                 parseInput(conn);
1235         }
1236
1237         /* Return the appropriate thing. */
1238         switch (conn->asyncStatus)
1239         {
1240                 case PGASYNC_IDLE:
1241                         res = NULL;                     /* query is complete */
1242                         break;
1243                 case PGASYNC_READY:
1244                         res = pqPrepareAsyncResult(conn);
1245                         /* Set the state back to BUSY, allowing parsing to proceed. */
1246                         conn->asyncStatus = PGASYNC_BUSY;
1247                         break;
1248                 case PGASYNC_COPY_IN:
1249                         if (conn->result && conn->result->resultStatus == PGRES_COPY_IN)
1250                                 res = pqPrepareAsyncResult(conn);
1251                         else
1252                                 res = PQmakeEmptyPGresult(conn, PGRES_COPY_IN);
1253                         break;
1254                 case PGASYNC_COPY_OUT:
1255                         if (conn->result && conn->result->resultStatus == PGRES_COPY_OUT)
1256                                 res = pqPrepareAsyncResult(conn);
1257                         else
1258                                 res = PQmakeEmptyPGresult(conn, PGRES_COPY_OUT);
1259                         break;
1260                 default:
1261                         printfPQExpBuffer(&conn->errorMessage,
1262                                                           libpq_gettext("unexpected asyncStatus: %d\n"),
1263                                                           (int) conn->asyncStatus);
1264                         res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1265                         break;
1266         }
1267
1268         return res;
1269 }
1270
1271
1272 /*
1273  * PQexec
1274  *        send a query to the backend and package up the result in a PGresult
1275  *
1276  * If the query was not even sent, return NULL; conn->errorMessage is set to
1277  * a relevant message.
1278  * If the query was sent, a new PGresult is returned (which could indicate
1279  * either success or failure).
1280  * The user is responsible for freeing the PGresult via PQclear()
1281  * when done with it.
1282  */
1283 PGresult *
1284 PQexec(PGconn *conn, const char *query)
1285 {
1286         if (!PQexecStart(conn))
1287                 return NULL;
1288         if (!PQsendQuery(conn, query))
1289                 return NULL;
1290         return PQexecFinish(conn);
1291 }
1292
1293 /*
1294  * PQexecParams
1295  *              Like PQexec, but use protocol 3.0 so we can pass parameters
1296  */
1297 PGresult *
1298 PQexecParams(PGconn *conn,
1299                          const char *command,
1300                          int nParams,
1301                          const Oid *paramTypes,
1302                          const char *const * paramValues,
1303                          const int *paramLengths,
1304                          const int *paramFormats,
1305                          int resultFormat)
1306 {
1307         if (!PQexecStart(conn))
1308                 return NULL;
1309         if (!PQsendQueryParams(conn, command,
1310                                                    nParams, paramTypes, paramValues, paramLengths,
1311                                                    paramFormats, resultFormat))
1312                 return NULL;
1313         return PQexecFinish(conn);
1314 }
1315
1316 /*
1317  * PQprepare
1318  *        Creates a prepared statement by issuing a v3.0 parse message.
1319  *
1320  * If the query was not even sent, return NULL; conn->errorMessage is set to
1321  * a relevant message.
1322  * If the query was sent, a new PGresult is returned (which could indicate
1323  * either success or failure).
1324  * The user is responsible for freeing the PGresult via PQclear()
1325  * when done with it.
1326  */
1327 PGresult *
1328 PQprepare(PGconn *conn,
1329                   const char *stmtName, const char *query,
1330                   int nParams, const Oid *paramTypes)
1331 {
1332         if (!PQexecStart(conn))
1333                 return NULL;
1334         if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
1335                 return NULL;
1336         return PQexecFinish(conn);
1337 }
1338
1339 /*
1340  * PQexecPrepared
1341  *              Like PQexec, but execute a previously prepared statement,
1342  *              using protocol 3.0 so we can pass parameters
1343  */
1344 PGresult *
1345 PQexecPrepared(PGconn *conn,
1346                            const char *stmtName,
1347                            int nParams,
1348                            const char *const * paramValues,
1349                            const int *paramLengths,
1350                            const int *paramFormats,
1351                            int resultFormat)
1352 {
1353         if (!PQexecStart(conn))
1354                 return NULL;
1355         if (!PQsendQueryPrepared(conn, stmtName,
1356                                                          nParams, paramValues, paramLengths,
1357                                                          paramFormats, resultFormat))
1358                 return NULL;
1359         return PQexecFinish(conn);
1360 }
1361
1362 /*
1363  * Common code for PQexec and sibling routines: prepare to send command
1364  */
1365 static bool
1366 PQexecStart(PGconn *conn)
1367 {
1368         PGresult   *result;
1369
1370         if (!conn)
1371                 return false;
1372
1373         /*
1374          * Silently discard any prior query result that application didn't eat.
1375          * This is probably poor design, but it's here for backward compatibility.
1376          */
1377         while ((result = PQgetResult(conn)) != NULL)
1378         {
1379                 ExecStatusType resultStatus = result->resultStatus;
1380
1381                 PQclear(result);                /* only need its status */
1382                 if (resultStatus == PGRES_COPY_IN)
1383                 {
1384                         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1385                         {
1386                                 /* In protocol 3, we can get out of a COPY IN state */
1387                                 if (PQputCopyEnd(conn,
1388                                                  libpq_gettext("COPY terminated by new PQexec")) < 0)
1389                                         return false;
1390                                 /* keep waiting to swallow the copy's failure message */
1391                         }
1392                         else
1393                         {
1394                                 /* In older protocols we have to punt */
1395                                 printfPQExpBuffer(&conn->errorMessage,
1396                                   libpq_gettext("COPY IN state must be terminated first\n"));
1397                                 return false;
1398                         }
1399                 }
1400                 else if (resultStatus == PGRES_COPY_OUT)
1401                 {
1402                         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1403                         {
1404                                 /*
1405                                  * In protocol 3, we can get out of a COPY OUT state: we just
1406                                  * switch back to BUSY and allow the remaining COPY data to be
1407                                  * dropped on the floor.
1408                                  */
1409                                 conn->asyncStatus = PGASYNC_BUSY;
1410                                 /* keep waiting to swallow the copy's completion message */
1411                         }
1412                         else
1413                         {
1414                                 /* In older protocols we have to punt */
1415                                 printfPQExpBuffer(&conn->errorMessage,
1416                                  libpq_gettext("COPY OUT state must be terminated first\n"));
1417                                 return false;
1418                         }
1419                 }
1420                 /* check for loss of connection, too */
1421                 if (conn->status == CONNECTION_BAD)
1422                         return false;
1423         }
1424
1425         /* OK to send a command */
1426         return true;
1427 }
1428
1429 /*
1430  * Common code for PQexec and sibling routines: wait for command result
1431  */
1432 static PGresult *
1433 PQexecFinish(PGconn *conn)
1434 {
1435         PGresult   *result;
1436         PGresult   *lastResult;
1437
1438         /*
1439          * For backwards compatibility, return the last result if there are more
1440          * than one --- but merge error messages if we get more than one error
1441          * result.
1442          *
1443          * We have to stop if we see copy in/out, however. We will resume parsing
1444          * after application performs the data transfer.
1445          *
1446          * Also stop if the connection is lost (else we'll loop infinitely).
1447          */
1448         lastResult = NULL;
1449         while ((result = PQgetResult(conn)) != NULL)
1450         {
1451                 if (lastResult)
1452                 {
1453                         if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
1454                                 result->resultStatus == PGRES_FATAL_ERROR)
1455                         {
1456                                 pqCatenateResultError(lastResult, result->errMsg);
1457                                 PQclear(result);
1458                                 result = lastResult;
1459
1460                                 /*
1461                                  * Make sure PQerrorMessage agrees with concatenated result
1462                                  */
1463                                 resetPQExpBuffer(&conn->errorMessage);
1464                                 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
1465                         }
1466                         else
1467                                 PQclear(lastResult);
1468                 }
1469                 lastResult = result;
1470                 if (result->resultStatus == PGRES_COPY_IN ||
1471                         result->resultStatus == PGRES_COPY_OUT ||
1472                         conn->status == CONNECTION_BAD)
1473                         break;
1474         }
1475
1476         return lastResult;
1477 }
1478
1479 /*
1480  * PQdescribePrepared
1481  *        Obtain information about a previously prepared statement
1482  *
1483  * If the query was not even sent, return NULL; conn->errorMessage is set to
1484  * a relevant message.
1485  * If the query was sent, a new PGresult is returned (which could indicate
1486  * either success or failure).  On success, the PGresult contains status
1487  * PGRES_COMMAND_OK, and its parameter and column-heading fields describe
1488  * the statement's inputs and outputs respectively.
1489  * The user is responsible for freeing the PGresult via PQclear()
1490  * when done with it.
1491  */
1492 PGresult *
1493 PQdescribePrepared(PGconn *conn, const char *stmt)
1494 {
1495         if (!PQexecStart(conn))
1496                 return NULL;
1497         if (!PQsendDescribe(conn, 'S', stmt))
1498                 return NULL;
1499         return PQexecFinish(conn);
1500 }
1501
1502 /*
1503  * PQdescribePortal
1504  *        Obtain information about a previously created portal
1505  *
1506  * This is much like PQdescribePrepared, except that no parameter info is
1507  * returned.  Note that at the moment, libpq doesn't really expose portals
1508  * to the client; but this can be used with a portal created by a SQL
1509  * DECLARE CURSOR command.
1510  */
1511 PGresult *
1512 PQdescribePortal(PGconn *conn, const char *portal)
1513 {
1514         if (!PQexecStart(conn))
1515                 return NULL;
1516         if (!PQsendDescribe(conn, 'P', portal))
1517                 return NULL;
1518         return PQexecFinish(conn);
1519 }
1520
1521 /*
1522  * PQsendDescribePrepared
1523  *       Submit a Describe Statement command, but don't wait for it to finish
1524  *
1525  * Returns: 1 if successfully submitted
1526  *                      0 if error (conn->errorMessage is set)
1527  */
1528 int
1529 PQsendDescribePrepared(PGconn *conn, const char *stmt)
1530 {
1531         return PQsendDescribe(conn, 'S', stmt);
1532 }
1533
1534 /*
1535  * PQsendDescribePortal
1536  *       Submit a Describe Portal command, but don't wait for it to finish
1537  *
1538  * Returns: 1 if successfully submitted
1539  *                      0 if error (conn->errorMessage is set)
1540  */
1541 int
1542 PQsendDescribePortal(PGconn *conn, const char *portal)
1543 {
1544         return PQsendDescribe(conn, 'P', portal);
1545 }
1546
1547 /*
1548  * PQsendDescribe
1549  *       Common code to send a Describe command
1550  *
1551  * Available options for desc_type are
1552  *   'S' to describe a prepared statement; or
1553  *   'P' to describe a portal.
1554  * Returns 1 on success and 0 on failure.
1555  */
1556 static int
1557 PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
1558 {
1559         /* Treat null desc_target as empty string */
1560         if (!desc_target)
1561                 desc_target = "";
1562
1563         if (!PQsendQueryStart(conn))
1564                 return 0;
1565
1566         /* This isn't gonna work on a 2.0 server */
1567         if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1568         {
1569                 printfPQExpBuffer(&conn->errorMessage,
1570                  libpq_gettext("function requires at least protocol version 3.0\n"));
1571                 return 0;
1572         }
1573
1574         /* construct the Describe message */
1575         if (pqPutMsgStart('D', false, conn) < 0 ||
1576                 pqPutc(desc_type, conn) < 0 ||
1577                 pqPuts(desc_target, conn) < 0 ||
1578                 pqPutMsgEnd(conn) < 0)
1579                 goto sendFailed;
1580
1581         /* construct the Sync message */
1582         if (pqPutMsgStart('S', false, conn) < 0 ||
1583                 pqPutMsgEnd(conn) < 0)
1584                 goto sendFailed;
1585
1586         /* remember we are doing a Describe */
1587         conn->queryclass = PGQUERY_DESCRIBE;
1588
1589         /* reset last-query string (not relevant now) */
1590         if (conn->last_query)
1591         {
1592                 free(conn->last_query);
1593                 conn->last_query = NULL;
1594         }
1595
1596         /*
1597          * Give the data a push.  In nonblock mode, don't complain if we're unable
1598          * to send it all; PQgetResult() will do any additional flushing needed.
1599          */
1600         if (pqFlush(conn) < 0)
1601                 goto sendFailed;
1602
1603         /* OK, it's launched! */
1604         conn->asyncStatus = PGASYNC_BUSY;
1605         return 1;
1606
1607 sendFailed:
1608         pqHandleSendFailure(conn);
1609         return 0;
1610 }
1611
1612 /*
1613  * PQnotifies
1614  *        returns a PGnotify* structure of the latest async notification
1615  * that has not yet been handled
1616  *
1617  * returns NULL, if there is currently
1618  * no unhandled async notification from the backend
1619  *
1620  * the CALLER is responsible for FREE'ing the structure returned
1621  */
1622 PGnotify *
1623 PQnotifies(PGconn *conn)
1624 {
1625         PGnotify   *event;
1626
1627         if (!conn)
1628                 return NULL;
1629
1630         /* Parse any available data to see if we can extract NOTIFY messages. */
1631         parseInput(conn);
1632
1633         event = conn->notifyHead;
1634         if (event)
1635         {
1636                 conn->notifyHead = event->next;
1637                 if (!conn->notifyHead)
1638                         conn->notifyTail = NULL;
1639                 event->next = NULL;             /* don't let app see the internal state */
1640         }
1641         return event;
1642 }
1643
1644 /*
1645  * PQputCopyData - send some data to the backend during COPY IN
1646  *
1647  * Returns 1 if successful, 0 if data could not be sent (only possible
1648  * in nonblock mode), or -1 if an error occurs.
1649  */
1650 int
1651 PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
1652 {
1653         if (!conn)
1654                 return -1;
1655         if (conn->asyncStatus != PGASYNC_COPY_IN)
1656         {
1657                 printfPQExpBuffer(&conn->errorMessage,
1658                                                   libpq_gettext("no COPY in progress\n"));
1659                 return -1;
1660         }
1661
1662         /*
1663          * Process any NOTICE or NOTIFY messages that might be pending in the
1664          * input buffer.  Since the server might generate many notices during
1665          * the COPY, we want to clean those out reasonably promptly to prevent
1666          * indefinite expansion of the input buffer.  (Note: the actual read
1667          * of input data into the input buffer happens down inside pqSendSome,
1668          * but it's not authorized to get rid of the data again.)
1669          */
1670         parseInput(conn);
1671
1672         if (nbytes > 0)
1673         {
1674                 /*
1675                  * Try to flush any previously sent data in preference to growing the
1676                  * output buffer.  If we can't enlarge the buffer enough to hold the
1677                  * data, return 0 in the nonblock case, else hard error. (For
1678                  * simplicity, always assume 5 bytes of overhead even in protocol 2.0
1679                  * case.)
1680                  */
1681                 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
1682                 {
1683                         if (pqFlush(conn) < 0)
1684                                 return -1;
1685                         if (pqCheckOutBufferSpace(conn->outCount + 5 + nbytes, conn))
1686                                 return pqIsnonblocking(conn) ? 0 : -1;
1687                 }
1688                 /* Send the data (too simple to delegate to fe-protocol files) */
1689                 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1690                 {
1691                         if (pqPutMsgStart('d', false, conn) < 0 ||
1692                                 pqPutnchar(buffer, nbytes, conn) < 0 ||
1693                                 pqPutMsgEnd(conn) < 0)
1694                                 return -1;
1695                 }
1696                 else
1697                 {
1698                         if (pqPutMsgStart(0, false, conn) < 0 ||
1699                                 pqPutnchar(buffer, nbytes, conn) < 0 ||
1700                                 pqPutMsgEnd(conn) < 0)
1701                                 return -1;
1702                 }
1703         }
1704         return 1;
1705 }
1706
1707 /*
1708  * PQputCopyEnd - send EOF indication to the backend during COPY IN
1709  *
1710  * After calling this, use PQgetResult() to check command completion status.
1711  *
1712  * Returns 1 if successful, 0 if data could not be sent (only possible
1713  * in nonblock mode), or -1 if an error occurs.
1714  */
1715 int
1716 PQputCopyEnd(PGconn *conn, const char *errormsg)
1717 {
1718         if (!conn)
1719                 return -1;
1720         if (conn->asyncStatus != PGASYNC_COPY_IN)
1721         {
1722                 printfPQExpBuffer(&conn->errorMessage,
1723                                                   libpq_gettext("no COPY in progress\n"));
1724                 return -1;
1725         }
1726
1727         /*
1728          * Send the COPY END indicator.  This is simple enough that we don't
1729          * bother delegating it to the fe-protocol files.
1730          */
1731         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1732         {
1733                 if (errormsg)
1734                 {
1735                         /* Send COPY FAIL */
1736                         if (pqPutMsgStart('f', false, conn) < 0 ||
1737                                 pqPuts(errormsg, conn) < 0 ||
1738                                 pqPutMsgEnd(conn) < 0)
1739                                 return -1;
1740                 }
1741                 else
1742                 {
1743                         /* Send COPY DONE */
1744                         if (pqPutMsgStart('c', false, conn) < 0 ||
1745                                 pqPutMsgEnd(conn) < 0)
1746                                 return -1;
1747                 }
1748
1749                 /*
1750                  * If we sent the COPY command in extended-query mode, we must issue a
1751                  * Sync as well.
1752                  */
1753                 if (conn->queryclass != PGQUERY_SIMPLE)
1754                 {
1755                         if (pqPutMsgStart('S', false, conn) < 0 ||
1756                                 pqPutMsgEnd(conn) < 0)
1757                                 return -1;
1758                 }
1759         }
1760         else
1761         {
1762                 if (errormsg)
1763                 {
1764                         /* Ooops, no way to do this in 2.0 */
1765                         printfPQExpBuffer(&conn->errorMessage,
1766                                                           libpq_gettext("function requires at least protocol version 3.0\n"));
1767                         return -1;
1768                 }
1769                 else
1770                 {
1771                         /* Send old-style end-of-data marker */
1772                         if (pqPutMsgStart(0, false, conn) < 0 ||
1773                                 pqPutnchar("\\.\n", 3, conn) < 0 ||
1774                                 pqPutMsgEnd(conn) < 0)
1775                                 return -1;
1776                 }
1777         }
1778
1779         /* Return to active duty */
1780         conn->asyncStatus = PGASYNC_BUSY;
1781         resetPQExpBuffer(&conn->errorMessage);
1782
1783         /* Try to flush data */
1784         if (pqFlush(conn) < 0)
1785                 return -1;
1786
1787         return 1;
1788 }
1789
1790 /*
1791  * PQgetCopyData - read a row of data from the backend during COPY OUT
1792  *
1793  * If successful, sets *buffer to point to a malloc'd row of data, and
1794  * returns row length (always > 0) as result.
1795  * Returns 0 if no row available yet (only possible if async is true),
1796  * -1 if end of copy (consult PQgetResult), or -2 if error (consult
1797  * PQerrorMessage).
1798  */
1799 int
1800 PQgetCopyData(PGconn *conn, char **buffer, int async)
1801 {
1802         *buffer = NULL;                         /* for all failure cases */
1803         if (!conn)
1804                 return -2;
1805         if (conn->asyncStatus != PGASYNC_COPY_OUT)
1806         {
1807                 printfPQExpBuffer(&conn->errorMessage,
1808                                                   libpq_gettext("no COPY in progress\n"));
1809                 return -2;
1810         }
1811         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1812                 return pqGetCopyData3(conn, buffer, async);
1813         else
1814                 return pqGetCopyData2(conn, buffer, async);
1815 }
1816
1817 /*
1818  * PQgetline - gets a newline-terminated string from the backend.
1819  *
1820  * Chiefly here so that applications can use "COPY <rel> to stdout"
1821  * and read the output string.  Returns a null-terminated string in s.
1822  *
1823  * XXX this routine is now deprecated, because it can't handle binary data.
1824  * If called during a COPY BINARY we return EOF.
1825  *
1826  * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
1827  * the terminating \n (like gets(3)).
1828  *
1829  * CAUTION: the caller is responsible for detecting the end-of-copy signal
1830  * (a line containing just "\.") when using this routine.
1831  *
1832  * RETURNS:
1833  *              EOF if error (eg, invalid arguments are given)
1834  *              0 if EOL is reached (i.e., \n has been read)
1835  *                              (this is required for backward-compatibility -- this
1836  *                               routine used to always return EOF or 0, assuming that
1837  *                               the line ended within maxlen bytes.)
1838  *              1 in other cases (i.e., the buffer was filled before \n is reached)
1839  */
1840 int
1841 PQgetline(PGconn *conn, char *s, int maxlen)
1842 {
1843         if (!s || maxlen <= 0)
1844                 return EOF;
1845         *s = '\0';
1846         /* maxlen must be at least 3 to hold the \. terminator! */
1847         if (maxlen < 3)
1848                 return EOF;
1849
1850         if (!conn)
1851                 return EOF;
1852
1853         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1854                 return pqGetline3(conn, s, maxlen);
1855         else
1856                 return pqGetline2(conn, s, maxlen);
1857 }
1858
1859 /*
1860  * PQgetlineAsync - gets a COPY data row without blocking.
1861  *
1862  * This routine is for applications that want to do "COPY <rel> to stdout"
1863  * asynchronously, that is without blocking.  Having issued the COPY command
1864  * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
1865  * and this routine until the end-of-data signal is detected.  Unlike
1866  * PQgetline, this routine takes responsibility for detecting end-of-data.
1867  *
1868  * On each call, PQgetlineAsync will return data if a complete data row
1869  * is available in libpq's input buffer.  Otherwise, no data is returned
1870  * until the rest of the row arrives.
1871  *
1872  * If -1 is returned, the end-of-data signal has been recognized (and removed
1873  * from libpq's input buffer).  The caller *must* next call PQendcopy and
1874  * then return to normal processing.
1875  *
1876  * RETURNS:
1877  *       -1    if the end-of-copy-data marker has been recognized
1878  *       0         if no data is available
1879  *       >0    the number of bytes returned.
1880  *
1881  * The data returned will not extend beyond a data-row boundary.  If possible
1882  * a whole row will be returned at one time.  But if the buffer offered by
1883  * the caller is too small to hold a row sent by the backend, then a partial
1884  * data row will be returned.  In text mode this can be detected by testing
1885  * whether the last returned byte is '\n' or not.
1886  *
1887  * The returned data is *not* null-terminated.
1888  */
1889
1890 int
1891 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
1892 {
1893         if (!conn)
1894                 return -1;
1895
1896         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1897                 return pqGetlineAsync3(conn, buffer, bufsize);
1898         else
1899                 return pqGetlineAsync2(conn, buffer, bufsize);
1900 }
1901
1902 /*
1903  * PQputline -- sends a string to the backend during COPY IN.
1904  * Returns 0 if OK, EOF if not.
1905  *
1906  * This is deprecated primarily because the return convention doesn't allow
1907  * caller to tell the difference between a hard error and a nonblock-mode
1908  * send failure.
1909  */
1910 int
1911 PQputline(PGconn *conn, const char *s)
1912 {
1913         return PQputnbytes(conn, s, strlen(s));
1914 }
1915
1916 /*
1917  * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
1918  * Returns 0 if OK, EOF if not.
1919  */
1920 int
1921 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
1922 {
1923         if (PQputCopyData(conn, buffer, nbytes) > 0)
1924                 return 0;
1925         else
1926                 return EOF;
1927 }
1928
1929 /*
1930  * PQendcopy
1931  *              After completing the data transfer portion of a copy in/out,
1932  *              the application must call this routine to finish the command protocol.
1933  *
1934  * When using protocol 3.0 this is deprecated; it's cleaner to use PQgetResult
1935  * to get the transfer status.  Note however that when using 2.0 protocol,
1936  * recovering from a copy failure often requires a PQreset.  PQendcopy will
1937  * take care of that, PQgetResult won't.
1938  *
1939  * RETURNS:
1940  *              0 on success
1941  *              1 on failure
1942  */
1943 int
1944 PQendcopy(PGconn *conn)
1945 {
1946         if (!conn)
1947                 return 0;
1948
1949         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1950                 return pqEndcopy3(conn);
1951         else
1952                 return pqEndcopy2(conn);
1953 }
1954
1955
1956 /* ----------------
1957  *              PQfn -  Send a function call to the POSTGRES backend.
1958  *
1959  *              conn                    : backend connection
1960  *              fnid                    : function id
1961  *              result_buf              : pointer to result buffer (&int if integer)
1962  *              result_len              : length of return value.
1963  *              actual_result_len: actual length returned. (differs from result_len
1964  *                                                for varlena structures.)
1965  *              result_type             : If the result is an integer, this must be 1,
1966  *                                                otherwise this should be 0
1967  *              args                    : pointer to an array of function arguments.
1968  *                                                (each has length, if integer, and value/pointer)
1969  *              nargs                   : # of arguments in args array.
1970  *
1971  * RETURNS
1972  *              PGresult with status = PGRES_COMMAND_OK if successful.
1973  *                      *actual_result_len is > 0 if there is a return value, 0 if not.
1974  *              PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
1975  *              NULL on communications failure.  conn->errorMessage will be set.
1976  * ----------------
1977  */
1978
1979 PGresult *
1980 PQfn(PGconn *conn,
1981          int fnid,
1982          int *result_buf,
1983          int *actual_result_len,
1984          int result_is_int,
1985          const PQArgBlock *args,
1986          int nargs)
1987 {
1988         *actual_result_len = 0;
1989
1990         if (!conn)
1991                 return NULL;
1992
1993         /* clear the error string */
1994         resetPQExpBuffer(&conn->errorMessage);
1995
1996         if (conn->sock < 0 || conn->asyncStatus != PGASYNC_IDLE ||
1997                 conn->result != NULL)
1998         {
1999                 printfPQExpBuffer(&conn->errorMessage,
2000                                                   libpq_gettext("connection in wrong state\n"));
2001                 return NULL;
2002         }
2003
2004         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2005                 return pqFunctionCall3(conn, fnid,
2006                                                            result_buf, actual_result_len,
2007                                                            result_is_int,
2008                                                            args, nargs);
2009         else
2010                 return pqFunctionCall2(conn, fnid,
2011                                                            result_buf, actual_result_len,
2012                                                            result_is_int,
2013                                                            args, nargs);
2014 }
2015
2016
2017 /* ====== accessor funcs for PGresult ======== */
2018
2019 ExecStatusType
2020 PQresultStatus(const PGresult *res)
2021 {
2022         if (!res)
2023                 return PGRES_FATAL_ERROR;
2024         return res->resultStatus;
2025 }
2026
2027 char *
2028 PQresStatus(ExecStatusType status)
2029 {
2030         if (status < 0 || status >= sizeof pgresStatus / sizeof pgresStatus[0])
2031                 return libpq_gettext("invalid ExecStatusType code");
2032         return pgresStatus[status];
2033 }
2034
2035 char *
2036 PQresultErrorMessage(const PGresult *res)
2037 {
2038         if (!res || !res->errMsg)
2039                 return "";
2040         return res->errMsg;
2041 }
2042
2043 char *
2044 PQresultErrorField(const PGresult *res, int fieldcode)
2045 {
2046         PGMessageField *pfield;
2047
2048         if (!res)
2049                 return NULL;
2050         for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
2051         {
2052                 if (pfield->code == fieldcode)
2053                         return pfield->contents;
2054         }
2055         return NULL;
2056 }
2057
2058 int
2059 PQntuples(const PGresult *res)
2060 {
2061         if (!res)
2062                 return 0;
2063         return res->ntups;
2064 }
2065
2066 int
2067 PQnfields(const PGresult *res)
2068 {
2069         if (!res)
2070                 return 0;
2071         return res->numAttributes;
2072 }
2073
2074 int
2075 PQbinaryTuples(const PGresult *res)
2076 {
2077         if (!res)
2078                 return 0;
2079         return res->binary;
2080 }
2081
2082 /*
2083  * Helper routines to range-check field numbers and tuple numbers.
2084  * Return TRUE if OK, FALSE if not
2085  */
2086
2087 static int
2088 check_field_number(const PGresult *res, int field_num)
2089 {
2090         if (!res)
2091                 return FALSE;                   /* no way to display error message... */
2092         if (field_num < 0 || field_num >= res->numAttributes)
2093         {
2094                 pqInternalNotice(&res->noticeHooks,
2095                                                  "column number %d is out of range 0..%d",
2096                                                  field_num, res->numAttributes - 1);
2097                 return FALSE;
2098         }
2099         return TRUE;
2100 }
2101
2102 static int
2103 check_tuple_field_number(const PGresult *res,
2104                                                  int tup_num, int field_num)
2105 {
2106         if (!res)
2107                 return FALSE;                   /* no way to display error message... */
2108         if (tup_num < 0 || tup_num >= res->ntups)
2109         {
2110                 pqInternalNotice(&res->noticeHooks,
2111                                                  "row number %d is out of range 0..%d",
2112                                                  tup_num, res->ntups - 1);
2113                 return FALSE;
2114         }
2115         if (field_num < 0 || field_num >= res->numAttributes)
2116         {
2117                 pqInternalNotice(&res->noticeHooks,
2118                                                  "column number %d is out of range 0..%d",
2119                                                  field_num, res->numAttributes - 1);
2120                 return FALSE;
2121         }
2122         return TRUE;
2123 }
2124
2125 static int
2126 check_param_number(const PGresult *res, int param_num)
2127 {
2128         if (!res)
2129                 return FALSE;                   /* no way to display error message... */
2130         if (param_num < 0 || param_num >= res->numParameters)
2131         {
2132                 pqInternalNotice(&res->noticeHooks,
2133                                                  "parameter number %d is out of range 0..%d",
2134                                                  param_num, res->numParameters - 1);
2135                 return FALSE;
2136         }
2137         
2138         return TRUE;
2139 }
2140
2141 /*
2142  * returns NULL if the field_num is invalid
2143  */
2144 char *
2145 PQfname(const PGresult *res, int field_num)
2146 {
2147         if (!check_field_number(res, field_num))
2148                 return NULL;
2149         if (res->attDescs)
2150                 return res->attDescs[field_num].name;
2151         else
2152                 return NULL;
2153 }
2154
2155 /*
2156  * PQfnumber: find column number given column name
2157  *
2158  * The column name is parsed as if it were in a SQL statement, including
2159  * case-folding and double-quote processing.  But note a possible gotcha:
2160  * downcasing in the frontend might follow different locale rules than
2161  * downcasing in the backend...
2162  *
2163  * Returns -1 if no match.      In the present backend it is also possible
2164  * to have multiple matches, in which case the first one is found.
2165  */
2166 int
2167 PQfnumber(const PGresult *res, const char *field_name)
2168 {
2169         char       *field_case;
2170         bool            in_quotes;
2171         char       *iptr;
2172         char       *optr;
2173         int                     i;
2174
2175         if (!res)
2176                 return -1;
2177
2178         /*
2179          * Note: it is correct to reject a zero-length input string; the proper
2180          * input to match a zero-length field name would be "".
2181          */
2182         if (field_name == NULL ||
2183                 field_name[0] == '\0' ||
2184                 res->attDescs == NULL)
2185                 return -1;
2186
2187         /*
2188          * Note: this code will not reject partially quoted strings, eg
2189          * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
2190          * condition.
2191          */
2192         field_case = strdup(field_name);
2193         if (field_case == NULL)
2194                 return -1;                              /* grotty */
2195
2196         in_quotes = false;
2197         optr = field_case;
2198         for (iptr = field_case; *iptr; iptr++)
2199         {
2200                 char            c = *iptr;
2201
2202                 if (in_quotes)
2203                 {
2204                         if (c == '"')
2205                         {
2206                                 if (iptr[1] == '"')
2207                                 {
2208                                         /* doubled quotes become a single quote */
2209                                         *optr++ = '"';
2210                                         iptr++;
2211                                 }
2212                                 else
2213                                         in_quotes = false;
2214                         }
2215                         else
2216                                 *optr++ = c;
2217                 }
2218                 else if (c == '"')
2219                         in_quotes = true;
2220                 else
2221                 {
2222                         c = pg_tolower((unsigned char) c);
2223                         *optr++ = c;
2224                 }
2225         }
2226         *optr = '\0';
2227
2228         for (i = 0; i < res->numAttributes; i++)
2229         {
2230                 if (strcmp(field_case, res->attDescs[i].name) == 0)
2231                 {
2232                         free(field_case);
2233                         return i;
2234                 }
2235         }
2236         free(field_case);
2237         return -1;
2238 }
2239
2240 Oid
2241 PQftable(const PGresult *res, int field_num)
2242 {
2243         if (!check_field_number(res, field_num))
2244                 return InvalidOid;
2245         if (res->attDescs)
2246                 return res->attDescs[field_num].tableid;
2247         else
2248                 return InvalidOid;
2249 }
2250
2251 int
2252 PQftablecol(const PGresult *res, int field_num)
2253 {
2254         if (!check_field_number(res, field_num))
2255                 return 0;
2256         if (res->attDescs)
2257                 return res->attDescs[field_num].columnid;
2258         else
2259                 return 0;
2260 }
2261
2262 int
2263 PQfformat(const PGresult *res, int field_num)
2264 {
2265         if (!check_field_number(res, field_num))
2266                 return 0;
2267         if (res->attDescs)
2268                 return res->attDescs[field_num].format;
2269         else
2270                 return 0;
2271 }
2272
2273 Oid
2274 PQftype(const PGresult *res, int field_num)
2275 {
2276         if (!check_field_number(res, field_num))
2277                 return InvalidOid;
2278         if (res->attDescs)
2279                 return res->attDescs[field_num].typid;
2280         else
2281                 return InvalidOid;
2282 }
2283
2284 int
2285 PQfsize(const PGresult *res, int field_num)
2286 {
2287         if (!check_field_number(res, field_num))
2288                 return 0;
2289         if (res->attDescs)
2290                 return res->attDescs[field_num].typlen;
2291         else
2292                 return 0;
2293 }
2294
2295 int
2296 PQfmod(const PGresult *res, int field_num)
2297 {
2298         if (!check_field_number(res, field_num))
2299                 return 0;
2300         if (res->attDescs)
2301                 return res->attDescs[field_num].atttypmod;
2302         else
2303                 return 0;
2304 }
2305
2306 char *
2307 PQcmdStatus(PGresult *res)
2308 {
2309         if (!res)
2310                 return NULL;
2311         return res->cmdStatus;
2312 }
2313
2314 /*
2315  * PQoidStatus -
2316  *      if the last command was an INSERT, return the oid string
2317  *      if not, return ""
2318  */
2319 char *
2320 PQoidStatus(const PGresult *res)
2321 {
2322         /*
2323          * This must be enough to hold the result. Don't laugh, this is better
2324          * than what this function used to do.
2325          */
2326         static char buf[24];
2327
2328         size_t          len;
2329
2330         if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2331                 return "";
2332
2333         len = strspn(res->cmdStatus + 7, "0123456789");
2334         if (len > 23)
2335                 len = 23;
2336         strncpy(buf, res->cmdStatus + 7, len);
2337         buf[len] = '\0';
2338
2339         return buf;
2340 }
2341
2342 /*
2343  * PQoidValue -
2344  *      a perhaps preferable form of the above which just returns
2345  *      an Oid type
2346  */
2347 Oid
2348 PQoidValue(const PGresult *res)
2349 {
2350         char       *endptr = NULL;
2351         unsigned long result;
2352
2353         if (!res ||
2354                 !res->cmdStatus ||
2355                 strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
2356                 res->cmdStatus[7] < '0' ||
2357                 res->cmdStatus[7] > '9')
2358                 return InvalidOid;
2359
2360         result = strtoul(res->cmdStatus + 7, &endptr, 10);
2361
2362         if (!endptr || (*endptr != ' ' && *endptr != '\0'))
2363                 return InvalidOid;
2364         else
2365                 return (Oid) result;
2366 }
2367
2368
2369 /*
2370  * PQcmdTuples -
2371  *      If the last command was INSERT/UPDATE/DELETE/MOVE/FETCH/COPY, return
2372  *      a string containing the number of inserted/affected tuples. If not,
2373  *      return "".
2374  *
2375  *      XXX: this should probably return an int
2376  */
2377 char *
2378 PQcmdTuples(PGresult *res)
2379 {
2380         char       *p, *c;
2381
2382         if (!res)
2383                 return "";
2384
2385         if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
2386         {
2387                 p = res->cmdStatus + 7;
2388                 /* INSERT: skip oid and space */
2389                 while (*p && *p != ' ')
2390                         p++;
2391                 if (*p == 0)
2392                         goto interpret_error;                           /* no space? */
2393                 p++;
2394         }
2395         else if (strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
2396                          strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
2397                 p = res->cmdStatus + 7;
2398         else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
2399                 p = res->cmdStatus + 6;
2400         else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
2401                          strncmp(res->cmdStatus, "COPY ", 5) == 0)
2402                 p = res->cmdStatus + 5;
2403         else
2404                 return "";
2405
2406         /* check that we have an integer (at least one digit, nothing else) */
2407         for (c = p; *c; c++)
2408         {
2409                 if (!isdigit((unsigned char) *c))
2410                         goto interpret_error;
2411         }
2412         if (c == p)
2413                 goto interpret_error;
2414
2415         return p;
2416         
2417 interpret_error:
2418         pqInternalNotice(&res->noticeHooks,
2419                                          "could not interpret result from server: %s",
2420                                          res->cmdStatus);
2421         return "";
2422 }
2423
2424 /*
2425  * PQgetvalue:
2426  *      return the value of field 'field_num' of row 'tup_num'
2427  */
2428 char *
2429 PQgetvalue(const PGresult *res, int tup_num, int field_num)
2430 {
2431         if (!check_tuple_field_number(res, tup_num, field_num))
2432                 return NULL;
2433         return res->tuples[tup_num][field_num].value;
2434 }
2435
2436 /* PQgetlength:
2437  *      returns the actual length of a field value in bytes.
2438  */
2439 int
2440 PQgetlength(const PGresult *res, int tup_num, int field_num)
2441 {
2442         if (!check_tuple_field_number(res, tup_num, field_num))
2443                 return 0;
2444         if (res->tuples[tup_num][field_num].len != NULL_LEN)
2445                 return res->tuples[tup_num][field_num].len;
2446         else
2447                 return 0;
2448 }
2449
2450 /* PQgetisnull:
2451  *      returns the null status of a field value.
2452  */
2453 int
2454 PQgetisnull(const PGresult *res, int tup_num, int field_num)
2455 {
2456         if (!check_tuple_field_number(res, tup_num, field_num))
2457                 return 1;                               /* pretend it is null */
2458         if (res->tuples[tup_num][field_num].len == NULL_LEN)
2459                 return 1;
2460         else
2461                 return 0;
2462 }
2463
2464 /* PQnparams:
2465  *      returns the number of input parameters of a prepared statement.
2466  */
2467 int
2468 PQnparams(const PGresult *res)
2469 {
2470         if (!res)
2471                 return 0;
2472         return res->numParameters;
2473 }
2474
2475 /* PQparamtype:
2476  *      returns type Oid of the specified statement parameter.
2477  */
2478 Oid
2479 PQparamtype(const PGresult *res, int param_num)
2480 {
2481         if (!check_param_number(res, param_num))
2482                 return InvalidOid;
2483         if (res->paramDescs)
2484                 return res->paramDescs[param_num].typid;
2485         else
2486                 return InvalidOid;
2487 }
2488
2489
2490 /* PQsetnonblocking:
2491  *      sets the PGconn's database connection non-blocking if the arg is TRUE
2492  *      or makes it non-blocking if the arg is FALSE, this will not protect
2493  *      you from PQexec(), you'll only be safe when using the non-blocking API.
2494  *      Needs to be called only on a connected database connection.
2495  */
2496 int
2497 PQsetnonblocking(PGconn *conn, int arg)
2498 {
2499         bool            barg;
2500
2501         if (!conn || conn->status == CONNECTION_BAD)
2502                 return -1;
2503
2504         barg = (arg ? TRUE : FALSE);
2505
2506         /* early out if the socket is already in the state requested */
2507         if (barg == conn->nonblocking)
2508                 return 0;
2509
2510         /*
2511          * to guarantee constancy for flushing/query/result-polling behavior we
2512          * need to flush the send queue at this point in order to guarantee proper
2513          * behavior. this is ok because either they are making a transition _from_
2514          * or _to_ blocking mode, either way we can block them.
2515          */
2516         /* if we are going from blocking to non-blocking flush here */
2517         if (pqFlush(conn))
2518                 return -1;
2519
2520         conn->nonblocking = barg;
2521
2522         return 0;
2523 }
2524
2525 /*
2526  * return the blocking status of the database connection
2527  *              TRUE == nonblocking, FALSE == blocking
2528  */
2529 int
2530 PQisnonblocking(const PGconn *conn)
2531 {
2532         return pqIsnonblocking(conn);
2533 }
2534
2535 /* libpq is thread-safe? */
2536 int
2537 PQisthreadsafe(void)
2538 {
2539 #ifdef ENABLE_THREAD_SAFETY
2540         return true;
2541 #else
2542         return false;
2543 #endif
2544 }
2545
2546
2547 /* try to force data out, really only useful for non-blocking users */
2548 int
2549 PQflush(PGconn *conn)
2550 {
2551         return pqFlush(conn);
2552 }
2553
2554
2555 /*
2556  *              PQfreemem - safely frees memory allocated
2557  *
2558  * Needed mostly by Win32, unless multithreaded DLL (/MD in VC6)
2559  * Used for freeing memory from PQescapeByte()a/PQunescapeBytea()
2560  */
2561 void
2562 PQfreemem(void *ptr)
2563 {
2564         free(ptr);
2565 }
2566
2567 /*
2568  * PQfreeNotify - free's the memory associated with a PGnotify
2569  *
2570  * This function is here only for binary backward compatibility.
2571  * New code should use PQfreemem().  A macro will automatically map
2572  * calls to PQfreemem.  It should be removed in the future.  bjm 2003-03-24
2573  */
2574
2575 #undef PQfreeNotify
2576 void            PQfreeNotify(PGnotify *notify);
2577
2578 void
2579 PQfreeNotify(PGnotify *notify)
2580 {
2581         PQfreemem(notify);
2582 }
2583
2584
2585 /*
2586  * Escaping arbitrary strings to get valid SQL literal strings.
2587  *
2588  * Replaces "'" with "''", and if not std_strings, replaces "\" with "\\".
2589  *
2590  * length is the length of the source string.  (Note: if a terminating NUL
2591  * is encountered sooner, PQescapeString stops short of "length"; the behavior
2592  * is thus rather like strncpy.)
2593  *
2594  * For safety the buffer at "to" must be at least 2*length + 1 bytes long.
2595  * A terminating NUL character is added to the output string, whether the
2596  * input is NUL-terminated or not.
2597  *
2598  * Returns the actual length of the output (not counting the terminating NUL).
2599  */
2600 static size_t
2601 PQescapeStringInternal(PGconn *conn,
2602                                            char *to, const char *from, size_t length,
2603                                            int *error,
2604                                            int encoding, bool std_strings)
2605 {
2606         const char *source = from;
2607         char       *target = to;
2608         size_t          remaining = length;
2609
2610         if (error)
2611                 *error = 0;
2612
2613         while (remaining > 0 && *source != '\0')
2614         {
2615                 char    c = *source;
2616                 int             len;
2617                 int             i;
2618
2619                 /* Fast path for plain ASCII */
2620                 if (!IS_HIGHBIT_SET(c))
2621                 {
2622                         /* Apply quoting if needed */
2623                         if (SQL_STR_DOUBLE(c, !std_strings))
2624                                 *target++ = c;
2625                         /* Copy the character */
2626                         *target++ = c;
2627                         source++;
2628                         remaining--;
2629                         continue;
2630                 }
2631
2632                 /* Slow path for possible multibyte characters */
2633                 len = pg_encoding_mblen(encoding, source);
2634
2635                 /* Copy the character */
2636                 for (i = 0; i < len; i++)
2637                 {
2638                         if (remaining == 0 || *source == '\0')
2639                                 break;
2640                         *target++ = *source++;
2641                         remaining--;
2642                 }
2643
2644                 /*
2645                  * If we hit premature end of string (ie, incomplete multibyte
2646                  * character), try to pad out to the correct length with spaces.
2647                  * We may not be able to pad completely, but we will always be able
2648                  * to insert at least one pad space (since we'd not have quoted a
2649                  * multibyte character).  This should be enough to make a string that
2650                  * the server will error out on.
2651                  */
2652                 if (i < len)
2653                 {
2654                         if (error)
2655                                 *error = 1;
2656                         if (conn)
2657                                 printfPQExpBuffer(&conn->errorMessage,
2658                                                 libpq_gettext("incomplete multibyte character\n"));
2659                         for (; i < len; i++)
2660                         {
2661                                 if (((size_t) (target - to)) / 2 >= length)
2662                                         break;
2663                                 *target++ = ' ';
2664                         }
2665                         break;
2666                 }
2667         }
2668
2669         /* Write the terminating NUL character. */
2670         *target = '\0';
2671
2672         return target - to;
2673 }
2674
2675 size_t
2676 PQescapeStringConn(PGconn *conn,
2677                                    char *to, const char *from, size_t length,
2678                                    int *error)
2679 {
2680         if (!conn)
2681         {
2682                 /* force empty-string result */
2683                 *to = '\0';
2684                 if (error)
2685                         *error = 1;
2686                 return 0;
2687         }
2688         return PQescapeStringInternal(conn, to, from, length, error,
2689                                                                   conn->client_encoding,
2690                                                                   conn->std_strings);
2691 }
2692
2693 size_t
2694 PQescapeString(char *to, const char *from, size_t length)
2695 {
2696         return PQescapeStringInternal(NULL, to, from, length, NULL,
2697                                                                   static_client_encoding,
2698                                                                   static_std_strings);
2699 }
2700
2701 /*
2702  *              PQescapeBytea   - converts from binary string to the
2703  *              minimal encoding necessary to include the string in an SQL
2704  *              INSERT statement with a bytea type column as the target.
2705  *
2706  *              The following transformations are applied
2707  *              '\0' == ASCII  0 == \000
2708  *              '\'' == ASCII 39 == ''
2709  *              '\\' == ASCII 92 == \\
2710  *              anything < 0x20, or > 0x7e ---> \ooo
2711  *                                                                              (where ooo is an octal expression)
2712  *              If not std_strings, all backslashes sent to the output are doubled.
2713  */
2714 static unsigned char *
2715 PQescapeByteaInternal(PGconn *conn,
2716                                           const unsigned char *from, size_t from_length,
2717                                           size_t *to_length, bool std_strings)
2718 {
2719         const unsigned char *vp;
2720         unsigned char *rp;
2721         unsigned char *result;
2722         size_t          i;
2723         size_t          len;
2724         size_t          bslash_len = (std_strings ? 1 : 2);
2725
2726         /*
2727          * empty string has 1 char ('\0')
2728          */
2729         len = 1;
2730
2731         vp = from;
2732         for (i = from_length; i > 0; i--, vp++)
2733         {
2734                 if (*vp < 0x20 || *vp > 0x7e)
2735                         len += bslash_len + 3;
2736                 else if (*vp == '\'')
2737                         len += 2;
2738                 else if (*vp == '\\')
2739                         len += bslash_len + bslash_len;
2740                 else
2741                         len++;
2742         }
2743
2744         *to_length = len;
2745         rp = result = (unsigned char *) malloc(len);
2746         if (rp == NULL)
2747         {
2748                 if (conn)
2749                         printfPQExpBuffer(&conn->errorMessage,
2750                                                           libpq_gettext("out of memory\n"));
2751                 return NULL;
2752         }
2753
2754         vp = from;
2755         for (i = from_length; i > 0; i--, vp++)
2756         {
2757                 if (*vp < 0x20 || *vp > 0x7e)
2758                 {
2759                         if (!std_strings)
2760                                 *rp++ = '\\';
2761                         (void) sprintf((char *) rp, "\\%03o", *vp);
2762                         rp += 4;
2763                 }
2764                 else if (*vp == '\'')
2765                 {
2766                         *rp++ = '\'';
2767                         *rp++ = '\'';
2768                 }
2769                 else if (*vp == '\\')
2770                 {
2771                         if (!std_strings)
2772                         {
2773                                 *rp++ = '\\';
2774                                 *rp++ = '\\';
2775                         }
2776                         *rp++ = '\\';
2777                         *rp++ = '\\';
2778                 }
2779                 else
2780                         *rp++ = *vp;
2781         }
2782         *rp = '\0';
2783
2784         return result;
2785 }
2786
2787 unsigned char *
2788 PQescapeByteaConn(PGconn *conn,
2789                                   const unsigned char *from, size_t from_length,
2790                                   size_t *to_length)
2791 {
2792         if (!conn)
2793                 return NULL;
2794         return PQescapeByteaInternal(conn, from, from_length, to_length,
2795                                                                  conn->std_strings);
2796 }
2797
2798 unsigned char *
2799 PQescapeBytea(const unsigned char *from, size_t from_length, size_t *to_length)
2800 {
2801         return PQescapeByteaInternal(NULL, from, from_length, to_length,
2802                                                                  static_std_strings);
2803 }
2804
2805
2806 #define ISFIRSTOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '3')
2807 #define ISOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '7')
2808 #define OCTVAL(CH) ((CH) - '0')
2809
2810 /*
2811  *              PQunescapeBytea - converts the null terminated string representation
2812  *              of a bytea, strtext, into binary, filling a buffer. It returns a
2813  *              pointer to the buffer (or NULL on error), and the size of the
2814  *              buffer in retbuflen. The pointer may subsequently be used as an
2815  *              argument to the function PQfreemem.
2816  *
2817  *              The following transformations are made:
2818  *              \\       == ASCII 92 == \
2819  *              \ooo == a byte whose value = ooo (ooo is an octal number)
2820  *              \x       == x (x is any character not matched by the above transformations)
2821  */
2822 unsigned char *
2823 PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
2824 {
2825         size_t          strtextlen,
2826                                 buflen;
2827         unsigned char *buffer,
2828                            *tmpbuf;
2829         size_t          i,
2830                                 j;
2831
2832         if (strtext == NULL)
2833                 return NULL;
2834
2835         strtextlen = strlen((const char *) strtext);
2836
2837         /*
2838          * Length of input is max length of output, but add one to avoid
2839          * unportable malloc(0) if input is zero-length.
2840          */
2841         buffer = (unsigned char *) malloc(strtextlen + 1);
2842         if (buffer == NULL)
2843                 return NULL;
2844
2845         for (i = j = 0; i < strtextlen;)
2846         {
2847                 switch (strtext[i])
2848                 {
2849                         case '\\':
2850                                 i++;
2851                                 if (strtext[i] == '\\')
2852                                         buffer[j++] = strtext[i++];
2853                                 else
2854                                 {
2855                                         if ((ISFIRSTOCTDIGIT(strtext[i])) &&
2856                                                 (ISOCTDIGIT(strtext[i + 1])) &&
2857                                                 (ISOCTDIGIT(strtext[i + 2])))
2858                                         {
2859                                                 int                     byte;
2860
2861                                                 byte = OCTVAL(strtext[i++]);
2862                                                 byte = (byte << 3) + OCTVAL(strtext[i++]);
2863                                                 byte = (byte << 3) + OCTVAL(strtext[i++]);
2864                                                 buffer[j++] = byte;
2865                                         }
2866                                 }
2867
2868                                 /*
2869                                  * Note: if we see '\' followed by something that isn't a
2870                                  * recognized escape sequence, we loop around having done
2871                                  * nothing except advance i.  Therefore the something will be
2872                                  * emitted as ordinary data on the next cycle. Corner case:
2873                                  * '\' at end of string will just be discarded.
2874                                  */
2875                                 break;
2876
2877                         default:
2878                                 buffer[j++] = strtext[i++];
2879                                 break;
2880                 }
2881         }
2882         buflen = j;                                     /* buflen is the length of the dequoted data */
2883
2884         /* Shrink the buffer to be no larger than necessary */
2885         /* +1 avoids unportable behavior when buflen==0 */
2886         tmpbuf = realloc(buffer, buflen + 1);
2887
2888         /* It would only be a very brain-dead realloc that could fail, but... */
2889         if (!tmpbuf)
2890         {
2891                 free(buffer);
2892                 return NULL;
2893         }
2894
2895         *retbuflen = buflen;
2896         return tmpbuf;
2897 }