]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-exec.c
Additional spelling corrections
[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-2013, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/interfaces/libpq/fe-exec.c
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         "PGRES_COPY_BOTH",
42         "PGRES_SINGLE_TUPLE"
43 };
44
45 /*
46  * static state needed by PQescapeString and PQescapeBytea; initialize to
47  * values that result in backward-compatible behavior
48  */
49 static int      static_client_encoding = PG_SQL_ASCII;
50 static bool static_std_strings = false;
51
52
53 static PGEvent *dupEvents(PGEvent *events, int count);
54 static bool pqAddTuple(PGresult *res, PGresAttValue *tup);
55 static bool PQsendQueryStart(PGconn *conn);
56 static int PQsendQueryGuts(PGconn *conn,
57                                 const char *command,
58                                 const char *stmtName,
59                                 int nParams,
60                                 const Oid *paramTypes,
61                                 const char *const * paramValues,
62                                 const int *paramLengths,
63                                 const int *paramFormats,
64                                 int resultFormat);
65 static void parseInput(PGconn *conn);
66 static bool PQexecStart(PGconn *conn);
67 static PGresult *PQexecFinish(PGconn *conn);
68 static int PQsendDescribe(PGconn *conn, char desc_type,
69                            const char *desc_target);
70 static int      check_field_number(const PGresult *res, int field_num);
71
72
73 /* ----------------
74  * Space management for PGresult.
75  *
76  * Formerly, libpq did a separate malloc() for each field of each tuple
77  * returned by a query.  This was remarkably expensive --- malloc/free
78  * consumed a sizable part of the application's runtime.  And there is
79  * no real need to keep track of the fields separately, since they will
80  * all be freed together when the PGresult is released.  So now, we grab
81  * large blocks of storage from malloc and allocate space for query data
82  * within these blocks, using a trivially simple allocator.  This reduces
83  * the number of malloc/free calls dramatically, and it also avoids
84  * fragmentation of the malloc storage arena.
85  * The PGresult structure itself is still malloc'd separately.  We could
86  * combine it with the first allocation block, but that would waste space
87  * for the common case that no extra storage is actually needed (that is,
88  * the SQL command did not return tuples).
89  *
90  * We also malloc the top-level array of tuple pointers separately, because
91  * we need to be able to enlarge it via realloc, and our trivial space
92  * allocator doesn't handle that effectively.  (Too bad the FE/BE protocol
93  * doesn't tell us up front how many tuples will be returned.)
94  * All other subsidiary storage for a PGresult is kept in PGresult_data blocks
95  * of size PGRESULT_DATA_BLOCKSIZE.  The overhead at the start of each block
96  * is just a link to the next one, if any.      Free-space management info is
97  * kept in the owning PGresult.
98  * A query returning a small amount of data will thus require three malloc
99  * calls: one for the PGresult, one for the tuples pointer array, and one
100  * PGresult_data block.
101  *
102  * Only the most recently allocated PGresult_data block is a candidate to
103  * have more stuff added to it --- any extra space left over in older blocks
104  * is wasted.  We could be smarter and search the whole chain, but the point
105  * here is to be simple and fast.  Typical applications do not keep a PGresult
106  * around very long anyway, so some wasted space within one is not a problem.
107  *
108  * Tuning constants for the space allocator are:
109  * PGRESULT_DATA_BLOCKSIZE: size of a standard allocation block, in bytes
110  * PGRESULT_ALIGN_BOUNDARY: assumed alignment requirement for binary data
111  * PGRESULT_SEP_ALLOC_THRESHOLD: objects bigger than this are given separate
112  *       blocks, instead of being crammed into a regular allocation block.
113  * Requirements for correct function are:
114  * PGRESULT_ALIGN_BOUNDARY must be a multiple of the alignment requirements
115  *              of all machine data types.      (Currently this is set from configure
116  *              tests, so it should be OK automatically.)
117  * PGRESULT_SEP_ALLOC_THRESHOLD + PGRESULT_BLOCK_OVERHEAD <=
118  *                      PGRESULT_DATA_BLOCKSIZE
119  *              pqResultAlloc assumes an object smaller than the threshold will fit
120  *              in a new block.
121  * The amount of space wasted at the end of a block could be as much as
122  * PGRESULT_SEP_ALLOC_THRESHOLD, so it doesn't pay to make that too large.
123  * ----------------
124  */
125
126 #define PGRESULT_DATA_BLOCKSIZE         2048
127 #define PGRESULT_ALIGN_BOUNDARY         MAXIMUM_ALIGNOF         /* from configure */
128 #define PGRESULT_BLOCK_OVERHEAD         Max(sizeof(PGresult_data), PGRESULT_ALIGN_BOUNDARY)
129 #define PGRESULT_SEP_ALLOC_THRESHOLD    (PGRESULT_DATA_BLOCKSIZE / 2)
130
131
132 /*
133  * PQmakeEmptyPGresult
134  *       returns a newly allocated, initialized PGresult with given status.
135  *       If conn is not NULL and status indicates an error, the conn's
136  *       errorMessage is copied.  Also, any PGEvents are copied from the conn.
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->events = NULL;
158         result->nEvents = 0;
159         result->errMsg = NULL;
160         result->errFields = NULL;
161         result->null_field[0] = '\0';
162         result->curBlock = NULL;
163         result->curOffset = 0;
164         result->spaceLeft = 0;
165
166         if (conn)
167         {
168                 /* copy connection data we might need for operations on PGresult */
169                 result->noticeHooks = conn->noticeHooks;
170                 result->client_encoding = conn->client_encoding;
171
172                 /* consider copying conn's errorMessage */
173                 switch (status)
174                 {
175                         case PGRES_EMPTY_QUERY:
176                         case PGRES_COMMAND_OK:
177                         case PGRES_TUPLES_OK:
178                         case PGRES_COPY_OUT:
179                         case PGRES_COPY_IN:
180                         case PGRES_COPY_BOTH:
181                         case PGRES_SINGLE_TUPLE:
182                                 /* non-error cases */
183                                 break;
184                         default:
185                                 pqSetResultError(result, conn->errorMessage.data);
186                                 break;
187                 }
188
189                 /* copy events last; result must be valid if we need to PQclear */
190                 if (conn->nEvents > 0)
191                 {
192                         result->events = dupEvents(conn->events, conn->nEvents);
193                         if (!result->events)
194                         {
195                                 PQclear(result);
196                                 return NULL;
197                         }
198                         result->nEvents = conn->nEvents;
199                 }
200         }
201         else
202         {
203                 /* defaults... */
204                 result->noticeHooks.noticeRec = NULL;
205                 result->noticeHooks.noticeRecArg = NULL;
206                 result->noticeHooks.noticeProc = NULL;
207                 result->noticeHooks.noticeProcArg = NULL;
208                 result->client_encoding = PG_SQL_ASCII;
209         }
210
211         return result;
212 }
213
214 /*
215  * PQsetResultAttrs
216  *
217  * Set the attributes for a given result.  This function fails if there are
218  * already attributes contained in the provided result.  The call is
219  * ignored if numAttributes is zero or attDescs is NULL.  If the
220  * function fails, it returns zero.  If the function succeeds, it
221  * returns a non-zero value.
222  */
223 int
224 PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs)
225 {
226         int                     i;
227
228         /* If attrs already exist, they cannot be overwritten. */
229         if (!res || res->numAttributes > 0)
230                 return FALSE;
231
232         /* ignore no-op request */
233         if (numAttributes <= 0 || !attDescs)
234                 return TRUE;
235
236         res->attDescs = (PGresAttDesc *)
237                 PQresultAlloc(res, numAttributes * sizeof(PGresAttDesc));
238
239         if (!res->attDescs)
240                 return FALSE;
241
242         res->numAttributes = numAttributes;
243         memcpy(res->attDescs, attDescs, numAttributes * sizeof(PGresAttDesc));
244
245         /* deep-copy the attribute names, and determine format */
246         res->binary = 1;
247         for (i = 0; i < res->numAttributes; i++)
248         {
249                 if (res->attDescs[i].name)
250                         res->attDescs[i].name = pqResultStrdup(res, res->attDescs[i].name);
251                 else
252                         res->attDescs[i].name = res->null_field;
253
254                 if (!res->attDescs[i].name)
255                         return FALSE;
256
257                 if (res->attDescs[i].format == 0)
258                         res->binary = 0;
259         }
260
261         return TRUE;
262 }
263
264 /*
265  * PQcopyResult
266  *
267  * Returns a deep copy of the provided 'src' PGresult, which cannot be NULL.
268  * The 'flags' argument controls which portions of the result will or will
269  * NOT be copied.  The created result is always put into the
270  * PGRES_TUPLES_OK status.      The source result error message is not copied,
271  * although cmdStatus is.
272  *
273  * To set custom attributes, use PQsetResultAttrs.      That function requires
274  * that there are no attrs contained in the result, so to use that
275  * function you cannot use the PG_COPYRES_ATTRS or PG_COPYRES_TUPLES
276  * options with this function.
277  *
278  * Options:
279  *       PG_COPYRES_ATTRS - Copy the source result's attributes
280  *
281  *       PG_COPYRES_TUPLES - Copy the source result's tuples.  This implies
282  *       copying the attrs, seeing how the attrs are needed by the tuples.
283  *
284  *       PG_COPYRES_EVENTS - Copy the source result's events.
285  *
286  *       PG_COPYRES_NOTICEHOOKS - Copy the source result's notice hooks.
287  */
288 PGresult *
289 PQcopyResult(const PGresult *src, int flags)
290 {
291         PGresult   *dest;
292         int                     i;
293
294         if (!src)
295                 return NULL;
296
297         dest = PQmakeEmptyPGresult(NULL, PGRES_TUPLES_OK);
298         if (!dest)
299                 return NULL;
300
301         /* Always copy these over.      Is cmdStatus really useful here? */
302         dest->client_encoding = src->client_encoding;
303         strcpy(dest->cmdStatus, src->cmdStatus);
304
305         /* Wants attrs? */
306         if (flags & (PG_COPYRES_ATTRS | PG_COPYRES_TUPLES))
307         {
308                 if (!PQsetResultAttrs(dest, src->numAttributes, src->attDescs))
309                 {
310                         PQclear(dest);
311                         return NULL;
312                 }
313         }
314
315         /* Wants to copy tuples? */
316         if (flags & PG_COPYRES_TUPLES)
317         {
318                 int                     tup,
319                                         field;
320
321                 for (tup = 0; tup < src->ntups; tup++)
322                 {
323                         for (field = 0; field < src->numAttributes; field++)
324                         {
325                                 if (!PQsetvalue(dest, tup, field,
326                                                                 src->tuples[tup][field].value,
327                                                                 src->tuples[tup][field].len))
328                                 {
329                                         PQclear(dest);
330                                         return NULL;
331                                 }
332                         }
333                 }
334         }
335
336         /* Wants to copy notice hooks? */
337         if (flags & PG_COPYRES_NOTICEHOOKS)
338                 dest->noticeHooks = src->noticeHooks;
339
340         /* Wants to copy PGEvents? */
341         if ((flags & PG_COPYRES_EVENTS) && src->nEvents > 0)
342         {
343                 dest->events = dupEvents(src->events, src->nEvents);
344                 if (!dest->events)
345                 {
346                         PQclear(dest);
347                         return NULL;
348                 }
349                 dest->nEvents = src->nEvents;
350         }
351
352         /* Okay, trigger PGEVT_RESULTCOPY event */
353         for (i = 0; i < dest->nEvents; i++)
354         {
355                 if (src->events[i].resultInitialized)
356                 {
357                         PGEventResultCopy evt;
358
359                         evt.src = src;
360                         evt.dest = dest;
361                         if (!dest->events[i].proc(PGEVT_RESULTCOPY, &evt,
362                                                                           dest->events[i].passThrough))
363                         {
364                                 PQclear(dest);
365                                 return NULL;
366                         }
367                         dest->events[i].resultInitialized = TRUE;
368                 }
369         }
370
371         return dest;
372 }
373
374 /*
375  * Copy an array of PGEvents (with no extra space for more).
376  * Does not duplicate the event instance data, sets this to NULL.
377  * Also, the resultInitialized flags are all cleared.
378  */
379 static PGEvent *
380 dupEvents(PGEvent *events, int count)
381 {
382         PGEvent    *newEvents;
383         int                     i;
384
385         if (!events || count <= 0)
386                 return NULL;
387
388         newEvents = (PGEvent *) malloc(count * sizeof(PGEvent));
389         if (!newEvents)
390                 return NULL;
391
392         for (i = 0; i < count; i++)
393         {
394                 newEvents[i].proc = events[i].proc;
395                 newEvents[i].passThrough = events[i].passThrough;
396                 newEvents[i].data = NULL;
397                 newEvents[i].resultInitialized = FALSE;
398                 newEvents[i].name = strdup(events[i].name);
399                 if (!newEvents[i].name)
400                 {
401                         while (--i >= 0)
402                                 free(newEvents[i].name);
403                         free(newEvents);
404                         return NULL;
405                 }
406         }
407
408         return newEvents;
409 }
410
411
412 /*
413  * Sets the value for a tuple field.  The tup_num must be less than or
414  * equal to PQntuples(res).  If it is equal, a new tuple is created and
415  * added to the result.
416  * Returns a non-zero value for success and zero for failure.
417  */
418 int
419 PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len)
420 {
421         PGresAttValue *attval;
422
423         if (!check_field_number(res, field_num))
424                 return FALSE;
425
426         /* Invalid tup_num, must be <= ntups */
427         if (tup_num < 0 || tup_num > res->ntups)
428                 return FALSE;
429
430         /* need to allocate a new tuple? */
431         if (tup_num == res->ntups)
432         {
433                 PGresAttValue *tup;
434                 int                     i;
435
436                 tup = (PGresAttValue *)
437                         pqResultAlloc(res, res->numAttributes * sizeof(PGresAttValue),
438                                                   TRUE);
439
440                 if (!tup)
441                         return FALSE;
442
443                 /* initialize each column to NULL */
444                 for (i = 0; i < res->numAttributes; i++)
445                 {
446                         tup[i].len = NULL_LEN;
447                         tup[i].value = res->null_field;
448                 }
449
450                 /* add it to the array */
451                 if (!pqAddTuple(res, tup))
452                         return FALSE;
453         }
454
455         attval = &res->tuples[tup_num][field_num];
456
457         /* treat either NULL_LEN or NULL value pointer as a NULL field */
458         if (len == NULL_LEN || value == NULL)
459         {
460                 attval->len = NULL_LEN;
461                 attval->value = res->null_field;
462         }
463         else if (len <= 0)
464         {
465                 attval->len = 0;
466                 attval->value = res->null_field;
467         }
468         else
469         {
470                 attval->value = (char *) pqResultAlloc(res, len + 1, TRUE);
471                 if (!attval->value)
472                         return FALSE;
473                 attval->len = len;
474                 memcpy(attval->value, value, len);
475                 attval->value[len] = '\0';
476         }
477
478         return TRUE;
479 }
480
481 /*
482  * pqResultAlloc - exported routine to allocate local storage in a PGresult.
483  *
484  * We force all such allocations to be maxaligned, since we don't know
485  * whether the value might be binary.
486  */
487 void *
488 PQresultAlloc(PGresult *res, size_t nBytes)
489 {
490         return pqResultAlloc(res, nBytes, TRUE);
491 }
492
493 /*
494  * pqResultAlloc -
495  *              Allocate subsidiary storage for a PGresult.
496  *
497  * nBytes is the amount of space needed for the object.
498  * If isBinary is true, we assume that we need to align the object on
499  * a machine allocation boundary.
500  * If isBinary is false, we assume the object is a char string and can
501  * be allocated on any byte boundary.
502  */
503 void *
504 pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
505 {
506         char       *space;
507         PGresult_data *block;
508
509         if (!res)
510                 return NULL;
511
512         if (nBytes <= 0)
513                 return res->null_field;
514
515         /*
516          * If alignment is needed, round up the current position to an alignment
517          * boundary.
518          */
519         if (isBinary)
520         {
521                 int                     offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
522
523                 if (offset)
524                 {
525                         res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
526                         res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
527                 }
528         }
529
530         /* If there's enough space in the current block, no problem. */
531         if (nBytes <= (size_t) res->spaceLeft)
532         {
533                 space = res->curBlock->space + res->curOffset;
534                 res->curOffset += nBytes;
535                 res->spaceLeft -= nBytes;
536                 return space;
537         }
538
539         /*
540          * If the requested object is very large, give it its own block; this
541          * avoids wasting what might be most of the current block to start a new
542          * block.  (We'd have to special-case requests bigger than the block size
543          * anyway.)  The object is always given binary alignment in this case.
544          */
545         if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
546         {
547                 block = (PGresult_data *) malloc(nBytes + PGRESULT_BLOCK_OVERHEAD);
548                 if (!block)
549                         return NULL;
550                 space = block->space + PGRESULT_BLOCK_OVERHEAD;
551                 if (res->curBlock)
552                 {
553                         /*
554                          * Tuck special block below the active block, so that we don't
555                          * have to waste the free space in the active block.
556                          */
557                         block->next = res->curBlock->next;
558                         res->curBlock->next = block;
559                 }
560                 else
561                 {
562                         /* Must set up the new block as the first active block. */
563                         block->next = NULL;
564                         res->curBlock = block;
565                         res->spaceLeft = 0; /* be sure it's marked full */
566                 }
567                 return space;
568         }
569
570         /* Otherwise, start a new block. */
571         block = (PGresult_data *) malloc(PGRESULT_DATA_BLOCKSIZE);
572         if (!block)
573                 return NULL;
574         block->next = res->curBlock;
575         res->curBlock = block;
576         if (isBinary)
577         {
578                 /* object needs full alignment */
579                 res->curOffset = PGRESULT_BLOCK_OVERHEAD;
580                 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - PGRESULT_BLOCK_OVERHEAD;
581         }
582         else
583         {
584                 /* we can cram it right after the overhead pointer */
585                 res->curOffset = sizeof(PGresult_data);
586                 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - sizeof(PGresult_data);
587         }
588
589         space = block->space + res->curOffset;
590         res->curOffset += nBytes;
591         res->spaceLeft -= nBytes;
592         return space;
593 }
594
595 /*
596  * pqResultStrdup -
597  *              Like strdup, but the space is subsidiary PGresult space.
598  */
599 char *
600 pqResultStrdup(PGresult *res, const char *str)
601 {
602         char       *space = (char *) pqResultAlloc(res, strlen(str) + 1, FALSE);
603
604         if (space)
605                 strcpy(space, str);
606         return space;
607 }
608
609 /*
610  * pqSetResultError -
611  *              assign a new error message to a PGresult
612  */
613 void
614 pqSetResultError(PGresult *res, const char *msg)
615 {
616         if (!res)
617                 return;
618         if (msg && *msg)
619                 res->errMsg = pqResultStrdup(res, msg);
620         else
621                 res->errMsg = NULL;
622 }
623
624 /*
625  * pqCatenateResultError -
626  *              concatenate a new error message to the one already in a PGresult
627  */
628 void
629 pqCatenateResultError(PGresult *res, const char *msg)
630 {
631         PQExpBufferData errorBuf;
632
633         if (!res || !msg)
634                 return;
635         initPQExpBuffer(&errorBuf);
636         if (res->errMsg)
637                 appendPQExpBufferStr(&errorBuf, res->errMsg);
638         appendPQExpBufferStr(&errorBuf, msg);
639         pqSetResultError(res, errorBuf.data);
640         termPQExpBuffer(&errorBuf);
641 }
642
643 /*
644  * PQclear -
645  *        free's the memory associated with a PGresult
646  */
647 void
648 PQclear(PGresult *res)
649 {
650         PGresult_data *block;
651         int                     i;
652
653         if (!res)
654                 return;
655
656         for (i = 0; i < res->nEvents; i++)
657         {
658                 /* only send DESTROY to successfully-initialized event procs */
659                 if (res->events[i].resultInitialized)
660                 {
661                         PGEventResultDestroy evt;
662
663                         evt.result = res;
664                         (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
665                                                                            res->events[i].passThrough);
666                 }
667                 free(res->events[i].name);
668         }
669
670         if (res->events)
671                 free(res->events);
672
673         /* Free all the subsidiary blocks */
674         while ((block = res->curBlock) != NULL)
675         {
676                 res->curBlock = block->next;
677                 free(block);
678         }
679
680         /* Free the top-level tuple pointer array */
681         if (res->tuples)
682                 free(res->tuples);
683
684         /* zero out the pointer fields to catch programming errors */
685         res->attDescs = NULL;
686         res->tuples = NULL;
687         res->paramDescs = NULL;
688         res->errFields = NULL;
689         res->events = NULL;
690         res->nEvents = 0;
691         /* res->curBlock was zeroed out earlier */
692
693         /* Free the PGresult structure itself */
694         free(res);
695 }
696
697 /*
698  * Handy subroutine to deallocate any partially constructed async result.
699  *
700  * Any "next" result gets cleared too.
701  */
702 void
703 pqClearAsyncResult(PGconn *conn)
704 {
705         if (conn->result)
706                 PQclear(conn->result);
707         conn->result = NULL;
708         if (conn->next_result)
709                 PQclear(conn->next_result);
710         conn->next_result = NULL;
711 }
712
713 /*
714  * This subroutine deletes any existing async result, sets conn->result
715  * to a PGresult with status PGRES_FATAL_ERROR, and stores the current
716  * contents of conn->errorMessage into that result.  It differs from a
717  * plain call on PQmakeEmptyPGresult() in that if there is already an
718  * async result with status PGRES_FATAL_ERROR, the current error message
719  * is APPENDED to the old error message instead of replacing it.  This
720  * behavior lets us report multiple error conditions properly, if necessary.
721  * (An example where this is needed is when the backend sends an 'E' message
722  * and immediately closes the connection --- we want to report both the
723  * backend error and the connection closure error.)
724  */
725 void
726 pqSaveErrorResult(PGconn *conn)
727 {
728         /*
729          * If no old async result, just let PQmakeEmptyPGresult make one. Likewise
730          * if old result is not an error message.
731          */
732         if (conn->result == NULL ||
733                 conn->result->resultStatus != PGRES_FATAL_ERROR ||
734                 conn->result->errMsg == NULL)
735         {
736                 pqClearAsyncResult(conn);
737                 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
738         }
739         else
740         {
741                 /* Else, concatenate error message to existing async result. */
742                 pqCatenateResultError(conn->result, conn->errorMessage.data);
743         }
744 }
745
746 /*
747  * This subroutine prepares an async result object for return to the caller.
748  * If there is not already an async result object, build an error object
749  * using whatever is in conn->errorMessage.  In any case, clear the async
750  * result storage and make sure PQerrorMessage will agree with the result's
751  * error string.
752  */
753 PGresult *
754 pqPrepareAsyncResult(PGconn *conn)
755 {
756         PGresult   *res;
757
758         /*
759          * conn->result is the PGresult to return.      If it is NULL (which probably
760          * shouldn't happen) we assume there is an appropriate error message in
761          * conn->errorMessage.
762          */
763         res = conn->result;
764         if (!res)
765                 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
766         else
767         {
768                 /*
769                  * Make sure PQerrorMessage agrees with result; it could be different
770                  * if we have concatenated messages.
771                  */
772                 resetPQExpBuffer(&conn->errorMessage);
773                 appendPQExpBufferStr(&conn->errorMessage,
774                                                          PQresultErrorMessage(res));
775         }
776
777         /*
778          * Replace conn->result with next_result, if any.  In the normal case
779          * there isn't a next result and we're just dropping ownership of the
780          * current result.      In single-row mode this restores the situation to what
781          * it was before we created the current single-row result.
782          */
783         conn->result = conn->next_result;
784         conn->next_result = NULL;
785
786         return res;
787 }
788
789 /*
790  * pqInternalNotice - produce an internally-generated notice message
791  *
792  * A format string and optional arguments can be passed.  Note that we do
793  * libpq_gettext() here, so callers need not.
794  *
795  * The supplied text is taken as primary message (ie., it should not include
796  * a trailing newline, and should not be more than one line).
797  */
798 void
799 pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
800 {
801         char            msgBuf[1024];
802         va_list         args;
803         PGresult   *res;
804
805         if (hooks->noticeRec == NULL)
806                 return;                                 /* nobody home to receive notice? */
807
808         /* Format the message */
809         va_start(args, fmt);
810         vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
811         va_end(args);
812         msgBuf[sizeof(msgBuf) - 1] = '\0';      /* make real sure it's terminated */
813
814         /* Make a PGresult to pass to the notice receiver */
815         res = PQmakeEmptyPGresult(NULL, PGRES_NONFATAL_ERROR);
816         if (!res)
817                 return;
818         res->noticeHooks = *hooks;
819
820         /*
821          * Set up fields of notice.
822          */
823         pqSaveMessageField(res, PG_DIAG_MESSAGE_PRIMARY, msgBuf);
824         pqSaveMessageField(res, PG_DIAG_SEVERITY, libpq_gettext("NOTICE"));
825         /* XXX should provide a SQLSTATE too? */
826
827         /*
828          * Result text is always just the primary message + newline. If we can't
829          * allocate it, don't bother invoking the receiver.
830          */
831         res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, FALSE);
832         if (res->errMsg)
833         {
834                 sprintf(res->errMsg, "%s\n", msgBuf);
835
836                 /*
837                  * Pass to receiver, then free it.
838                  */
839                 (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
840         }
841         PQclear(res);
842 }
843
844 /*
845  * pqAddTuple
846  *        add a row pointer to the PGresult structure, growing it if necessary
847  *        Returns TRUE if OK, FALSE if not enough memory to add the row
848  */
849 static bool
850 pqAddTuple(PGresult *res, PGresAttValue *tup)
851 {
852         if (res->ntups >= res->tupArrSize)
853         {
854                 /*
855                  * Try to grow the array.
856                  *
857                  * We can use realloc because shallow copying of the structure is
858                  * okay. Note that the first time through, res->tuples is NULL. While
859                  * ANSI says that realloc() should act like malloc() in that case,
860                  * some old C libraries (like SunOS 4.1.x) coredump instead. On
861                  * failure realloc is supposed to return NULL without damaging the
862                  * existing allocation. Note that the positions beyond res->ntups are
863                  * garbage, not necessarily NULL.
864                  */
865                 int                     newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
866                 PGresAttValue **newTuples;
867
868                 if (res->tuples == NULL)
869                         newTuples = (PGresAttValue **)
870                                 malloc(newSize * sizeof(PGresAttValue *));
871                 else
872                         newTuples = (PGresAttValue **)
873                                 realloc(res->tuples, newSize * sizeof(PGresAttValue *));
874                 if (!newTuples)
875                         return FALSE;           /* malloc or realloc failed */
876                 res->tupArrSize = newSize;
877                 res->tuples = newTuples;
878         }
879         res->tuples[res->ntups] = tup;
880         res->ntups++;
881         return TRUE;
882 }
883
884 /*
885  * pqSaveMessageField - save one field of an error or notice message
886  */
887 void
888 pqSaveMessageField(PGresult *res, char code, const char *value)
889 {
890         PGMessageField *pfield;
891
892         pfield = (PGMessageField *)
893                 pqResultAlloc(res,
894                                           sizeof(PGMessageField) + strlen(value),
895                                           TRUE);
896         if (!pfield)
897                 return;                                 /* out of memory? */
898         pfield->code = code;
899         strcpy(pfield->contents, value);
900         pfield->next = res->errFields;
901         res->errFields = pfield;
902 }
903
904 /*
905  * pqSaveParameterStatus - remember parameter status sent by backend
906  */
907 void
908 pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
909 {
910         pgParameterStatus *pstatus;
911         pgParameterStatus *prev;
912
913         if (conn->Pfdebug)
914                 fprintf(conn->Pfdebug, "pqSaveParameterStatus: '%s' = '%s'\n",
915                                 name, value);
916
917         /*
918          * Forget any old information about the parameter
919          */
920         for (pstatus = conn->pstatus, prev = NULL;
921                  pstatus != NULL;
922                  prev = pstatus, pstatus = pstatus->next)
923         {
924                 if (strcmp(pstatus->name, name) == 0)
925                 {
926                         if (prev)
927                                 prev->next = pstatus->next;
928                         else
929                                 conn->pstatus = pstatus->next;
930                         free(pstatus);          /* frees name and value strings too */
931                         break;
932                 }
933         }
934
935         /*
936          * Store new info as a single malloc block
937          */
938         pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
939                                                                                    strlen(name) +strlen(value) + 2);
940         if (pstatus)
941         {
942                 char       *ptr;
943
944                 ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
945                 pstatus->name = ptr;
946                 strcpy(ptr, name);
947                 ptr += strlen(name) + 1;
948                 pstatus->value = ptr;
949                 strcpy(ptr, value);
950                 pstatus->next = conn->pstatus;
951                 conn->pstatus = pstatus;
952         }
953
954         /*
955          * Special hacks: remember client_encoding and
956          * standard_conforming_strings, and convert server version to a numeric
957          * form.  We keep the first two of these in static variables as well, so
958          * that PQescapeString and PQescapeBytea can behave somewhat sanely (at
959          * least in single-connection-using programs).
960          */
961         if (strcmp(name, "client_encoding") == 0)
962         {
963                 conn->client_encoding = pg_char_to_encoding(value);
964                 /* if we don't recognize the encoding name, fall back to SQL_ASCII */
965                 if (conn->client_encoding < 0)
966                         conn->client_encoding = PG_SQL_ASCII;
967                 static_client_encoding = conn->client_encoding;
968         }
969         else if (strcmp(name, "standard_conforming_strings") == 0)
970         {
971                 conn->std_strings = (strcmp(value, "on") == 0);
972                 static_std_strings = conn->std_strings;
973         }
974         else if (strcmp(name, "server_version") == 0)
975         {
976                 int                     cnt;
977                 int                     vmaj,
978                                         vmin,
979                                         vrev;
980
981                 cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
982
983                 if (cnt < 2)
984                         conn->sversion = 0; /* unknown */
985                 else
986                 {
987                         if (cnt == 2)
988                                 vrev = 0;
989                         conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
990                 }
991         }
992 }
993
994
995 /*
996  * pqRowProcessor
997  *        Add the received row to the current async result (conn->result).
998  *        Returns 1 if OK, 0 if error occurred.
999  *
1000  * On error, *errmsgp can be set to an error string to be returned.
1001  * If it is left NULL, the error is presumed to be "out of memory".
1002  *
1003  * In single-row mode, we create a new result holding just the current row,
1004  * stashing the previous result in conn->next_result so that it becomes
1005  * active again after pqPrepareAsyncResult().  This allows the result metadata
1006  * (column descriptions) to be carried forward to each result row.
1007  */
1008 int
1009 pqRowProcessor(PGconn *conn, const char **errmsgp)
1010 {
1011         PGresult   *res = conn->result;
1012         int                     nfields = res->numAttributes;
1013         const PGdataValue *columns = conn->rowBuf;
1014         PGresAttValue *tup;
1015         int                     i;
1016
1017         /*
1018          * In single-row mode, make a new PGresult that will hold just this one
1019          * row; the original conn->result is left unchanged so that it can be used
1020          * again as the template for future rows.
1021          */
1022         if (conn->singleRowMode)
1023         {
1024                 /* Copy everything that should be in the result at this point */
1025                 res = PQcopyResult(res,
1026                                                    PG_COPYRES_ATTRS | PG_COPYRES_EVENTS |
1027                                                    PG_COPYRES_NOTICEHOOKS);
1028                 if (!res)
1029                         return 0;
1030         }
1031
1032         /*
1033          * Basically we just allocate space in the PGresult for each field and
1034          * copy the data over.
1035          *
1036          * Note: on malloc failure, we return 0 leaving *errmsgp still NULL, which
1037          * caller will take to mean "out of memory".  This is preferable to trying
1038          * to set up such a message here, because evidently there's not enough
1039          * memory for gettext() to do anything.
1040          */
1041         tup = (PGresAttValue *)
1042                 pqResultAlloc(res, nfields * sizeof(PGresAttValue), TRUE);
1043         if (tup == NULL)
1044                 goto fail;
1045
1046         for (i = 0; i < nfields; i++)
1047         {
1048                 int                     clen = columns[i].len;
1049
1050                 if (clen < 0)
1051                 {
1052                         /* null field */
1053                         tup[i].len = NULL_LEN;
1054                         tup[i].value = res->null_field;
1055                 }
1056                 else
1057                 {
1058                         bool            isbinary = (res->attDescs[i].format != 0);
1059                         char       *val;
1060
1061                         val = (char *) pqResultAlloc(res, clen + 1, isbinary);
1062                         if (val == NULL)
1063                                 goto fail;
1064
1065                         /* copy and zero-terminate the data (even if it's binary) */
1066                         memcpy(val, columns[i].value, clen);
1067                         val[clen] = '\0';
1068
1069                         tup[i].len = clen;
1070                         tup[i].value = val;
1071                 }
1072         }
1073
1074         /* And add the tuple to the PGresult's tuple array */
1075         if (!pqAddTuple(res, tup))
1076                 goto fail;
1077
1078         /*
1079          * Success.  In single-row mode, make the result available to the client
1080          * immediately.
1081          */
1082         if (conn->singleRowMode)
1083         {
1084                 /* Change result status to special single-row value */
1085                 res->resultStatus = PGRES_SINGLE_TUPLE;
1086                 /* Stash old result for re-use later */
1087                 conn->next_result = conn->result;
1088                 conn->result = res;
1089                 /* And mark the result ready to return */
1090                 conn->asyncStatus = PGASYNC_READY;
1091         }
1092
1093         return 1;
1094
1095 fail:
1096         /* release locally allocated PGresult, if we made one */
1097         if (res != conn->result)
1098                 PQclear(res);
1099         return 0;
1100 }
1101
1102
1103 /*
1104  * PQsendQuery
1105  *       Submit a query, but don't wait for it to finish
1106  *
1107  * Returns: 1 if successfully submitted
1108  *                      0 if error (conn->errorMessage is set)
1109  */
1110 int
1111 PQsendQuery(PGconn *conn, const char *query)
1112 {
1113         if (!PQsendQueryStart(conn))
1114                 return 0;
1115
1116         /* check the argument */
1117         if (!query)
1118         {
1119                 printfPQExpBuffer(&conn->errorMessage,
1120                                                 libpq_gettext("command string is a null pointer\n"));
1121                 return 0;
1122         }
1123
1124         /* construct the outgoing Query message */
1125         if (pqPutMsgStart('Q', false, conn) < 0 ||
1126                 pqPuts(query, conn) < 0 ||
1127                 pqPutMsgEnd(conn) < 0)
1128         {
1129                 pqHandleSendFailure(conn);
1130                 return 0;
1131         }
1132
1133         /* remember we are using simple query protocol */
1134         conn->queryclass = PGQUERY_SIMPLE;
1135
1136         /* and remember the query text too, if possible */
1137         /* if insufficient memory, last_query just winds up NULL */
1138         if (conn->last_query)
1139                 free(conn->last_query);
1140         conn->last_query = strdup(query);
1141
1142         /*
1143          * Give the data a push.  In nonblock mode, don't complain if we're unable
1144          * to send it all; PQgetResult() will do any additional flushing needed.
1145          */
1146         if (pqFlush(conn) < 0)
1147         {
1148                 pqHandleSendFailure(conn);
1149                 return 0;
1150         }
1151
1152         /* OK, it's launched! */
1153         conn->asyncStatus = PGASYNC_BUSY;
1154         return 1;
1155 }
1156
1157 /*
1158  * PQsendQueryParams
1159  *              Like PQsendQuery, but use protocol 3.0 so we can pass parameters
1160  */
1161 int
1162 PQsendQueryParams(PGconn *conn,
1163                                   const char *command,
1164                                   int nParams,
1165                                   const Oid *paramTypes,
1166                                   const char *const * paramValues,
1167                                   const int *paramLengths,
1168                                   const int *paramFormats,
1169                                   int resultFormat)
1170 {
1171         if (!PQsendQueryStart(conn))
1172                 return 0;
1173
1174         /* check the arguments */
1175         if (!command)
1176         {
1177                 printfPQExpBuffer(&conn->errorMessage,
1178                                                 libpq_gettext("command string is a null pointer\n"));
1179                 return 0;
1180         }
1181         if (nParams < 0 || nParams > 65535)
1182         {
1183                 printfPQExpBuffer(&conn->errorMessage,
1184                 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1185                 return 0;
1186         }
1187
1188         return PQsendQueryGuts(conn,
1189                                                    command,
1190                                                    "",  /* use unnamed statement */
1191                                                    nParams,
1192                                                    paramTypes,
1193                                                    paramValues,
1194                                                    paramLengths,
1195                                                    paramFormats,
1196                                                    resultFormat);
1197 }
1198
1199 /*
1200  * PQsendPrepare
1201  *       Submit a Parse message, but don't wait for it to finish
1202  *
1203  * Returns: 1 if successfully submitted
1204  *                      0 if error (conn->errorMessage is set)
1205  */
1206 int
1207 PQsendPrepare(PGconn *conn,
1208                           const char *stmtName, const char *query,
1209                           int nParams, const Oid *paramTypes)
1210 {
1211         if (!PQsendQueryStart(conn))
1212                 return 0;
1213
1214         /* check the arguments */
1215         if (!stmtName)
1216         {
1217                 printfPQExpBuffer(&conn->errorMessage,
1218                                                 libpq_gettext("statement name is a null pointer\n"));
1219                 return 0;
1220         }
1221         if (!query)
1222         {
1223                 printfPQExpBuffer(&conn->errorMessage,
1224                                                 libpq_gettext("command string is a null pointer\n"));
1225                 return 0;
1226         }
1227         if (nParams < 0 || nParams > 65535)
1228         {
1229                 printfPQExpBuffer(&conn->errorMessage,
1230                 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1231                 return 0;
1232         }
1233
1234         /* This isn't gonna work on a 2.0 server */
1235         if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1236         {
1237                 printfPQExpBuffer(&conn->errorMessage,
1238                  libpq_gettext("function requires at least protocol version 3.0\n"));
1239                 return 0;
1240         }
1241
1242         /* construct the Parse message */
1243         if (pqPutMsgStart('P', false, conn) < 0 ||
1244                 pqPuts(stmtName, conn) < 0 ||
1245                 pqPuts(query, conn) < 0)
1246                 goto sendFailed;
1247
1248         if (nParams > 0 && paramTypes)
1249         {
1250                 int                     i;
1251
1252                 if (pqPutInt(nParams, 2, conn) < 0)
1253                         goto sendFailed;
1254                 for (i = 0; i < nParams; i++)
1255                 {
1256                         if (pqPutInt(paramTypes[i], 4, conn) < 0)
1257                                 goto sendFailed;
1258                 }
1259         }
1260         else
1261         {
1262                 if (pqPutInt(0, 2, conn) < 0)
1263                         goto sendFailed;
1264         }
1265         if (pqPutMsgEnd(conn) < 0)
1266                 goto sendFailed;
1267
1268         /* construct the Sync message */
1269         if (pqPutMsgStart('S', false, conn) < 0 ||
1270                 pqPutMsgEnd(conn) < 0)
1271                 goto sendFailed;
1272
1273         /* remember we are doing just a Parse */
1274         conn->queryclass = PGQUERY_PREPARE;
1275
1276         /* and remember the query text too, if possible */
1277         /* if insufficient memory, last_query just winds up NULL */
1278         if (conn->last_query)
1279                 free(conn->last_query);
1280         conn->last_query = strdup(query);
1281
1282         /*
1283          * Give the data a push.  In nonblock mode, don't complain if we're unable
1284          * to send it all; PQgetResult() will do any additional flushing needed.
1285          */
1286         if (pqFlush(conn) < 0)
1287                 goto sendFailed;
1288
1289         /* OK, it's launched! */
1290         conn->asyncStatus = PGASYNC_BUSY;
1291         return 1;
1292
1293 sendFailed:
1294         pqHandleSendFailure(conn);
1295         return 0;
1296 }
1297
1298 /*
1299  * PQsendQueryPrepared
1300  *              Like PQsendQuery, but execute a previously prepared statement,
1301  *              using protocol 3.0 so we can pass parameters
1302  */
1303 int
1304 PQsendQueryPrepared(PGconn *conn,
1305                                         const char *stmtName,
1306                                         int nParams,
1307                                         const char *const * paramValues,
1308                                         const int *paramLengths,
1309                                         const int *paramFormats,
1310                                         int resultFormat)
1311 {
1312         if (!PQsendQueryStart(conn))
1313                 return 0;
1314
1315         /* check the arguments */
1316         if (!stmtName)
1317         {
1318                 printfPQExpBuffer(&conn->errorMessage,
1319                                                 libpq_gettext("statement name is a null pointer\n"));
1320                 return 0;
1321         }
1322         if (nParams < 0 || nParams > 65535)
1323         {
1324                 printfPQExpBuffer(&conn->errorMessage,
1325                 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1326                 return 0;
1327         }
1328
1329         return PQsendQueryGuts(conn,
1330                                                    NULL,        /* no command to parse */
1331                                                    stmtName,
1332                                                    nParams,
1333                                                    NULL,        /* no param types */
1334                                                    paramValues,
1335                                                    paramLengths,
1336                                                    paramFormats,
1337                                                    resultFormat);
1338 }
1339
1340 /*
1341  * Common startup code for PQsendQuery and sibling routines
1342  */
1343 static bool
1344 PQsendQueryStart(PGconn *conn)
1345 {
1346         if (!conn)
1347                 return false;
1348
1349         /* clear the error string */
1350         resetPQExpBuffer(&conn->errorMessage);
1351
1352         /* Don't try to send if we know there's no live connection. */
1353         if (conn->status != CONNECTION_OK)
1354         {
1355                 printfPQExpBuffer(&conn->errorMessage,
1356                                                   libpq_gettext("no connection to the server\n"));
1357                 return false;
1358         }
1359         /* Can't send while already busy, either. */
1360         if (conn->asyncStatus != PGASYNC_IDLE)
1361         {
1362                 printfPQExpBuffer(&conn->errorMessage,
1363                                   libpq_gettext("another command is already in progress\n"));
1364                 return false;
1365         }
1366
1367         /* initialize async result-accumulation state */
1368         conn->result = NULL;
1369         conn->next_result = NULL;
1370
1371         /* reset single-row processing mode */
1372         conn->singleRowMode = false;
1373
1374         /* ready to send command message */
1375         return true;
1376 }
1377
1378 /*
1379  * PQsendQueryGuts
1380  *              Common code for protocol-3.0 query sending
1381  *              PQsendQueryStart should be done already
1382  *
1383  * command may be NULL to indicate we use an already-prepared statement
1384  */
1385 static int
1386 PQsendQueryGuts(PGconn *conn,
1387                                 const char *command,
1388                                 const char *stmtName,
1389                                 int nParams,
1390                                 const Oid *paramTypes,
1391                                 const char *const * paramValues,
1392                                 const int *paramLengths,
1393                                 const int *paramFormats,
1394                                 int resultFormat)
1395 {
1396         int                     i;
1397
1398         /* This isn't gonna work on a 2.0 server */
1399         if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1400         {
1401                 printfPQExpBuffer(&conn->errorMessage,
1402                  libpq_gettext("function requires at least protocol version 3.0\n"));
1403                 return 0;
1404         }
1405
1406         /*
1407          * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync,
1408          * using specified statement name and the unnamed portal.
1409          */
1410
1411         if (command)
1412         {
1413                 /* construct the Parse message */
1414                 if (pqPutMsgStart('P', false, conn) < 0 ||
1415                         pqPuts(stmtName, conn) < 0 ||
1416                         pqPuts(command, conn) < 0)
1417                         goto sendFailed;
1418                 if (nParams > 0 && paramTypes)
1419                 {
1420                         if (pqPutInt(nParams, 2, conn) < 0)
1421                                 goto sendFailed;
1422                         for (i = 0; i < nParams; i++)
1423                         {
1424                                 if (pqPutInt(paramTypes[i], 4, conn) < 0)
1425                                         goto sendFailed;
1426                         }
1427                 }
1428                 else
1429                 {
1430                         if (pqPutInt(0, 2, conn) < 0)
1431                                 goto sendFailed;
1432                 }
1433                 if (pqPutMsgEnd(conn) < 0)
1434                         goto sendFailed;
1435         }
1436
1437         /* Construct the Bind message */
1438         if (pqPutMsgStart('B', false, conn) < 0 ||
1439                 pqPuts("", conn) < 0 ||
1440                 pqPuts(stmtName, conn) < 0)
1441                 goto sendFailed;
1442
1443         /* Send parameter formats */
1444         if (nParams > 0 && paramFormats)
1445         {
1446                 if (pqPutInt(nParams, 2, conn) < 0)
1447                         goto sendFailed;
1448                 for (i = 0; i < nParams; i++)
1449                 {
1450                         if (pqPutInt(paramFormats[i], 2, conn) < 0)
1451                                 goto sendFailed;
1452                 }
1453         }
1454         else
1455         {
1456                 if (pqPutInt(0, 2, conn) < 0)
1457                         goto sendFailed;
1458         }
1459
1460         if (pqPutInt(nParams, 2, conn) < 0)
1461                 goto sendFailed;
1462
1463         /* Send parameters */
1464         for (i = 0; i < nParams; i++)
1465         {
1466                 if (paramValues && paramValues[i])
1467                 {
1468                         int                     nbytes;
1469
1470                         if (paramFormats && paramFormats[i] != 0)
1471                         {
1472                                 /* binary parameter */
1473                                 if (paramLengths)
1474                                         nbytes = paramLengths[i];
1475                                 else
1476                                 {
1477                                         printfPQExpBuffer(&conn->errorMessage,
1478                                                                           libpq_gettext("length must be given for binary parameter\n"));
1479                                         goto sendFailed;
1480                                 }
1481                         }
1482                         else
1483                         {
1484                                 /* text parameter, do not use paramLengths */
1485                                 nbytes = strlen(paramValues[i]);
1486                         }
1487                         if (pqPutInt(nbytes, 4, conn) < 0 ||
1488                                 pqPutnchar(paramValues[i], nbytes, conn) < 0)
1489                                 goto sendFailed;
1490                 }
1491                 else
1492                 {
1493                         /* take the param as NULL */
1494                         if (pqPutInt(-1, 4, conn) < 0)
1495                                 goto sendFailed;
1496                 }
1497         }
1498         if (pqPutInt(1, 2, conn) < 0 ||
1499                 pqPutInt(resultFormat, 2, conn))
1500                 goto sendFailed;
1501         if (pqPutMsgEnd(conn) < 0)
1502                 goto sendFailed;
1503
1504         /* construct the Describe Portal message */
1505         if (pqPutMsgStart('D', false, conn) < 0 ||
1506                 pqPutc('P', conn) < 0 ||
1507                 pqPuts("", conn) < 0 ||
1508                 pqPutMsgEnd(conn) < 0)
1509                 goto sendFailed;
1510
1511         /* construct the Execute message */
1512         if (pqPutMsgStart('E', false, conn) < 0 ||
1513                 pqPuts("", conn) < 0 ||
1514                 pqPutInt(0, 4, conn) < 0 ||
1515                 pqPutMsgEnd(conn) < 0)
1516                 goto sendFailed;
1517
1518         /* construct the Sync message */
1519         if (pqPutMsgStart('S', false, conn) < 0 ||
1520                 pqPutMsgEnd(conn) < 0)
1521                 goto sendFailed;
1522
1523         /* remember we are using extended query protocol */
1524         conn->queryclass = PGQUERY_EXTENDED;
1525
1526         /* and remember the query text too, if possible */
1527         /* if insufficient memory, last_query just winds up NULL */
1528         if (conn->last_query)
1529                 free(conn->last_query);
1530         if (command)
1531                 conn->last_query = strdup(command);
1532         else
1533                 conn->last_query = NULL;
1534
1535         /*
1536          * Give the data a push.  In nonblock mode, don't complain if we're unable
1537          * to send it all; PQgetResult() will do any additional flushing needed.
1538          */
1539         if (pqFlush(conn) < 0)
1540                 goto sendFailed;
1541
1542         /* OK, it's launched! */
1543         conn->asyncStatus = PGASYNC_BUSY;
1544         return 1;
1545
1546 sendFailed:
1547         pqHandleSendFailure(conn);
1548         return 0;
1549 }
1550
1551 /*
1552  * pqHandleSendFailure: try to clean up after failure to send command.
1553  *
1554  * Primarily, what we want to accomplish here is to process an async
1555  * NOTICE message that the backend might have sent just before it died.
1556  *
1557  * NOTE: this routine should only be called in PGASYNC_IDLE state.
1558  */
1559 void
1560 pqHandleSendFailure(PGconn *conn)
1561 {
1562         /*
1563          * Accept any available input data, ignoring errors.  Note that if
1564          * pqReadData decides the backend has closed the channel, it will close
1565          * our side of the socket --- that's just what we want here.
1566          */
1567         while (pqReadData(conn) > 0)
1568                  /* loop until no more data readable */ ;
1569
1570         /*
1571          * Parse any available input messages.  Since we are in PGASYNC_IDLE
1572          * state, only NOTICE and NOTIFY messages will be eaten.
1573          */
1574         parseInput(conn);
1575 }
1576
1577 /*
1578  * Select row-by-row processing mode
1579  */
1580 int
1581 PQsetSingleRowMode(PGconn *conn)
1582 {
1583         /*
1584          * Only allow setting the flag when we have launched a query and not yet
1585          * received any results.
1586          */
1587         if (!conn)
1588                 return 0;
1589         if (conn->asyncStatus != PGASYNC_BUSY)
1590                 return 0;
1591         if (conn->queryclass != PGQUERY_SIMPLE &&
1592                 conn->queryclass != PGQUERY_EXTENDED)
1593                 return 0;
1594         if (conn->result)
1595                 return 0;
1596
1597         /* OK, set flag */
1598         conn->singleRowMode = true;
1599         return 1;
1600 }
1601
1602 /*
1603  * Consume any available input from the backend
1604  * 0 return: some kind of trouble
1605  * 1 return: no problem
1606  */
1607 int
1608 PQconsumeInput(PGconn *conn)
1609 {
1610         if (!conn)
1611                 return 0;
1612
1613         /*
1614          * for non-blocking connections try to flush the send-queue, otherwise we
1615          * may never get a response for something that may not have already been
1616          * sent because it's in our write buffer!
1617          */
1618         if (pqIsnonblocking(conn))
1619         {
1620                 if (pqFlush(conn) < 0)
1621                         return 0;
1622         }
1623
1624         /*
1625          * Load more data, if available. We do this no matter what state we are
1626          * in, since we are probably getting called because the application wants
1627          * to get rid of a read-select condition. Note that we will NOT block
1628          * waiting for more input.
1629          */
1630         if (pqReadData(conn) < 0)
1631                 return 0;
1632
1633         /* Parsing of the data waits till later. */
1634         return 1;
1635 }
1636
1637
1638 /*
1639  * parseInput: if appropriate, parse input data from backend
1640  * until input is exhausted or a stopping state is reached.
1641  * Note that this function will NOT attempt to read more data from the backend.
1642  */
1643 static void
1644 parseInput(PGconn *conn)
1645 {
1646         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1647                 pqParseInput3(conn);
1648         else
1649                 pqParseInput2(conn);
1650 }
1651
1652 /*
1653  * PQisBusy
1654  *       Return TRUE if PQgetResult would block waiting for input.
1655  */
1656
1657 int
1658 PQisBusy(PGconn *conn)
1659 {
1660         if (!conn)
1661                 return FALSE;
1662
1663         /* Parse any available data, if our state permits. */
1664         parseInput(conn);
1665
1666         /* PQgetResult will return immediately in all states except BUSY. */
1667         return conn->asyncStatus == PGASYNC_BUSY;
1668 }
1669
1670
1671 /*
1672  * PQgetResult
1673  *        Get the next PGresult produced by a query.  Returns NULL if no
1674  *        query work remains or an error has occurred (e.g. out of
1675  *        memory).
1676  */
1677
1678 PGresult *
1679 PQgetResult(PGconn *conn)
1680 {
1681         PGresult   *res;
1682
1683         if (!conn)
1684                 return NULL;
1685
1686         /* Parse any available data, if our state permits. */
1687         parseInput(conn);
1688
1689         /* If not ready to return something, block until we are. */
1690         while (conn->asyncStatus == PGASYNC_BUSY)
1691         {
1692                 int                     flushResult;
1693
1694                 /*
1695                  * If data remains unsent, send it.  Else we might be waiting for the
1696                  * result of a command the backend hasn't even got yet.
1697                  */
1698                 while ((flushResult = pqFlush(conn)) > 0)
1699                 {
1700                         if (pqWait(FALSE, TRUE, conn))
1701                         {
1702                                 flushResult = -1;
1703                                 break;
1704                         }
1705                 }
1706
1707                 /* Wait for some more data, and load it. */
1708                 if (flushResult ||
1709                         pqWait(TRUE, FALSE, conn) ||
1710                         pqReadData(conn) < 0)
1711                 {
1712                         /*
1713                          * conn->errorMessage has been set by pqWait or pqReadData. We
1714                          * want to append it to any already-received error message.
1715                          */
1716                         pqSaveErrorResult(conn);
1717                         conn->asyncStatus = PGASYNC_IDLE;
1718                         return pqPrepareAsyncResult(conn);
1719                 }
1720
1721                 /* Parse it. */
1722                 parseInput(conn);
1723         }
1724
1725         /* Return the appropriate thing. */
1726         switch (conn->asyncStatus)
1727         {
1728                 case PGASYNC_IDLE:
1729                         res = NULL;                     /* query is complete */
1730                         break;
1731                 case PGASYNC_READY:
1732                         res = pqPrepareAsyncResult(conn);
1733                         /* Set the state back to BUSY, allowing parsing to proceed. */
1734                         conn->asyncStatus = PGASYNC_BUSY;
1735                         break;
1736                 case PGASYNC_COPY_IN:
1737                         if (conn->result && conn->result->resultStatus == PGRES_COPY_IN)
1738                                 res = pqPrepareAsyncResult(conn);
1739                         else
1740                                 res = PQmakeEmptyPGresult(conn, PGRES_COPY_IN);
1741                         break;
1742                 case PGASYNC_COPY_OUT:
1743                         if (conn->result && conn->result->resultStatus == PGRES_COPY_OUT)
1744                                 res = pqPrepareAsyncResult(conn);
1745                         else
1746                                 res = PQmakeEmptyPGresult(conn, PGRES_COPY_OUT);
1747                         break;
1748                 case PGASYNC_COPY_BOTH:
1749                         if (conn->result && conn->result->resultStatus == PGRES_COPY_BOTH)
1750                                 res = pqPrepareAsyncResult(conn);
1751                         else
1752                                 res = PQmakeEmptyPGresult(conn, PGRES_COPY_BOTH);
1753                         break;
1754                 default:
1755                         printfPQExpBuffer(&conn->errorMessage,
1756                                                           libpq_gettext("unexpected asyncStatus: %d\n"),
1757                                                           (int) conn->asyncStatus);
1758                         res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1759                         break;
1760         }
1761
1762         if (res)
1763         {
1764                 int                     i;
1765
1766                 for (i = 0; i < res->nEvents; i++)
1767                 {
1768                         PGEventResultCreate evt;
1769
1770                         evt.conn = conn;
1771                         evt.result = res;
1772                         if (!res->events[i].proc(PGEVT_RESULTCREATE, &evt,
1773                                                                          res->events[i].passThrough))
1774                         {
1775                                 printfPQExpBuffer(&conn->errorMessage,
1776                                                                   libpq_gettext("PGEventProc \"%s\" failed during PGEVT_RESULTCREATE event\n"),
1777                                                                   res->events[i].name);
1778                                 pqSetResultError(res, conn->errorMessage.data);
1779                                 res->resultStatus = PGRES_FATAL_ERROR;
1780                                 break;
1781                         }
1782                         res->events[i].resultInitialized = TRUE;
1783                 }
1784         }
1785
1786         return res;
1787 }
1788
1789
1790 /*
1791  * PQexec
1792  *        send a query to the backend and package up the result in a PGresult
1793  *
1794  * If the query was not even sent, return NULL; conn->errorMessage is set to
1795  * a relevant message.
1796  * If the query was sent, a new PGresult is returned (which could indicate
1797  * either success or failure).
1798  * The user is responsible for freeing the PGresult via PQclear()
1799  * when done with it.
1800  */
1801 PGresult *
1802 PQexec(PGconn *conn, const char *query)
1803 {
1804         if (!PQexecStart(conn))
1805                 return NULL;
1806         if (!PQsendQuery(conn, query))
1807                 return NULL;
1808         return PQexecFinish(conn);
1809 }
1810
1811 /*
1812  * PQexecParams
1813  *              Like PQexec, but use protocol 3.0 so we can pass parameters
1814  */
1815 PGresult *
1816 PQexecParams(PGconn *conn,
1817                          const char *command,
1818                          int nParams,
1819                          const Oid *paramTypes,
1820                          const char *const * paramValues,
1821                          const int *paramLengths,
1822                          const int *paramFormats,
1823                          int resultFormat)
1824 {
1825         if (!PQexecStart(conn))
1826                 return NULL;
1827         if (!PQsendQueryParams(conn, command,
1828                                                    nParams, paramTypes, paramValues, paramLengths,
1829                                                    paramFormats, resultFormat))
1830                 return NULL;
1831         return PQexecFinish(conn);
1832 }
1833
1834 /*
1835  * PQprepare
1836  *        Creates a prepared statement by issuing a v3.0 parse message.
1837  *
1838  * If the query was not even sent, return NULL; conn->errorMessage is set to
1839  * a relevant message.
1840  * If the query was sent, a new PGresult is returned (which could indicate
1841  * either success or failure).
1842  * The user is responsible for freeing the PGresult via PQclear()
1843  * when done with it.
1844  */
1845 PGresult *
1846 PQprepare(PGconn *conn,
1847                   const char *stmtName, const char *query,
1848                   int nParams, const Oid *paramTypes)
1849 {
1850         if (!PQexecStart(conn))
1851                 return NULL;
1852         if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
1853                 return NULL;
1854         return PQexecFinish(conn);
1855 }
1856
1857 /*
1858  * PQexecPrepared
1859  *              Like PQexec, but execute a previously prepared statement,
1860  *              using protocol 3.0 so we can pass parameters
1861  */
1862 PGresult *
1863 PQexecPrepared(PGconn *conn,
1864                            const char *stmtName,
1865                            int nParams,
1866                            const char *const * paramValues,
1867                            const int *paramLengths,
1868                            const int *paramFormats,
1869                            int resultFormat)
1870 {
1871         if (!PQexecStart(conn))
1872                 return NULL;
1873         if (!PQsendQueryPrepared(conn, stmtName,
1874                                                          nParams, paramValues, paramLengths,
1875                                                          paramFormats, resultFormat))
1876                 return NULL;
1877         return PQexecFinish(conn);
1878 }
1879
1880 /*
1881  * Common code for PQexec and sibling routines: prepare to send command
1882  */
1883 static bool
1884 PQexecStart(PGconn *conn)
1885 {
1886         PGresult   *result;
1887
1888         if (!conn)
1889                 return false;
1890
1891         /*
1892          * Silently discard any prior query result that application didn't eat.
1893          * This is probably poor design, but it's here for backward compatibility.
1894          */
1895         while ((result = PQgetResult(conn)) != NULL)
1896         {
1897                 ExecStatusType resultStatus = result->resultStatus;
1898
1899                 PQclear(result);                /* only need its status */
1900                 if (resultStatus == PGRES_COPY_IN)
1901                 {
1902                         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1903                         {
1904                                 /* In protocol 3, we can get out of a COPY IN state */
1905                                 if (PQputCopyEnd(conn,
1906                                                  libpq_gettext("COPY terminated by new PQexec")) < 0)
1907                                         return false;
1908                                 /* keep waiting to swallow the copy's failure message */
1909                         }
1910                         else
1911                         {
1912                                 /* In older protocols we have to punt */
1913                                 printfPQExpBuffer(&conn->errorMessage,
1914                                   libpq_gettext("COPY IN state must be terminated first\n"));
1915                                 return false;
1916                         }
1917                 }
1918                 else if (resultStatus == PGRES_COPY_OUT)
1919                 {
1920                         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1921                         {
1922                                 /*
1923                                  * In protocol 3, we can get out of a COPY OUT state: we just
1924                                  * switch back to BUSY and allow the remaining COPY data to be
1925                                  * dropped on the floor.
1926                                  */
1927                                 conn->asyncStatus = PGASYNC_BUSY;
1928                                 /* keep waiting to swallow the copy's completion message */
1929                         }
1930                         else
1931                         {
1932                                 /* In older protocols we have to punt */
1933                                 printfPQExpBuffer(&conn->errorMessage,
1934                                  libpq_gettext("COPY OUT state must be terminated first\n"));
1935                                 return false;
1936                         }
1937                 }
1938                 else if (resultStatus == PGRES_COPY_BOTH)
1939                 {
1940                         /* We don't allow PQexec during COPY BOTH */
1941                         printfPQExpBuffer(&conn->errorMessage,
1942                                          libpq_gettext("PQexec not allowed during COPY BOTH\n"));
1943                         return false;
1944                 }
1945                 /* check for loss of connection, too */
1946                 if (conn->status == CONNECTION_BAD)
1947                         return false;
1948         }
1949
1950         /* OK to send a command */
1951         return true;
1952 }
1953
1954 /*
1955  * Common code for PQexec and sibling routines: wait for command result
1956  */
1957 static PGresult *
1958 PQexecFinish(PGconn *conn)
1959 {
1960         PGresult   *result;
1961         PGresult   *lastResult;
1962
1963         /*
1964          * For backwards compatibility, return the last result if there are more
1965          * than one --- but merge error messages if we get more than one error
1966          * result.
1967          *
1968          * We have to stop if we see copy in/out/both, however. We will resume
1969          * parsing after application performs the data transfer.
1970          *
1971          * Also stop if the connection is lost (else we'll loop infinitely).
1972          */
1973         lastResult = NULL;
1974         while ((result = PQgetResult(conn)) != NULL)
1975         {
1976                 if (lastResult)
1977                 {
1978                         if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
1979                                 result->resultStatus == PGRES_FATAL_ERROR)
1980                         {
1981                                 pqCatenateResultError(lastResult, result->errMsg);
1982                                 PQclear(result);
1983                                 result = lastResult;
1984
1985                                 /*
1986                                  * Make sure PQerrorMessage agrees with concatenated result
1987                                  */
1988                                 resetPQExpBuffer(&conn->errorMessage);
1989                                 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
1990                         }
1991                         else
1992                                 PQclear(lastResult);
1993                 }
1994                 lastResult = result;
1995                 if (result->resultStatus == PGRES_COPY_IN ||
1996                         result->resultStatus == PGRES_COPY_OUT ||
1997                         result->resultStatus == PGRES_COPY_BOTH ||
1998                         conn->status == CONNECTION_BAD)
1999                         break;
2000         }
2001
2002         return lastResult;
2003 }
2004
2005 /*
2006  * PQdescribePrepared
2007  *        Obtain information about a previously prepared statement
2008  *
2009  * If the query was not even sent, return NULL; conn->errorMessage is set to
2010  * a relevant message.
2011  * If the query was sent, a new PGresult is returned (which could indicate
2012  * either success or failure).  On success, the PGresult contains status
2013  * PGRES_COMMAND_OK, and its parameter and column-heading fields describe
2014  * the statement's inputs and outputs respectively.
2015  * The user is responsible for freeing the PGresult via PQclear()
2016  * when done with it.
2017  */
2018 PGresult *
2019 PQdescribePrepared(PGconn *conn, const char *stmt)
2020 {
2021         if (!PQexecStart(conn))
2022                 return NULL;
2023         if (!PQsendDescribe(conn, 'S', stmt))
2024                 return NULL;
2025         return PQexecFinish(conn);
2026 }
2027
2028 /*
2029  * PQdescribePortal
2030  *        Obtain information about a previously created portal
2031  *
2032  * This is much like PQdescribePrepared, except that no parameter info is
2033  * returned.  Note that at the moment, libpq doesn't really expose portals
2034  * to the client; but this can be used with a portal created by a SQL
2035  * DECLARE CURSOR command.
2036  */
2037 PGresult *
2038 PQdescribePortal(PGconn *conn, const char *portal)
2039 {
2040         if (!PQexecStart(conn))
2041                 return NULL;
2042         if (!PQsendDescribe(conn, 'P', portal))
2043                 return NULL;
2044         return PQexecFinish(conn);
2045 }
2046
2047 /*
2048  * PQsendDescribePrepared
2049  *       Submit a Describe Statement command, but don't wait for it to finish
2050  *
2051  * Returns: 1 if successfully submitted
2052  *                      0 if error (conn->errorMessage is set)
2053  */
2054 int
2055 PQsendDescribePrepared(PGconn *conn, const char *stmt)
2056 {
2057         return PQsendDescribe(conn, 'S', stmt);
2058 }
2059
2060 /*
2061  * PQsendDescribePortal
2062  *       Submit a Describe Portal command, but don't wait for it to finish
2063  *
2064  * Returns: 1 if successfully submitted
2065  *                      0 if error (conn->errorMessage is set)
2066  */
2067 int
2068 PQsendDescribePortal(PGconn *conn, const char *portal)
2069 {
2070         return PQsendDescribe(conn, 'P', portal);
2071 }
2072
2073 /*
2074  * PQsendDescribe
2075  *       Common code to send a Describe command
2076  *
2077  * Available options for desc_type are
2078  *       'S' to describe a prepared statement; or
2079  *       'P' to describe a portal.
2080  * Returns 1 on success and 0 on failure.
2081  */
2082 static int
2083 PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
2084 {
2085         /* Treat null desc_target as empty string */
2086         if (!desc_target)
2087                 desc_target = "";
2088
2089         if (!PQsendQueryStart(conn))
2090                 return 0;
2091
2092         /* This isn't gonna work on a 2.0 server */
2093         if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2094         {
2095                 printfPQExpBuffer(&conn->errorMessage,
2096                  libpq_gettext("function requires at least protocol version 3.0\n"));
2097                 return 0;
2098         }
2099
2100         /* construct the Describe message */
2101         if (pqPutMsgStart('D', false, conn) < 0 ||
2102                 pqPutc(desc_type, conn) < 0 ||
2103                 pqPuts(desc_target, conn) < 0 ||
2104                 pqPutMsgEnd(conn) < 0)
2105                 goto sendFailed;
2106
2107         /* construct the Sync message */
2108         if (pqPutMsgStart('S', false, conn) < 0 ||
2109                 pqPutMsgEnd(conn) < 0)
2110                 goto sendFailed;
2111
2112         /* remember we are doing a Describe */
2113         conn->queryclass = PGQUERY_DESCRIBE;
2114
2115         /* reset last-query string (not relevant now) */
2116         if (conn->last_query)
2117         {
2118                 free(conn->last_query);
2119                 conn->last_query = NULL;
2120         }
2121
2122         /*
2123          * Give the data a push.  In nonblock mode, don't complain if we're unable
2124          * to send it all; PQgetResult() will do any additional flushing needed.
2125          */
2126         if (pqFlush(conn) < 0)
2127                 goto sendFailed;
2128
2129         /* OK, it's launched! */
2130         conn->asyncStatus = PGASYNC_BUSY;
2131         return 1;
2132
2133 sendFailed:
2134         pqHandleSendFailure(conn);
2135         return 0;
2136 }
2137
2138 /*
2139  * PQnotifies
2140  *        returns a PGnotify* structure of the latest async notification
2141  * that has not yet been handled
2142  *
2143  * returns NULL, if there is currently
2144  * no unhandled async notification from the backend
2145  *
2146  * the CALLER is responsible for FREE'ing the structure returned
2147  */
2148 PGnotify *
2149 PQnotifies(PGconn *conn)
2150 {
2151         PGnotify   *event;
2152
2153         if (!conn)
2154                 return NULL;
2155
2156         /* Parse any available data to see if we can extract NOTIFY messages. */
2157         parseInput(conn);
2158
2159         event = conn->notifyHead;
2160         if (event)
2161         {
2162                 conn->notifyHead = event->next;
2163                 if (!conn->notifyHead)
2164                         conn->notifyTail = NULL;
2165                 event->next = NULL;             /* don't let app see the internal state */
2166         }
2167         return event;
2168 }
2169
2170 /*
2171  * PQputCopyData - send some data to the backend during COPY IN or COPY BOTH
2172  *
2173  * Returns 1 if successful, 0 if data could not be sent (only possible
2174  * in nonblock mode), or -1 if an error occurs.
2175  */
2176 int
2177 PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
2178 {
2179         if (!conn)
2180                 return -1;
2181         if (conn->asyncStatus != PGASYNC_COPY_IN &&
2182                 conn->asyncStatus != PGASYNC_COPY_BOTH)
2183         {
2184                 printfPQExpBuffer(&conn->errorMessage,
2185                                                   libpq_gettext("no COPY in progress\n"));
2186                 return -1;
2187         }
2188
2189         /*
2190          * Process any NOTICE or NOTIFY messages that might be pending in the
2191          * input buffer.  Since the server might generate many notices during the
2192          * COPY, we want to clean those out reasonably promptly to prevent
2193          * indefinite expansion of the input buffer.  (Note: the actual read of
2194          * input data into the input buffer happens down inside pqSendSome, but
2195          * it's not authorized to get rid of the data again.)
2196          */
2197         parseInput(conn);
2198
2199         if (nbytes > 0)
2200         {
2201                 /*
2202                  * Try to flush any previously sent data in preference to growing the
2203                  * output buffer.  If we can't enlarge the buffer enough to hold the
2204                  * data, return 0 in the nonblock case, else hard error. (For
2205                  * simplicity, always assume 5 bytes of overhead even in protocol 2.0
2206                  * case.)
2207                  */
2208                 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2209                 {
2210                         if (pqFlush(conn) < 0)
2211                                 return -1;
2212                         if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2213                                                                           conn))
2214                                 return pqIsnonblocking(conn) ? 0 : -1;
2215                 }
2216                 /* Send the data (too simple to delegate to fe-protocol files) */
2217                 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2218                 {
2219                         if (pqPutMsgStart('d', false, conn) < 0 ||
2220                                 pqPutnchar(buffer, nbytes, conn) < 0 ||
2221                                 pqPutMsgEnd(conn) < 0)
2222                                 return -1;
2223                 }
2224                 else
2225                 {
2226                         if (pqPutMsgStart(0, false, conn) < 0 ||
2227                                 pqPutnchar(buffer, nbytes, conn) < 0 ||
2228                                 pqPutMsgEnd(conn) < 0)
2229                                 return -1;
2230                 }
2231         }
2232         return 1;
2233 }
2234
2235 /*
2236  * PQputCopyEnd - send EOF indication to the backend during COPY IN
2237  *
2238  * After calling this, use PQgetResult() to check command completion status.
2239  *
2240  * Returns 1 if successful, 0 if data could not be sent (only possible
2241  * in nonblock mode), or -1 if an error occurs.
2242  */
2243 int
2244 PQputCopyEnd(PGconn *conn, const char *errormsg)
2245 {
2246         if (!conn)
2247                 return -1;
2248         if (conn->asyncStatus != PGASYNC_COPY_IN &&
2249                 conn->asyncStatus != PGASYNC_COPY_BOTH)
2250         {
2251                 printfPQExpBuffer(&conn->errorMessage,
2252                                                   libpq_gettext("no COPY in progress\n"));
2253                 return -1;
2254         }
2255
2256         /*
2257          * Send the COPY END indicator.  This is simple enough that we don't
2258          * bother delegating it to the fe-protocol files.
2259          */
2260         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2261         {
2262                 if (errormsg)
2263                 {
2264                         /* Send COPY FAIL */
2265                         if (pqPutMsgStart('f', false, conn) < 0 ||
2266                                 pqPuts(errormsg, conn) < 0 ||
2267                                 pqPutMsgEnd(conn) < 0)
2268                                 return -1;
2269                 }
2270                 else
2271                 {
2272                         /* Send COPY DONE */
2273                         if (pqPutMsgStart('c', false, conn) < 0 ||
2274                                 pqPutMsgEnd(conn) < 0)
2275                                 return -1;
2276                 }
2277
2278                 /*
2279                  * If we sent the COPY command in extended-query mode, we must issue a
2280                  * Sync as well.
2281                  */
2282                 if (conn->queryclass != PGQUERY_SIMPLE)
2283                 {
2284                         if (pqPutMsgStart('S', false, conn) < 0 ||
2285                                 pqPutMsgEnd(conn) < 0)
2286                                 return -1;
2287                 }
2288         }
2289         else
2290         {
2291                 if (errormsg)
2292                 {
2293                         /* Ooops, no way to do this in 2.0 */
2294                         printfPQExpBuffer(&conn->errorMessage,
2295                                                           libpq_gettext("function requires at least protocol version 3.0\n"));
2296                         return -1;
2297                 }
2298                 else
2299                 {
2300                         /* Send old-style end-of-data marker */
2301                         if (pqPutMsgStart(0, false, conn) < 0 ||
2302                                 pqPutnchar("\\.\n", 3, conn) < 0 ||
2303                                 pqPutMsgEnd(conn) < 0)
2304                                 return -1;
2305                 }
2306         }
2307
2308         /* Return to active duty */
2309         if (conn->asyncStatus == PGASYNC_COPY_BOTH)
2310                 conn->asyncStatus = PGASYNC_COPY_OUT;
2311         else
2312                 conn->asyncStatus = PGASYNC_BUSY;
2313         resetPQExpBuffer(&conn->errorMessage);
2314
2315         /* Try to flush data */
2316         if (pqFlush(conn) < 0)
2317                 return -1;
2318
2319         return 1;
2320 }
2321
2322 /*
2323  * PQgetCopyData - read a row of data from the backend during COPY OUT
2324  * or COPY BOTH
2325  *
2326  * If successful, sets *buffer to point to a malloc'd row of data, and
2327  * returns row length (always > 0) as result.
2328  * Returns 0 if no row available yet (only possible if async is true),
2329  * -1 if end of copy (consult PQgetResult), or -2 if error (consult
2330  * PQerrorMessage).
2331  */
2332 int
2333 PQgetCopyData(PGconn *conn, char **buffer, int async)
2334 {
2335         *buffer = NULL;                         /* for all failure cases */
2336         if (!conn)
2337                 return -2;
2338         if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2339                 conn->asyncStatus != PGASYNC_COPY_BOTH)
2340         {
2341                 printfPQExpBuffer(&conn->errorMessage,
2342                                                   libpq_gettext("no COPY in progress\n"));
2343                 return -2;
2344         }
2345         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2346                 return pqGetCopyData3(conn, buffer, async);
2347         else
2348                 return pqGetCopyData2(conn, buffer, async);
2349 }
2350
2351 /*
2352  * PQgetline - gets a newline-terminated string from the backend.
2353  *
2354  * Chiefly here so that applications can use "COPY <rel> to stdout"
2355  * and read the output string.  Returns a null-terminated string in s.
2356  *
2357  * XXX this routine is now deprecated, because it can't handle binary data.
2358  * If called during a COPY BINARY we return EOF.
2359  *
2360  * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
2361  * the terminating \n (like gets(3)).
2362  *
2363  * CAUTION: the caller is responsible for detecting the end-of-copy signal
2364  * (a line containing just "\.") when using this routine.
2365  *
2366  * RETURNS:
2367  *              EOF if error (eg, invalid arguments are given)
2368  *              0 if EOL is reached (i.e., \n has been read)
2369  *                              (this is required for backward-compatibility -- this
2370  *                               routine used to always return EOF or 0, assuming that
2371  *                               the line ended within maxlen bytes.)
2372  *              1 in other cases (i.e., the buffer was filled before \n is reached)
2373  */
2374 int
2375 PQgetline(PGconn *conn, char *s, int maxlen)
2376 {
2377         if (!s || maxlen <= 0)
2378                 return EOF;
2379         *s = '\0';
2380         /* maxlen must be at least 3 to hold the \. terminator! */
2381         if (maxlen < 3)
2382                 return EOF;
2383
2384         if (!conn)
2385                 return EOF;
2386
2387         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2388                 return pqGetline3(conn, s, maxlen);
2389         else
2390                 return pqGetline2(conn, s, maxlen);
2391 }
2392
2393 /*
2394  * PQgetlineAsync - gets a COPY data row without blocking.
2395  *
2396  * This routine is for applications that want to do "COPY <rel> to stdout"
2397  * asynchronously, that is without blocking.  Having issued the COPY command
2398  * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
2399  * and this routine until the end-of-data signal is detected.  Unlike
2400  * PQgetline, this routine takes responsibility for detecting end-of-data.
2401  *
2402  * On each call, PQgetlineAsync will return data if a complete data row
2403  * is available in libpq's input buffer.  Otherwise, no data is returned
2404  * until the rest of the row arrives.
2405  *
2406  * If -1 is returned, the end-of-data signal has been recognized (and removed
2407  * from libpq's input buffer).  The caller *must* next call PQendcopy and
2408  * then return to normal processing.
2409  *
2410  * RETURNS:
2411  *       -1    if the end-of-copy-data marker has been recognized
2412  *       0         if no data is available
2413  *       >0    the number of bytes returned.
2414  *
2415  * The data returned will not extend beyond a data-row boundary.  If possible
2416  * a whole row will be returned at one time.  But if the buffer offered by
2417  * the caller is too small to hold a row sent by the backend, then a partial
2418  * data row will be returned.  In text mode this can be detected by testing
2419  * whether the last returned byte is '\n' or not.
2420  *
2421  * The returned data is *not* null-terminated.
2422  */
2423
2424 int
2425 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
2426 {
2427         if (!conn)
2428                 return -1;
2429
2430         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2431                 return pqGetlineAsync3(conn, buffer, bufsize);
2432         else
2433                 return pqGetlineAsync2(conn, buffer, bufsize);
2434 }
2435
2436 /*
2437  * PQputline -- sends a string to the backend during COPY IN.
2438  * Returns 0 if OK, EOF if not.
2439  *
2440  * This is deprecated primarily because the return convention doesn't allow
2441  * caller to tell the difference between a hard error and a nonblock-mode
2442  * send failure.
2443  */
2444 int
2445 PQputline(PGconn *conn, const char *s)
2446 {
2447         return PQputnbytes(conn, s, strlen(s));
2448 }
2449
2450 /*
2451  * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
2452  * Returns 0 if OK, EOF if not.
2453  */
2454 int
2455 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
2456 {
2457         if (PQputCopyData(conn, buffer, nbytes) > 0)
2458                 return 0;
2459         else
2460                 return EOF;
2461 }
2462
2463 /*
2464  * PQendcopy
2465  *              After completing the data transfer portion of a copy in/out,
2466  *              the application must call this routine to finish the command protocol.
2467  *
2468  * When using protocol 3.0 this is deprecated; it's cleaner to use PQgetResult
2469  * to get the transfer status.  Note however that when using 2.0 protocol,
2470  * recovering from a copy failure often requires a PQreset.  PQendcopy will
2471  * take care of that, PQgetResult won't.
2472  *
2473  * RETURNS:
2474  *              0 on success
2475  *              1 on failure
2476  */
2477 int
2478 PQendcopy(PGconn *conn)
2479 {
2480         if (!conn)
2481                 return 0;
2482
2483         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2484                 return pqEndcopy3(conn);
2485         else
2486                 return pqEndcopy2(conn);
2487 }
2488
2489
2490 /* ----------------
2491  *              PQfn -  Send a function call to the POSTGRES backend.
2492  *
2493  *              conn                    : backend connection
2494  *              fnid                    : function id
2495  *              result_buf              : pointer to result buffer (&int if integer)
2496  *              result_len              : length of return value.
2497  *              actual_result_len: actual length returned. (differs from result_len
2498  *                                                for varlena structures.)
2499  *              result_type             : If the result is an integer, this must be 1,
2500  *                                                otherwise this should be 0
2501  *              args                    : pointer to an array of function arguments.
2502  *                                                (each has length, if integer, and value/pointer)
2503  *              nargs                   : # of arguments in args array.
2504  *
2505  * RETURNS
2506  *              PGresult with status = PGRES_COMMAND_OK if successful.
2507  *                      *actual_result_len is > 0 if there is a return value, 0 if not.
2508  *              PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
2509  *              NULL on communications failure.  conn->errorMessage will be set.
2510  * ----------------
2511  */
2512
2513 PGresult *
2514 PQfn(PGconn *conn,
2515          int fnid,
2516          int *result_buf,
2517          int *actual_result_len,
2518          int result_is_int,
2519          const PQArgBlock *args,
2520          int nargs)
2521 {
2522         *actual_result_len = 0;
2523
2524         if (!conn)
2525                 return NULL;
2526
2527         /* clear the error string */
2528         resetPQExpBuffer(&conn->errorMessage);
2529
2530         if (conn->sock < 0 || conn->asyncStatus != PGASYNC_IDLE ||
2531                 conn->result != NULL)
2532         {
2533                 printfPQExpBuffer(&conn->errorMessage,
2534                                                   libpq_gettext("connection in wrong state\n"));
2535                 return NULL;
2536         }
2537
2538         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2539                 return pqFunctionCall3(conn, fnid,
2540                                                            result_buf, actual_result_len,
2541                                                            result_is_int,
2542                                                            args, nargs);
2543         else
2544                 return pqFunctionCall2(conn, fnid,
2545                                                            result_buf, actual_result_len,
2546                                                            result_is_int,
2547                                                            args, nargs);
2548 }
2549
2550
2551 /* ====== accessor funcs for PGresult ======== */
2552
2553 ExecStatusType
2554 PQresultStatus(const PGresult *res)
2555 {
2556         if (!res)
2557                 return PGRES_FATAL_ERROR;
2558         return res->resultStatus;
2559 }
2560
2561 char *
2562 PQresStatus(ExecStatusType status)
2563 {
2564         if ((unsigned int) status >= sizeof pgresStatus / sizeof pgresStatus[0])
2565                 return libpq_gettext("invalid ExecStatusType code");
2566         return pgresStatus[status];
2567 }
2568
2569 char *
2570 PQresultErrorMessage(const PGresult *res)
2571 {
2572         if (!res || !res->errMsg)
2573                 return "";
2574         return res->errMsg;
2575 }
2576
2577 char *
2578 PQresultErrorField(const PGresult *res, int fieldcode)
2579 {
2580         PGMessageField *pfield;
2581
2582         if (!res)
2583                 return NULL;
2584         for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
2585         {
2586                 if (pfield->code == fieldcode)
2587                         return pfield->contents;
2588         }
2589         return NULL;
2590 }
2591
2592 int
2593 PQntuples(const PGresult *res)
2594 {
2595         if (!res)
2596                 return 0;
2597         return res->ntups;
2598 }
2599
2600 int
2601 PQnfields(const PGresult *res)
2602 {
2603         if (!res)
2604                 return 0;
2605         return res->numAttributes;
2606 }
2607
2608 int
2609 PQbinaryTuples(const PGresult *res)
2610 {
2611         if (!res)
2612                 return 0;
2613         return res->binary;
2614 }
2615
2616 /*
2617  * Helper routines to range-check field numbers and tuple numbers.
2618  * Return TRUE if OK, FALSE if not
2619  */
2620
2621 static int
2622 check_field_number(const PGresult *res, int field_num)
2623 {
2624         if (!res)
2625                 return FALSE;                   /* no way to display error message... */
2626         if (field_num < 0 || field_num >= res->numAttributes)
2627         {
2628                 pqInternalNotice(&res->noticeHooks,
2629                                                  "column number %d is out of range 0..%d",
2630                                                  field_num, res->numAttributes - 1);
2631                 return FALSE;
2632         }
2633         return TRUE;
2634 }
2635
2636 static int
2637 check_tuple_field_number(const PGresult *res,
2638                                                  int tup_num, int field_num)
2639 {
2640         if (!res)
2641                 return FALSE;                   /* no way to display error message... */
2642         if (tup_num < 0 || tup_num >= res->ntups)
2643         {
2644                 pqInternalNotice(&res->noticeHooks,
2645                                                  "row number %d is out of range 0..%d",
2646                                                  tup_num, res->ntups - 1);
2647                 return FALSE;
2648         }
2649         if (field_num < 0 || field_num >= res->numAttributes)
2650         {
2651                 pqInternalNotice(&res->noticeHooks,
2652                                                  "column number %d is out of range 0..%d",
2653                                                  field_num, res->numAttributes - 1);
2654                 return FALSE;
2655         }
2656         return TRUE;
2657 }
2658
2659 static int
2660 check_param_number(const PGresult *res, int param_num)
2661 {
2662         if (!res)
2663                 return FALSE;                   /* no way to display error message... */
2664         if (param_num < 0 || param_num >= res->numParameters)
2665         {
2666                 pqInternalNotice(&res->noticeHooks,
2667                                                  "parameter number %d is out of range 0..%d",
2668                                                  param_num, res->numParameters - 1);
2669                 return FALSE;
2670         }
2671
2672         return TRUE;
2673 }
2674
2675 /*
2676  * returns NULL if the field_num is invalid
2677  */
2678 char *
2679 PQfname(const PGresult *res, int field_num)
2680 {
2681         if (!check_field_number(res, field_num))
2682                 return NULL;
2683         if (res->attDescs)
2684                 return res->attDescs[field_num].name;
2685         else
2686                 return NULL;
2687 }
2688
2689 /*
2690  * PQfnumber: find column number given column name
2691  *
2692  * The column name is parsed as if it were in a SQL statement, including
2693  * case-folding and double-quote processing.  But note a possible gotcha:
2694  * downcasing in the frontend might follow different locale rules than
2695  * downcasing in the backend...
2696  *
2697  * Returns -1 if no match.      In the present backend it is also possible
2698  * to have multiple matches, in which case the first one is found.
2699  */
2700 int
2701 PQfnumber(const PGresult *res, const char *field_name)
2702 {
2703         char       *field_case;
2704         bool            in_quotes;
2705         char       *iptr;
2706         char       *optr;
2707         int                     i;
2708
2709         if (!res)
2710                 return -1;
2711
2712         /*
2713          * Note: it is correct to reject a zero-length input string; the proper
2714          * input to match a zero-length field name would be "".
2715          */
2716         if (field_name == NULL ||
2717                 field_name[0] == '\0' ||
2718                 res->attDescs == NULL)
2719                 return -1;
2720
2721         /*
2722          * Note: this code will not reject partially quoted strings, eg
2723          * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
2724          * condition.
2725          */
2726         field_case = strdup(field_name);
2727         if (field_case == NULL)
2728                 return -1;                              /* grotty */
2729
2730         in_quotes = false;
2731         optr = field_case;
2732         for (iptr = field_case; *iptr; iptr++)
2733         {
2734                 char            c = *iptr;
2735
2736                 if (in_quotes)
2737                 {
2738                         if (c == '"')
2739                         {
2740                                 if (iptr[1] == '"')
2741                                 {
2742                                         /* doubled quotes become a single quote */
2743                                         *optr++ = '"';
2744                                         iptr++;
2745                                 }
2746                                 else
2747                                         in_quotes = false;
2748                         }
2749                         else
2750                                 *optr++ = c;
2751                 }
2752                 else if (c == '"')
2753                         in_quotes = true;
2754                 else
2755                 {
2756                         c = pg_tolower((unsigned char) c);
2757                         *optr++ = c;
2758                 }
2759         }
2760         *optr = '\0';
2761
2762         for (i = 0; i < res->numAttributes; i++)
2763         {
2764                 if (strcmp(field_case, res->attDescs[i].name) == 0)
2765                 {
2766                         free(field_case);
2767                         return i;
2768                 }
2769         }
2770         free(field_case);
2771         return -1;
2772 }
2773
2774 Oid
2775 PQftable(const PGresult *res, int field_num)
2776 {
2777         if (!check_field_number(res, field_num))
2778                 return InvalidOid;
2779         if (res->attDescs)
2780                 return res->attDescs[field_num].tableid;
2781         else
2782                 return InvalidOid;
2783 }
2784
2785 int
2786 PQftablecol(const PGresult *res, int field_num)
2787 {
2788         if (!check_field_number(res, field_num))
2789                 return 0;
2790         if (res->attDescs)
2791                 return res->attDescs[field_num].columnid;
2792         else
2793                 return 0;
2794 }
2795
2796 int
2797 PQfformat(const PGresult *res, int field_num)
2798 {
2799         if (!check_field_number(res, field_num))
2800                 return 0;
2801         if (res->attDescs)
2802                 return res->attDescs[field_num].format;
2803         else
2804                 return 0;
2805 }
2806
2807 Oid
2808 PQftype(const PGresult *res, int field_num)
2809 {
2810         if (!check_field_number(res, field_num))
2811                 return InvalidOid;
2812         if (res->attDescs)
2813                 return res->attDescs[field_num].typid;
2814         else
2815                 return InvalidOid;
2816 }
2817
2818 int
2819 PQfsize(const PGresult *res, int field_num)
2820 {
2821         if (!check_field_number(res, field_num))
2822                 return 0;
2823         if (res->attDescs)
2824                 return res->attDescs[field_num].typlen;
2825         else
2826                 return 0;
2827 }
2828
2829 int
2830 PQfmod(const PGresult *res, int field_num)
2831 {
2832         if (!check_field_number(res, field_num))
2833                 return 0;
2834         if (res->attDescs)
2835                 return res->attDescs[field_num].atttypmod;
2836         else
2837                 return 0;
2838 }
2839
2840 char *
2841 PQcmdStatus(PGresult *res)
2842 {
2843         if (!res)
2844                 return NULL;
2845         return res->cmdStatus;
2846 }
2847
2848 /*
2849  * PQoidStatus -
2850  *      if the last command was an INSERT, return the oid string
2851  *      if not, return ""
2852  */
2853 char *
2854 PQoidStatus(const PGresult *res)
2855 {
2856         /*
2857          * This must be enough to hold the result. Don't laugh, this is better
2858          * than what this function used to do.
2859          */
2860         static char buf[24];
2861
2862         size_t          len;
2863
2864         if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2865                 return "";
2866
2867         len = strspn(res->cmdStatus + 7, "0123456789");
2868         if (len > 23)
2869                 len = 23;
2870         strncpy(buf, res->cmdStatus + 7, len);
2871         buf[len] = '\0';
2872
2873         return buf;
2874 }
2875
2876 /*
2877  * PQoidValue -
2878  *      a perhaps preferable form of the above which just returns
2879  *      an Oid type
2880  */
2881 Oid
2882 PQoidValue(const PGresult *res)
2883 {
2884         char       *endptr = NULL;
2885         unsigned long result;
2886
2887         if (!res ||
2888                 !res->cmdStatus ||
2889                 strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
2890                 res->cmdStatus[7] < '0' ||
2891                 res->cmdStatus[7] > '9')
2892                 return InvalidOid;
2893
2894         result = strtoul(res->cmdStatus + 7, &endptr, 10);
2895
2896         if (!endptr || (*endptr != ' ' && *endptr != '\0'))
2897                 return InvalidOid;
2898         else
2899                 return (Oid) result;
2900 }
2901
2902
2903 /*
2904  * PQcmdTuples -
2905  *      If the last command was INSERT/UPDATE/DELETE/MOVE/FETCH/COPY, return
2906  *      a string containing the number of inserted/affected tuples. If not,
2907  *      return "".
2908  *
2909  *      XXX: this should probably return an int
2910  */
2911 char *
2912 PQcmdTuples(PGresult *res)
2913 {
2914         char       *p,
2915                            *c;
2916
2917         if (!res)
2918                 return "";
2919
2920         if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
2921         {
2922                 p = res->cmdStatus + 7;
2923                 /* INSERT: skip oid and space */
2924                 while (*p && *p != ' ')
2925                         p++;
2926                 if (*p == 0)
2927                         goto interpret_error;           /* no space? */
2928                 p++;
2929         }
2930         else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
2931                          strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
2932                          strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
2933                 p = res->cmdStatus + 7;
2934         else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
2935                 p = res->cmdStatus + 6;
2936         else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
2937                          strncmp(res->cmdStatus, "COPY ", 5) == 0)
2938                 p = res->cmdStatus + 5;
2939         else
2940                 return "";
2941
2942         /* check that we have an integer (at least one digit, nothing else) */
2943         for (c = p; *c; c++)
2944         {
2945                 if (!isdigit((unsigned char) *c))
2946                         goto interpret_error;
2947         }
2948         if (c == p)
2949                 goto interpret_error;
2950
2951         return p;
2952
2953 interpret_error:
2954         pqInternalNotice(&res->noticeHooks,
2955                                          "could not interpret result from server: %s",
2956                                          res->cmdStatus);
2957         return "";
2958 }
2959
2960 /*
2961  * PQgetvalue:
2962  *      return the value of field 'field_num' of row 'tup_num'
2963  */
2964 char *
2965 PQgetvalue(const PGresult *res, int tup_num, int field_num)
2966 {
2967         if (!check_tuple_field_number(res, tup_num, field_num))
2968                 return NULL;
2969         return res->tuples[tup_num][field_num].value;
2970 }
2971
2972 /* PQgetlength:
2973  *      returns the actual length of a field value in bytes.
2974  */
2975 int
2976 PQgetlength(const PGresult *res, int tup_num, int field_num)
2977 {
2978         if (!check_tuple_field_number(res, tup_num, field_num))
2979                 return 0;
2980         if (res->tuples[tup_num][field_num].len != NULL_LEN)
2981                 return res->tuples[tup_num][field_num].len;
2982         else
2983                 return 0;
2984 }
2985
2986 /* PQgetisnull:
2987  *      returns the null status of a field value.
2988  */
2989 int
2990 PQgetisnull(const PGresult *res, int tup_num, int field_num)
2991 {
2992         if (!check_tuple_field_number(res, tup_num, field_num))
2993                 return 1;                               /* pretend it is null */
2994         if (res->tuples[tup_num][field_num].len == NULL_LEN)
2995                 return 1;
2996         else
2997                 return 0;
2998 }
2999
3000 /* PQnparams:
3001  *      returns the number of input parameters of a prepared statement.
3002  */
3003 int
3004 PQnparams(const PGresult *res)
3005 {
3006         if (!res)
3007                 return 0;
3008         return res->numParameters;
3009 }
3010
3011 /* PQparamtype:
3012  *      returns type Oid of the specified statement parameter.
3013  */
3014 Oid
3015 PQparamtype(const PGresult *res, int param_num)
3016 {
3017         if (!check_param_number(res, param_num))
3018                 return InvalidOid;
3019         if (res->paramDescs)
3020                 return res->paramDescs[param_num].typid;
3021         else
3022                 return InvalidOid;
3023 }
3024
3025
3026 /* PQsetnonblocking:
3027  *      sets the PGconn's database connection non-blocking if the arg is TRUE
3028  *      or makes it blocking if the arg is FALSE, this will not protect
3029  *      you from PQexec(), you'll only be safe when using the non-blocking API.
3030  *      Needs to be called only on a connected database connection.
3031  */
3032 int
3033 PQsetnonblocking(PGconn *conn, int arg)
3034 {
3035         bool            barg;
3036
3037         if (!conn || conn->status == CONNECTION_BAD)
3038                 return -1;
3039
3040         barg = (arg ? TRUE : FALSE);
3041
3042         /* early out if the socket is already in the state requested */
3043         if (barg == conn->nonblocking)
3044                 return 0;
3045
3046         /*
3047          * to guarantee constancy for flushing/query/result-polling behavior we
3048          * need to flush the send queue at this point in order to guarantee proper
3049          * behavior. this is ok because either they are making a transition _from_
3050          * or _to_ blocking mode, either way we can block them.
3051          */
3052         /* if we are going from blocking to non-blocking flush here */
3053         if (pqFlush(conn))
3054                 return -1;
3055
3056         conn->nonblocking = barg;
3057
3058         return 0;
3059 }
3060
3061 /*
3062  * return the blocking status of the database connection
3063  *              TRUE == nonblocking, FALSE == blocking
3064  */
3065 int
3066 PQisnonblocking(const PGconn *conn)
3067 {
3068         return pqIsnonblocking(conn);
3069 }
3070
3071 /* libpq is thread-safe? */
3072 int
3073 PQisthreadsafe(void)
3074 {
3075 #ifdef ENABLE_THREAD_SAFETY
3076         return true;
3077 #else
3078         return false;
3079 #endif
3080 }
3081
3082
3083 /* try to force data out, really only useful for non-blocking users */
3084 int
3085 PQflush(PGconn *conn)
3086 {
3087         return pqFlush(conn);
3088 }
3089
3090
3091 /*
3092  *              PQfreemem - safely frees memory allocated
3093  *
3094  * Needed mostly by Win32, unless multithreaded DLL (/MD in VC6)
3095  * Used for freeing memory from PQescapeByte()a/PQunescapeBytea()
3096  */
3097 void
3098 PQfreemem(void *ptr)
3099 {
3100         free(ptr);
3101 }
3102
3103 /*
3104  * PQfreeNotify - free's the memory associated with a PGnotify
3105  *
3106  * This function is here only for binary backward compatibility.
3107  * New code should use PQfreemem().  A macro will automatically map
3108  * calls to PQfreemem.  It should be removed in the future.  bjm 2003-03-24
3109  */
3110
3111 #undef PQfreeNotify
3112 void            PQfreeNotify(PGnotify *notify);
3113
3114 void
3115 PQfreeNotify(PGnotify *notify)
3116 {
3117         PQfreemem(notify);
3118 }
3119
3120
3121 /*
3122  * Escaping arbitrary strings to get valid SQL literal strings.
3123  *
3124  * Replaces "'" with "''", and if not std_strings, replaces "\" with "\\".
3125  *
3126  * length is the length of the source string.  (Note: if a terminating NUL
3127  * is encountered sooner, PQescapeString stops short of "length"; the behavior
3128  * is thus rather like strncpy.)
3129  *
3130  * For safety the buffer at "to" must be at least 2*length + 1 bytes long.
3131  * A terminating NUL character is added to the output string, whether the
3132  * input is NUL-terminated or not.
3133  *
3134  * Returns the actual length of the output (not counting the terminating NUL).
3135  */
3136 static size_t
3137 PQescapeStringInternal(PGconn *conn,
3138                                            char *to, const char *from, size_t length,
3139                                            int *error,
3140                                            int encoding, bool std_strings)
3141 {
3142         const char *source = from;
3143         char       *target = to;
3144         size_t          remaining = length;
3145
3146         if (error)
3147                 *error = 0;
3148
3149         while (remaining > 0 && *source != '\0')
3150         {
3151                 char            c = *source;
3152                 int                     len;
3153                 int                     i;
3154
3155                 /* Fast path for plain ASCII */
3156                 if (!IS_HIGHBIT_SET(c))
3157                 {
3158                         /* Apply quoting if needed */
3159                         if (SQL_STR_DOUBLE(c, !std_strings))
3160                                 *target++ = c;
3161                         /* Copy the character */
3162                         *target++ = c;
3163                         source++;
3164                         remaining--;
3165                         continue;
3166                 }
3167
3168                 /* Slow path for possible multibyte characters */
3169                 len = pg_encoding_mblen(encoding, source);
3170
3171                 /* Copy the character */
3172                 for (i = 0; i < len; i++)
3173                 {
3174                         if (remaining == 0 || *source == '\0')
3175                                 break;
3176                         *target++ = *source++;
3177                         remaining--;
3178                 }
3179
3180                 /*
3181                  * If we hit premature end of string (ie, incomplete multibyte
3182                  * character), try to pad out to the correct length with spaces. We
3183                  * may not be able to pad completely, but we will always be able to
3184                  * insert at least one pad space (since we'd not have quoted a
3185                  * multibyte character).  This should be enough to make a string that
3186                  * the server will error out on.
3187                  */
3188                 if (i < len)
3189                 {
3190                         if (error)
3191                                 *error = 1;
3192                         if (conn)
3193                                 printfPQExpBuffer(&conn->errorMessage,
3194                                                   libpq_gettext("incomplete multibyte character\n"));
3195                         for (; i < len; i++)
3196                         {
3197                                 if (((size_t) (target - to)) / 2 >= length)
3198                                         break;
3199                                 *target++ = ' ';
3200                         }
3201                         break;
3202                 }
3203         }
3204
3205         /* Write the terminating NUL character. */
3206         *target = '\0';
3207
3208         return target - to;
3209 }
3210
3211 size_t
3212 PQescapeStringConn(PGconn *conn,
3213                                    char *to, const char *from, size_t length,
3214                                    int *error)
3215 {
3216         if (!conn)
3217         {
3218                 /* force empty-string result */
3219                 *to = '\0';
3220                 if (error)
3221                         *error = 1;
3222                 return 0;
3223         }
3224         return PQescapeStringInternal(conn, to, from, length, error,
3225                                                                   conn->client_encoding,
3226                                                                   conn->std_strings);
3227 }
3228
3229 size_t
3230 PQescapeString(char *to, const char *from, size_t length)
3231 {
3232         return PQescapeStringInternal(NULL, to, from, length, NULL,
3233                                                                   static_client_encoding,
3234                                                                   static_std_strings);
3235 }
3236
3237
3238 /*
3239  * Escape arbitrary strings.  If as_ident is true, we escape the result
3240  * as an identifier; if false, as a literal.  The result is returned in
3241  * a newly allocated buffer.  If we fail due to an encoding violation or out
3242  * of memory condition, we return NULL, storing an error message into conn.
3243  */
3244 static char *
3245 PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
3246 {
3247         const char *s;
3248         char       *result;
3249         char       *rp;
3250         int                     num_quotes = 0; /* single or double, depending on as_ident */
3251         int                     num_backslashes = 0;
3252         int                     input_len;
3253         int                     result_size;
3254         char            quote_char = as_ident ? '"' : '\'';
3255
3256         /* We must have a connection, else fail immediately. */
3257         if (!conn)
3258                 return NULL;
3259
3260         /* Scan the string for characters that must be escaped. */
3261         for (s = str; (s - str) < len && *s != '\0'; ++s)
3262         {
3263                 if (*s == quote_char)
3264                         ++num_quotes;
3265                 else if (*s == '\\')
3266                         ++num_backslashes;
3267                 else if (IS_HIGHBIT_SET(*s))
3268                 {
3269                         int                     charlen;
3270
3271                         /* Slow path for possible multibyte characters */
3272                         charlen = pg_encoding_mblen(conn->client_encoding, s);
3273
3274                         /* Multibyte character overruns allowable length. */
3275                         if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
3276                         {
3277                                 printfPQExpBuffer(&conn->errorMessage,
3278                                                   libpq_gettext("incomplete multibyte character\n"));
3279                                 return NULL;
3280                         }
3281
3282                         /* Adjust s, bearing in mind that for loop will increment it. */
3283                         s += charlen - 1;
3284                 }
3285         }
3286
3287         /* Allocate output buffer. */
3288         input_len = s - str;
3289         result_size = input_len + num_quotes + 3;       /* two quotes, plus a NUL */
3290         if (!as_ident && num_backslashes > 0)
3291                 result_size += num_backslashes + 2;
3292         result = rp = (char *) malloc(result_size);
3293         if (rp == NULL)
3294         {
3295                 printfPQExpBuffer(&conn->errorMessage,
3296                                                   libpq_gettext("out of memory\n"));
3297                 return NULL;
3298         }
3299
3300         /*
3301          * If we are escaping a literal that contains backslashes, we use the
3302          * escape string syntax so that the result is correct under either value
3303          * of standard_conforming_strings.      We also emit a leading space in this
3304          * case, to guard against the possibility that the result might be
3305          * interpolated immediately following an identifier.
3306          */
3307         if (!as_ident && num_backslashes > 0)
3308         {
3309                 *rp++ = ' ';
3310                 *rp++ = 'E';
3311         }
3312
3313         /* Opening quote. */
3314         *rp++ = quote_char;
3315
3316         /*
3317          * Use fast path if possible.
3318          *
3319          * We've already verified that the input string is well-formed in the
3320          * current encoding.  If it contains no quotes and, in the case of
3321          * literal-escaping, no backslashes, then we can just copy it directly to
3322          * the output buffer, adding the necessary quotes.
3323          *
3324          * If not, we must rescan the input and process each character
3325          * individually.
3326          */
3327         if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
3328         {
3329                 memcpy(rp, str, input_len);
3330                 rp += input_len;
3331         }
3332         else
3333         {
3334                 for (s = str; s - str < input_len; ++s)
3335                 {
3336                         if (*s == quote_char || (!as_ident && *s == '\\'))
3337                         {
3338                                 *rp++ = *s;
3339                                 *rp++ = *s;
3340                         }
3341                         else if (!IS_HIGHBIT_SET(*s))
3342                                 *rp++ = *s;
3343                         else
3344                         {
3345                                 int                     i = pg_encoding_mblen(conn->client_encoding, s);
3346
3347                                 while (1)
3348                                 {
3349                                         *rp++ = *s;
3350                                         if (--i == 0)
3351                                                 break;
3352                                         ++s;            /* for loop will provide the final increment */
3353                                 }
3354                         }
3355                 }
3356         }
3357
3358         /* Closing quote and terminating NUL. */
3359         *rp++ = quote_char;
3360         *rp = '\0';
3361
3362         return result;
3363 }
3364
3365 char *
3366 PQescapeLiteral(PGconn *conn, const char *str, size_t len)
3367 {
3368         return PQescapeInternal(conn, str, len, false);
3369 }
3370
3371 char *
3372 PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
3373 {
3374         return PQescapeInternal(conn, str, len, true);
3375 }
3376
3377 /* HEX encoding support for bytea */
3378 static const char hextbl[] = "0123456789abcdef";
3379
3380 static const int8 hexlookup[128] = {
3381         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3382         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3383         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3384         0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
3385         -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3386         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3387         -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3388         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3389 };
3390
3391 static inline char
3392 get_hex(char c)
3393 {
3394         int                     res = -1;
3395
3396         if (c > 0 && c < 127)
3397                 res = hexlookup[(unsigned char) c];
3398
3399         return (char) res;
3400 }
3401
3402
3403 /*
3404  *              PQescapeBytea   - converts from binary string to the
3405  *              minimal encoding necessary to include the string in an SQL
3406  *              INSERT statement with a bytea type column as the target.
3407  *
3408  *              We can use either hex or escape (traditional) encoding.
3409  *              In escape mode, the following transformations are applied:
3410  *              '\0' == ASCII  0 == \000
3411  *              '\'' == ASCII 39 == ''
3412  *              '\\' == ASCII 92 == \\
3413  *              anything < 0x20, or > 0x7e ---> \ooo
3414  *                                                                              (where ooo is an octal expression)
3415  *
3416  *              If not std_strings, all backslashes sent to the output are doubled.
3417  */
3418 static unsigned char *
3419 PQescapeByteaInternal(PGconn *conn,
3420                                           const unsigned char *from, size_t from_length,
3421                                           size_t *to_length, bool std_strings, bool use_hex)
3422 {
3423         const unsigned char *vp;
3424         unsigned char *rp;
3425         unsigned char *result;
3426         size_t          i;
3427         size_t          len;
3428         size_t          bslash_len = (std_strings ? 1 : 2);
3429
3430         /*
3431          * empty string has 1 char ('\0')
3432          */
3433         len = 1;
3434
3435         if (use_hex)
3436         {
3437                 len += bslash_len + 1 + 2 * from_length;
3438         }
3439         else
3440         {
3441                 vp = from;
3442                 for (i = from_length; i > 0; i--, vp++)
3443                 {
3444                         if (*vp < 0x20 || *vp > 0x7e)
3445                                 len += bslash_len + 3;
3446                         else if (*vp == '\'')
3447                                 len += 2;
3448                         else if (*vp == '\\')
3449                                 len += bslash_len + bslash_len;
3450                         else
3451                                 len++;
3452                 }
3453         }
3454
3455         *to_length = len;
3456         rp = result = (unsigned char *) malloc(len);
3457         if (rp == NULL)
3458         {
3459                 if (conn)
3460                         printfPQExpBuffer(&conn->errorMessage,
3461                                                           libpq_gettext("out of memory\n"));
3462                 return NULL;
3463         }
3464
3465         if (use_hex)
3466         {
3467                 if (!std_strings)
3468                         *rp++ = '\\';
3469                 *rp++ = '\\';
3470                 *rp++ = 'x';
3471         }
3472
3473         vp = from;
3474         for (i = from_length; i > 0; i--, vp++)
3475         {
3476                 unsigned char c = *vp;
3477
3478                 if (use_hex)
3479                 {
3480                         *rp++ = hextbl[(c >> 4) & 0xF];
3481                         *rp++ = hextbl[c & 0xF];
3482                 }
3483                 else if (c < 0x20 || c > 0x7e)
3484                 {
3485                         if (!std_strings)
3486                                 *rp++ = '\\';
3487                         *rp++ = '\\';
3488                         *rp++ = (c >> 6) + '0';
3489                         *rp++ = ((c >> 3) & 07) + '0';
3490                         *rp++ = (c & 07) + '0';
3491                 }
3492                 else if (c == '\'')
3493                 {
3494                         *rp++ = '\'';
3495                         *rp++ = '\'';
3496                 }
3497                 else if (c == '\\')
3498                 {
3499                         if (!std_strings)
3500                         {
3501                                 *rp++ = '\\';
3502                                 *rp++ = '\\';
3503                         }
3504                         *rp++ = '\\';
3505                         *rp++ = '\\';
3506                 }
3507                 else
3508                         *rp++ = c;
3509         }
3510         *rp = '\0';
3511
3512         return result;
3513 }
3514
3515 unsigned char *
3516 PQescapeByteaConn(PGconn *conn,
3517                                   const unsigned char *from, size_t from_length,
3518                                   size_t *to_length)
3519 {
3520         if (!conn)
3521                 return NULL;
3522         return PQescapeByteaInternal(conn, from, from_length, to_length,
3523                                                                  conn->std_strings,
3524                                                                  (conn->sversion >= 90000));
3525 }
3526
3527 unsigned char *
3528 PQescapeBytea(const unsigned char *from, size_t from_length, size_t *to_length)
3529 {
3530         return PQescapeByteaInternal(NULL, from, from_length, to_length,
3531                                                                  static_std_strings,
3532                                                                  false /* can't use hex */ );
3533 }
3534
3535
3536 #define ISFIRSTOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '3')
3537 #define ISOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '7')
3538 #define OCTVAL(CH) ((CH) - '0')
3539
3540 /*
3541  *              PQunescapeBytea - converts the null terminated string representation
3542  *              of a bytea, strtext, into binary, filling a buffer. It returns a
3543  *              pointer to the buffer (or NULL on error), and the size of the
3544  *              buffer in retbuflen. The pointer may subsequently be used as an
3545  *              argument to the function PQfreemem.
3546  *
3547  *              The following transformations are made:
3548  *              \\       == ASCII 92 == \
3549  *              \ooo == a byte whose value = ooo (ooo is an octal number)
3550  *              \x       == x (x is any character not matched by the above transformations)
3551  */
3552 unsigned char *
3553 PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
3554 {
3555         size_t          strtextlen,
3556                                 buflen;
3557         unsigned char *buffer,
3558                            *tmpbuf;
3559         size_t          i,
3560                                 j;
3561
3562         if (strtext == NULL)
3563                 return NULL;
3564
3565         strtextlen = strlen((const char *) strtext);
3566
3567         if (strtext[0] == '\\' && strtext[1] == 'x')
3568         {
3569                 const unsigned char *s;
3570                 unsigned char *p;
3571
3572                 buflen = (strtextlen - 2) / 2;
3573                 /* Avoid unportable malloc(0) */
3574                 buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
3575                 if (buffer == NULL)
3576                         return NULL;
3577
3578                 s = strtext + 2;
3579                 p = buffer;
3580                 while (*s)
3581                 {
3582                         char            v1,
3583                                                 v2;
3584
3585                         /*
3586                          * Bad input is silently ignored.  Note that this includes
3587                          * whitespace between hex pairs, which is allowed by byteain.
3588                          */
3589                         v1 = get_hex(*s++);
3590                         if (!*s || v1 == (char) -1)
3591                                 continue;
3592                         v2 = get_hex(*s++);
3593                         if (v2 != (char) -1)
3594                                 *p++ = (v1 << 4) | v2;
3595                 }
3596
3597                 buflen = p - buffer;
3598         }
3599         else
3600         {
3601                 /*
3602                  * Length of input is max length of output, but add one to avoid
3603                  * unportable malloc(0) if input is zero-length.
3604                  */
3605                 buffer = (unsigned char *) malloc(strtextlen + 1);
3606                 if (buffer == NULL)
3607                         return NULL;
3608
3609                 for (i = j = 0; i < strtextlen;)
3610                 {
3611                         switch (strtext[i])
3612                         {
3613                                 case '\\':
3614                                         i++;
3615                                         if (strtext[i] == '\\')
3616                                                 buffer[j++] = strtext[i++];
3617                                         else
3618                                         {
3619                                                 if ((ISFIRSTOCTDIGIT(strtext[i])) &&
3620                                                         (ISOCTDIGIT(strtext[i + 1])) &&
3621                                                         (ISOCTDIGIT(strtext[i + 2])))
3622                                                 {
3623                                                         int                     byte;
3624
3625                                                         byte = OCTVAL(strtext[i++]);
3626                                                         byte = (byte << 3) + OCTVAL(strtext[i++]);
3627                                                         byte = (byte << 3) + OCTVAL(strtext[i++]);
3628                                                         buffer[j++] = byte;
3629                                                 }
3630                                         }
3631
3632                                         /*
3633                                          * Note: if we see '\' followed by something that isn't a
3634                                          * recognized escape sequence, we loop around having done
3635                                          * nothing except advance i.  Therefore the something will
3636                                          * be emitted as ordinary data on the next cycle. Corner
3637                                          * case: '\' at end of string will just be discarded.
3638                                          */
3639                                         break;
3640
3641                                 default:
3642                                         buffer[j++] = strtext[i++];
3643                                         break;
3644                         }
3645                 }
3646                 buflen = j;                             /* buflen is the length of the dequoted data */
3647         }
3648
3649         /* Shrink the buffer to be no larger than necessary */
3650         /* +1 avoids unportable behavior when buflen==0 */
3651         tmpbuf = realloc(buffer, buflen + 1);
3652
3653         /* It would only be a very brain-dead realloc that could fail, but... */
3654         if (!tmpbuf)
3655         {
3656                 free(buffer);
3657                 return NULL;
3658         }
3659
3660         *retbuflen = buflen;
3661         return tmpbuf;
3662 }