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