OSDN Git Service

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