]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-exec.c
Remove dllist.c from libpq. It's overkill for what libpq needs; we can
[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-2004, 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.163 2004/10/16 22:52:53 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          * convert server version to a numeric form as well.
613          */
614         if (strcmp(name, "client_encoding") == 0)
615                 conn->client_encoding = pg_char_to_encoding(value);
616         else if (strcmp(name, "server_version") == 0)
617         {
618                 int                     cnt;
619                 int                     vmaj,
620                                         vmin,
621                                         vrev;
622
623                 cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
624
625                 if (cnt < 2)
626                         conn->sversion = 0; /* unknown */
627                 else
628                 {
629                         if (cnt == 2)
630                                 vrev = 0;
631                         conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
632                 }
633         }
634 }
635
636
637 /*
638  * PQsendQuery
639  *       Submit a query, but don't wait for it to finish
640  *
641  * Returns: 1 if successfully submitted
642  *                      0 if error (conn->errorMessage is set)
643  */
644 int
645 PQsendQuery(PGconn *conn, const char *query)
646 {
647         if (!PQsendQueryStart(conn))
648                 return 0;
649
650         if (!query)
651         {
652                 printfPQExpBuffer(&conn->errorMessage,
653                                         libpq_gettext("command string is a null pointer\n"));
654                 return 0;
655         }
656
657         /* construct the outgoing Query message */
658         if (pqPutMsgStart('Q', false, conn) < 0 ||
659                 pqPuts(query, conn) < 0 ||
660                 pqPutMsgEnd(conn) < 0)
661         {
662                 pqHandleSendFailure(conn);
663                 return 0;
664         }
665
666         /* remember we are using simple query protocol */
667         conn->ext_query = false;
668
669         /*
670          * Give the data a push.  In nonblock mode, don't complain if we're
671          * unable to send it all; PQgetResult() will do any additional
672          * flushing needed.
673          */
674         if (pqFlush(conn) < 0)
675         {
676                 pqHandleSendFailure(conn);
677                 return 0;
678         }
679
680         /* OK, it's launched! */
681         conn->asyncStatus = PGASYNC_BUSY;
682         return 1;
683 }
684
685 /*
686  * PQsendQueryParams
687  *              Like PQsendQuery, but use protocol 3.0 so we can pass parameters
688  */
689 int
690 PQsendQueryParams(PGconn *conn,
691                                   const char *command,
692                                   int nParams,
693                                   const Oid *paramTypes,
694                                   const char *const * paramValues,
695                                   const int *paramLengths,
696                                   const int *paramFormats,
697                                   int resultFormat)
698 {
699         if (!PQsendQueryStart(conn))
700                 return 0;
701
702         if (!command)
703         {
704                 printfPQExpBuffer(&conn->errorMessage,
705                                         libpq_gettext("command string is a null pointer\n"));
706                 return 0;
707         }
708
709         return PQsendQueryGuts(conn,
710                                                    command,
711                                                    "",  /* use unnamed statement */
712                                                    nParams,
713                                                    paramTypes,
714                                                    paramValues,
715                                                    paramLengths,
716                                                    paramFormats,
717                                                    resultFormat);
718 }
719
720 /*
721  * PQsendQueryPrepared
722  *              Like PQsendQuery, but execute a previously prepared statement,
723  *              using protocol 3.0 so we can pass parameters
724  */
725 int
726 PQsendQueryPrepared(PGconn *conn,
727                                         const char *stmtName,
728                                         int nParams,
729                                         const char *const * paramValues,
730                                         const int *paramLengths,
731                                         const int *paramFormats,
732                                         int resultFormat)
733 {
734         if (!PQsendQueryStart(conn))
735                 return 0;
736
737         if (!stmtName)
738         {
739                 printfPQExpBuffer(&conn->errorMessage,
740                                         libpq_gettext("statement name is a null pointer\n"));
741                 return 0;
742         }
743
744         return PQsendQueryGuts(conn,
745                                                    NULL,        /* no command to parse */
746                                                    stmtName,
747                                                    nParams,
748                                                    NULL,        /* no param types */
749                                                    paramValues,
750                                                    paramLengths,
751                                                    paramFormats,
752                                                    resultFormat);
753 }
754
755 /*
756  * Common startup code for PQsendQuery and sibling routines
757  */
758 static bool
759 PQsendQueryStart(PGconn *conn)
760 {
761         if (!conn)
762                 return false;
763
764         /* clear the error string */
765         resetPQExpBuffer(&conn->errorMessage);
766
767         /* Don't try to send if we know there's no live connection. */
768         if (conn->status != CONNECTION_OK)
769         {
770                 printfPQExpBuffer(&conn->errorMessage,
771                                                   libpq_gettext("no connection to the server\n"));
772                 return false;
773         }
774         /* Can't send while already busy, either. */
775         if (conn->asyncStatus != PGASYNC_IDLE)
776         {
777                 printfPQExpBuffer(&conn->errorMessage,
778                           libpq_gettext("another command is already in progress\n"));
779                 return false;
780         }
781
782         /* initialize async result-accumulation state */
783         conn->result = NULL;
784         conn->curTuple = NULL;
785
786         /* ready to send command message */
787         return true;
788 }
789
790 /*
791  * PQsendQueryGuts
792  *              Common code for protocol-3.0 query sending
793  *              PQsendQueryStart should be done already
794  *
795  * command may be NULL to indicate we use an already-prepared statement
796  */
797 static int
798 PQsendQueryGuts(PGconn *conn,
799                                 const char *command,
800                                 const char *stmtName,
801                                 int nParams,
802                                 const Oid *paramTypes,
803                                 const char *const * paramValues,
804                                 const int *paramLengths,
805                                 const int *paramFormats,
806                                 int resultFormat)
807 {
808         int                     i;
809
810         /* This isn't gonna work on a 2.0 server */
811         if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
812         {
813                 printfPQExpBuffer(&conn->errorMessage,
814                                                   libpq_gettext("function requires at least protocol version 3.0\n"));
815                 return 0;
816         }
817
818         /*
819          * We will send Parse (if needed), Bind, Describe Portal, Execute,
820          * Sync, using specified statement name and the unnamed portal.
821          */
822
823         if (command)
824         {
825                 /* construct the Parse message */
826                 if (pqPutMsgStart('P', false, conn) < 0 ||
827                         pqPuts(stmtName, conn) < 0 ||
828                         pqPuts(command, conn) < 0)
829                         goto sendFailed;
830                 if (nParams > 0 && paramTypes)
831                 {
832                         if (pqPutInt(nParams, 2, conn) < 0)
833                                 goto sendFailed;
834                         for (i = 0; i < nParams; i++)
835                         {
836                                 if (pqPutInt(paramTypes[i], 4, conn) < 0)
837                                         goto sendFailed;
838                         }
839                 }
840                 else
841                 {
842                         if (pqPutInt(0, 2, conn) < 0)
843                                 goto sendFailed;
844                 }
845                 if (pqPutMsgEnd(conn) < 0)
846                         goto sendFailed;
847         }
848
849         /* construct the Bind message */
850         if (pqPutMsgStart('B', false, conn) < 0 ||
851                 pqPuts("", conn) < 0 ||
852                 pqPuts(stmtName, conn) < 0)
853                 goto sendFailed;
854         if (nParams > 0 && paramFormats)
855         {
856                 if (pqPutInt(nParams, 2, conn) < 0)
857                         goto sendFailed;
858                 for (i = 0; i < nParams; i++)
859                 {
860                         if (pqPutInt(paramFormats[i], 2, conn) < 0)
861                                 goto sendFailed;
862                 }
863         }
864         else
865         {
866                 if (pqPutInt(0, 2, conn) < 0)
867                         goto sendFailed;
868         }
869         if (pqPutInt(nParams, 2, conn) < 0)
870                 goto sendFailed;
871         for (i = 0; i < nParams; i++)
872         {
873                 if (paramValues && paramValues[i])
874                 {
875                         int                     nbytes;
876
877                         if (paramFormats && paramFormats[i] != 0)
878                         {
879                                 /* binary parameter */
880                                 nbytes = paramLengths[i];
881                         }
882                         else
883                         {
884                                 /* text parameter, do not use paramLengths */
885                                 nbytes = strlen(paramValues[i]);
886                         }
887                         if (pqPutInt(nbytes, 4, conn) < 0 ||
888                                 pqPutnchar(paramValues[i], nbytes, conn) < 0)
889                                 goto sendFailed;
890                 }
891                 else
892                 {
893                         /* take the param as NULL */
894                         if (pqPutInt(-1, 4, conn) < 0)
895                                 goto sendFailed;
896                 }
897         }
898         if (pqPutInt(1, 2, conn) < 0 ||
899                 pqPutInt(resultFormat, 2, conn))
900                 goto sendFailed;
901         if (pqPutMsgEnd(conn) < 0)
902                 goto sendFailed;
903
904         /* construct the Describe Portal message */
905         if (pqPutMsgStart('D', false, conn) < 0 ||
906                 pqPutc('P', conn) < 0 ||
907                 pqPuts("", conn) < 0 ||
908                 pqPutMsgEnd(conn) < 0)
909                 goto sendFailed;
910
911         /* construct the Execute message */
912         if (pqPutMsgStart('E', false, conn) < 0 ||
913                 pqPuts("", conn) < 0 ||
914                 pqPutInt(0, 4, conn) < 0 ||
915                 pqPutMsgEnd(conn) < 0)
916                 goto sendFailed;
917
918         /* construct the Sync message */
919         if (pqPutMsgStart('S', false, conn) < 0 ||
920                 pqPutMsgEnd(conn) < 0)
921                 goto sendFailed;
922
923         /* remember we are using extended query protocol */
924         conn->ext_query = true;
925
926         /*
927          * Give the data a push.  In nonblock mode, don't complain if we're
928          * unable to send it all; PQgetResult() will do any additional
929          * flushing needed.
930          */
931         if (pqFlush(conn) < 0)
932                 goto sendFailed;
933
934         /* OK, it's launched! */
935         conn->asyncStatus = PGASYNC_BUSY;
936         return 1;
937
938 sendFailed:
939         pqHandleSendFailure(conn);
940         return 0;
941 }
942
943 /*
944  * pqHandleSendFailure: try to clean up after failure to send command.
945  *
946  * Primarily, what we want to accomplish here is to process an async
947  * NOTICE message that the backend might have sent just before it died.
948  *
949  * NOTE: this routine should only be called in PGASYNC_IDLE state.
950  */
951 void
952 pqHandleSendFailure(PGconn *conn)
953 {
954         /*
955          * Accept any available input data, ignoring errors.  Note that if
956          * pqReadData decides the backend has closed the channel, it will
957          * close our side of the socket --- that's just what we want here.
958          */
959         while (pqReadData(conn) > 0)
960                  /* loop until no more data readable */ ;
961
962         /*
963          * Parse any available input messages.  Since we are in PGASYNC_IDLE
964          * state, only NOTICE and NOTIFY messages will be eaten.
965          */
966         parseInput(conn);
967 }
968
969 /*
970  * Consume any available input from the backend
971  * 0 return: some kind of trouble
972  * 1 return: no problem
973  */
974 int
975 PQconsumeInput(PGconn *conn)
976 {
977         if (!conn)
978                 return 0;
979
980         /*
981          * for non-blocking connections try to flush the send-queue, otherwise
982          * we may never get a response for something that may not have already
983          * been sent because it's in our write buffer!
984          */
985         if (pqIsnonblocking(conn))
986         {
987                 if (pqFlush(conn) < 0)
988                         return 0;
989         }
990
991         /*
992          * Load more data, if available. We do this no matter what state we
993          * are in, since we are probably getting called because the
994          * application wants to get rid of a read-select condition. Note that
995          * we will NOT block waiting for more input.
996          */
997         if (pqReadData(conn) < 0)
998                 return 0;
999
1000         /* Parsing of the data waits till later. */
1001         return 1;
1002 }
1003
1004
1005 /*
1006  * parseInput: if appropriate, parse input data from backend
1007  * until input is exhausted or a stopping state is reached.
1008  * Note that this function will NOT attempt to read more data from the backend.
1009  */
1010 static void
1011 parseInput(PGconn *conn)
1012 {
1013         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1014                 pqParseInput3(conn);
1015         else
1016                 pqParseInput2(conn);
1017 }
1018
1019 /*
1020  * PQisBusy
1021  *       Return TRUE if PQgetResult would block waiting for input.
1022  */
1023
1024 int
1025 PQisBusy(PGconn *conn)
1026 {
1027         if (!conn)
1028                 return FALSE;
1029
1030         /* Parse any available data, if our state permits. */
1031         parseInput(conn);
1032
1033         /* PQgetResult will return immediately in all states except BUSY. */
1034         return conn->asyncStatus == PGASYNC_BUSY;
1035 }
1036
1037
1038 /*
1039  * PQgetResult
1040  *        Get the next PGresult produced by a query.
1041  *        Returns NULL if and only if no query work remains.
1042  */
1043
1044 PGresult *
1045 PQgetResult(PGconn *conn)
1046 {
1047         PGresult   *res;
1048
1049         if (!conn)
1050                 return NULL;
1051
1052         /* Parse any available data, if our state permits. */
1053         parseInput(conn);
1054
1055         /* If not ready to return something, block until we are. */
1056         while (conn->asyncStatus == PGASYNC_BUSY)
1057         {
1058                 int                     flushResult;
1059
1060                 /*
1061                  * If data remains unsent, send it.  Else we might be waiting for
1062                  * the result of a command the backend hasn't even got yet.
1063                  */
1064                 while ((flushResult = pqFlush(conn)) > 0)
1065                 {
1066                         if (pqWait(FALSE, TRUE, conn))
1067                         {
1068                                 flushResult = -1;
1069                                 break;
1070                         }
1071                 }
1072
1073                 /* Wait for some more data, and load it. */
1074                 if (flushResult ||
1075                         pqWait(TRUE, FALSE, conn) ||
1076                         pqReadData(conn) < 0)
1077                 {
1078                         /*
1079                          * conn->errorMessage has been set by pqWait or pqReadData. We
1080                          * want to append it to any already-received error message.
1081                          */
1082                         pqSaveErrorResult(conn);
1083                         conn->asyncStatus = PGASYNC_IDLE;
1084                         return pqPrepareAsyncResult(conn);
1085                 }
1086
1087                 /* Parse it. */
1088                 parseInput(conn);
1089         }
1090
1091         /* Return the appropriate thing. */
1092         switch (conn->asyncStatus)
1093         {
1094                 case PGASYNC_IDLE:
1095                         res = NULL;                     /* query is complete */
1096                         break;
1097                 case PGASYNC_READY:
1098                         res = pqPrepareAsyncResult(conn);
1099                         /* Set the state back to BUSY, allowing parsing to proceed. */
1100                         conn->asyncStatus = PGASYNC_BUSY;
1101                         break;
1102                 case PGASYNC_COPY_IN:
1103                         if (conn->result && conn->result->resultStatus == PGRES_COPY_IN)
1104                                 res = pqPrepareAsyncResult(conn);
1105                         else
1106                                 res = PQmakeEmptyPGresult(conn, PGRES_COPY_IN);
1107                         break;
1108                 case PGASYNC_COPY_OUT:
1109                         if (conn->result && conn->result->resultStatus == PGRES_COPY_OUT)
1110                                 res = pqPrepareAsyncResult(conn);
1111                         else
1112                                 res = PQmakeEmptyPGresult(conn, PGRES_COPY_OUT);
1113                         break;
1114                 default:
1115                         printfPQExpBuffer(&conn->errorMessage,
1116                                                    libpq_gettext("unexpected asyncStatus: %d\n"),
1117                                                           (int) conn->asyncStatus);
1118                         res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1119                         break;
1120         }
1121
1122         return res;
1123 }
1124
1125
1126 /*
1127  * PQexec
1128  *        send a query to the backend and package up the result in a PGresult
1129  *
1130  * If the query was not even sent, return NULL; conn->errorMessage is set to
1131  * a relevant message.
1132  * If the query was sent, a new PGresult is returned (which could indicate
1133  * either success or failure).
1134  * The user is responsible for freeing the PGresult via PQclear()
1135  * when done with it.
1136  */
1137
1138 PGresult *
1139 PQexec(PGconn *conn, const char *query)
1140 {
1141         if (!PQexecStart(conn))
1142                 return NULL;
1143         if (!PQsendQuery(conn, query))
1144                 return NULL;
1145         return PQexecFinish(conn);
1146 }
1147
1148 /*
1149  * PQexecParams
1150  *              Like PQexec, but use protocol 3.0 so we can pass parameters
1151  */
1152 PGresult *
1153 PQexecParams(PGconn *conn,
1154                          const char *command,
1155                          int nParams,
1156                          const Oid *paramTypes,
1157                          const char *const * paramValues,
1158                          const int *paramLengths,
1159                          const int *paramFormats,
1160                          int resultFormat)
1161 {
1162         if (!PQexecStart(conn))
1163                 return NULL;
1164         if (!PQsendQueryParams(conn, command,
1165                                                    nParams, paramTypes, paramValues, paramLengths,
1166                                                    paramFormats, resultFormat))
1167                 return NULL;
1168         return PQexecFinish(conn);
1169 }
1170
1171 /*
1172  * PQexecPrepared
1173  *              Like PQexec, but execute a previously prepared statement,
1174  *              using protocol 3.0 so we can pass parameters
1175  */
1176 PGresult *
1177 PQexecPrepared(PGconn *conn,
1178                            const char *stmtName,
1179                            int nParams,
1180                            const char *const * paramValues,
1181                            const int *paramLengths,
1182                            const int *paramFormats,
1183                            int resultFormat)
1184 {
1185         if (!PQexecStart(conn))
1186                 return NULL;
1187         if (!PQsendQueryPrepared(conn, stmtName,
1188                                                          nParams, paramValues, paramLengths,
1189                                                          paramFormats, resultFormat))
1190                 return NULL;
1191         return PQexecFinish(conn);
1192 }
1193
1194 /*
1195  * Common code for PQexec and sibling routines: prepare to send command
1196  */
1197 static bool
1198 PQexecStart(PGconn *conn)
1199 {
1200         PGresult   *result;
1201
1202         if (!conn)
1203                 return false;
1204
1205         /*
1206          * Silently discard any prior query result that application didn't
1207          * eat. This is probably poor design, but it's here for backward
1208          * compatibility.
1209          */
1210         while ((result = PQgetResult(conn)) != NULL)
1211         {
1212                 ExecStatusType resultStatus = result->resultStatus;
1213
1214                 PQclear(result);                /* only need its status */
1215                 if (resultStatus == PGRES_COPY_IN)
1216                 {
1217                         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1218                         {
1219                                 /* In protocol 3, we can get out of a COPY IN state */
1220                                 if (PQputCopyEnd(conn,
1221                                          libpq_gettext("COPY terminated by new PQexec")) < 0)
1222                                         return false;
1223                                 /* keep waiting to swallow the copy's failure message */
1224                         }
1225                         else
1226                         {
1227                                 /* In older protocols we have to punt */
1228                                 printfPQExpBuffer(&conn->errorMessage,
1229                                                                   libpq_gettext("COPY IN state must be terminated first\n"));
1230                                 return false;
1231                         }
1232                 }
1233                 else if (resultStatus == PGRES_COPY_OUT)
1234                 {
1235                         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1236                         {
1237                                 /*
1238                                  * In protocol 3, we can get out of a COPY OUT state: we
1239                                  * just switch back to BUSY and allow the remaining COPY
1240                                  * data to be dropped on the floor.
1241                                  */
1242                                 conn->asyncStatus = PGASYNC_BUSY;
1243                                 /* keep waiting to swallow the copy's completion message */
1244                         }
1245                         else
1246                         {
1247                                 /* In older protocols we have to punt */
1248                                 printfPQExpBuffer(&conn->errorMessage,
1249                                                                   libpq_gettext("COPY OUT state must be terminated first\n"));
1250                                 return false;
1251                         }
1252                 }
1253                 /* check for loss of connection, too */
1254                 if (conn->status == CONNECTION_BAD)
1255                         return false;
1256         }
1257
1258         /* OK to send a command */
1259         return true;
1260 }
1261
1262 /*
1263  * Common code for PQexec and sibling routines: wait for command result
1264  */
1265 static PGresult *
1266 PQexecFinish(PGconn *conn)
1267 {
1268         PGresult   *result;
1269         PGresult   *lastResult;
1270
1271         /*
1272          * For backwards compatibility, return the last result if there are
1273          * more than one --- but merge error messages if we get more than one
1274          * error result.
1275          *
1276          * We have to stop if we see copy in/out, however. We will resume parsing
1277          * after application performs the data transfer.
1278          *
1279          * Also stop if the connection is lost (else we'll loop infinitely).
1280          */
1281         lastResult = NULL;
1282         while ((result = PQgetResult(conn)) != NULL)
1283         {
1284                 if (lastResult)
1285                 {
1286                         if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
1287                                 result->resultStatus == PGRES_FATAL_ERROR)
1288                         {
1289                                 pqCatenateResultError(lastResult, result->errMsg);
1290                                 PQclear(result);
1291                                 result = lastResult;
1292
1293                                 /*
1294                                  * Make sure PQerrorMessage agrees with concatenated
1295                                  * result
1296                                  */
1297                                 resetPQExpBuffer(&conn->errorMessage);
1298                                 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
1299                         }
1300                         else
1301                                 PQclear(lastResult);
1302                 }
1303                 lastResult = result;
1304                 if (result->resultStatus == PGRES_COPY_IN ||
1305                         result->resultStatus == PGRES_COPY_OUT ||
1306                         conn->status == CONNECTION_BAD)
1307                         break;
1308         }
1309
1310         return lastResult;
1311 }
1312
1313 /*
1314  * PQnotifies
1315  *        returns a PGnotify* structure of the latest async notification
1316  * that has not yet been handled
1317  *
1318  * returns NULL, if there is currently
1319  * no unhandled async notification from the backend
1320  *
1321  * the CALLER is responsible for FREE'ing the structure returned
1322  */
1323 PGnotify *
1324 PQnotifies(PGconn *conn)
1325 {
1326         PGnotify   *event;
1327
1328         if (!conn)
1329                 return NULL;
1330
1331         /* Parse any available data to see if we can extract NOTIFY messages. */
1332         parseInput(conn);
1333
1334         event = conn->notifyHead;
1335         if (event)
1336         {
1337                 conn->notifyHead = event->next;
1338                 if (!conn->notifyHead)
1339                         conn->notifyTail = NULL;
1340                 event->next = NULL;             /* don't let app see the internal state */
1341         }
1342         return event;
1343 }
1344
1345 /*
1346  * PQputCopyData - send some data to the backend during COPY IN
1347  *
1348  * Returns 1 if successful, 0 if data could not be sent (only possible
1349  * in nonblock mode), or -1 if an error occurs.
1350  */
1351 int
1352 PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
1353 {
1354         if (!conn)
1355                 return -1;
1356         if (conn->asyncStatus != PGASYNC_COPY_IN)
1357         {
1358                 printfPQExpBuffer(&conn->errorMessage,
1359                                                   libpq_gettext("no COPY in progress\n"));
1360                 return -1;
1361         }
1362
1363         /*
1364          * Check for NOTICE messages coming back from the server.  Since the
1365          * server might generate multiple notices during the COPY, we have to
1366          * consume those in a reasonably prompt fashion to prevent the comm
1367          * buffers from filling up and possibly blocking the server.
1368          */
1369         if (!PQconsumeInput(conn))
1370                 return -1;                              /* I/O failure */
1371         parseInput(conn);
1372
1373         if (nbytes > 0)
1374         {
1375                 /*
1376                  * Try to flush any previously sent data in preference to growing
1377                  * the output buffer.  If we can't enlarge the buffer enough to
1378                  * hold the data, return 0 in the nonblock case, else hard error.
1379                  * (For simplicity, always assume 5 bytes of overhead even in
1380                  * protocol 2.0 case.)
1381                  */
1382                 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
1383                 {
1384                         if (pqFlush(conn) < 0)
1385                                 return -1;
1386                         if (pqCheckOutBufferSpace(conn->outCount + 5 + nbytes, conn))
1387                                 return pqIsnonblocking(conn) ? 0 : -1;
1388                 }
1389                 /* Send the data (too simple to delegate to fe-protocol files) */
1390                 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1391                 {
1392                         if (pqPutMsgStart('d', false, conn) < 0 ||
1393                                 pqPutnchar(buffer, nbytes, conn) < 0 ||
1394                                 pqPutMsgEnd(conn) < 0)
1395                                 return -1;
1396                 }
1397                 else
1398                 {
1399                         if (pqPutMsgStart(0, false, conn) < 0 ||
1400                                 pqPutnchar(buffer, nbytes, conn) < 0 ||
1401                                 pqPutMsgEnd(conn) < 0)
1402                                 return -1;
1403                 }
1404         }
1405         return 1;
1406 }
1407
1408 /*
1409  * PQputCopyEnd - send EOF indication to the backend during COPY IN
1410  *
1411  * After calling this, use PQgetResult() to check command completion status.
1412  *
1413  * Returns 1 if successful, 0 if data could not be sent (only possible
1414  * in nonblock mode), or -1 if an error occurs.
1415  */
1416 int
1417 PQputCopyEnd(PGconn *conn, const char *errormsg)
1418 {
1419         if (!conn)
1420                 return -1;
1421         if (conn->asyncStatus != PGASYNC_COPY_IN)
1422         {
1423                 printfPQExpBuffer(&conn->errorMessage,
1424                                                   libpq_gettext("no COPY in progress\n"));
1425                 return -1;
1426         }
1427
1428         /*
1429          * Send the COPY END indicator.  This is simple enough that we don't
1430          * bother delegating it to the fe-protocol files.
1431          */
1432         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1433         {
1434                 if (errormsg)
1435                 {
1436                         /* Send COPY FAIL */
1437                         if (pqPutMsgStart('f', false, conn) < 0 ||
1438                                 pqPuts(errormsg, conn) < 0 ||
1439                                 pqPutMsgEnd(conn) < 0)
1440                                 return -1;
1441                 }
1442                 else
1443                 {
1444                         /* Send COPY DONE */
1445                         if (pqPutMsgStart('c', false, conn) < 0 ||
1446                                 pqPutMsgEnd(conn) < 0)
1447                                 return -1;
1448                 }
1449
1450                 /*
1451                  * If we sent the COPY command in extended-query mode, we must
1452                  * issue a Sync as well.
1453                  */
1454                 if (conn->ext_query)
1455                 {
1456                         if (pqPutMsgStart('S', false, conn) < 0 ||
1457                                 pqPutMsgEnd(conn) < 0)
1458                                 return -1;
1459                 }
1460         }
1461         else
1462         {
1463                 if (errormsg)
1464                 {
1465                         /* Ooops, no way to do this in 2.0 */
1466                         printfPQExpBuffer(&conn->errorMessage,
1467                                                           libpq_gettext("function requires at least protocol version 3.0\n"));
1468                         return -1;
1469                 }
1470                 else
1471                 {
1472                         /* Send old-style end-of-data marker */
1473                         if (pqPutMsgStart(0, false, conn) < 0 ||
1474                                 pqPutnchar("\\.\n", 3, conn) < 0 ||
1475                                 pqPutMsgEnd(conn) < 0)
1476                                 return -1;
1477                 }
1478         }
1479
1480         /* Return to active duty */
1481         conn->asyncStatus = PGASYNC_BUSY;
1482         resetPQExpBuffer(&conn->errorMessage);
1483
1484         /* Try to flush data */
1485         if (pqFlush(conn) < 0)
1486                 return -1;
1487
1488         return 1;
1489 }
1490
1491 /*
1492  * PQgetCopyData - read a row of data from the backend during COPY OUT
1493  *
1494  * If successful, sets *buffer to point to a malloc'd row of data, and
1495  * returns row length (always > 0) as result.
1496  * Returns 0 if no row available yet (only possible if async is true),
1497  * -1 if end of copy (consult PQgetResult), or -2 if error (consult
1498  * PQerrorMessage).
1499  */
1500 int
1501 PQgetCopyData(PGconn *conn, char **buffer, int async)
1502 {
1503         *buffer = NULL;                         /* for all failure cases */
1504         if (!conn)
1505                 return -2;
1506         if (conn->asyncStatus != PGASYNC_COPY_OUT)
1507         {
1508                 printfPQExpBuffer(&conn->errorMessage,
1509                                                   libpq_gettext("no COPY in progress\n"));
1510                 return -2;
1511         }
1512         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1513                 return pqGetCopyData3(conn, buffer, async);
1514         else
1515                 return pqGetCopyData2(conn, buffer, async);
1516 }
1517
1518 /*
1519  * PQgetline - gets a newline-terminated string from the backend.
1520  *
1521  * Chiefly here so that applications can use "COPY <rel> to stdout"
1522  * and read the output string.  Returns a null-terminated string in s.
1523  *
1524  * XXX this routine is now deprecated, because it can't handle binary data.
1525  * If called during a COPY BINARY we return EOF.
1526  *
1527  * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
1528  * the terminating \n (like gets(3)).
1529  *
1530  * CAUTION: the caller is responsible for detecting the end-of-copy signal
1531  * (a line containing just "\.") when using this routine.
1532  *
1533  * RETURNS:
1534  *              EOF if error (eg, invalid arguments are given)
1535  *              0 if EOL is reached (i.e., \n has been read)
1536  *                              (this is required for backward-compatibility -- this
1537  *                               routine used to always return EOF or 0, assuming that
1538  *                               the line ended within maxlen bytes.)
1539  *              1 in other cases (i.e., the buffer was filled before \n is reached)
1540  */
1541 int
1542 PQgetline(PGconn *conn, char *s, int maxlen)
1543 {
1544         if (!s || maxlen <= 0)
1545                 return EOF;
1546         *s = '\0';
1547         /* maxlen must be at least 3 to hold the \. terminator! */
1548         if (maxlen < 3)
1549                 return EOF;
1550
1551         if (!conn)
1552                 return EOF;
1553
1554         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1555                 return pqGetline3(conn, s, maxlen);
1556         else
1557                 return pqGetline2(conn, s, maxlen);
1558 }
1559
1560 /*
1561  * PQgetlineAsync - gets a COPY data row without blocking.
1562  *
1563  * This routine is for applications that want to do "COPY <rel> to stdout"
1564  * asynchronously, that is without blocking.  Having issued the COPY command
1565  * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
1566  * and this routine until the end-of-data signal is detected.  Unlike
1567  * PQgetline, this routine takes responsibility for detecting end-of-data.
1568  *
1569  * On each call, PQgetlineAsync will return data if a complete data row
1570  * is available in libpq's input buffer.  Otherwise, no data is returned
1571  * until the rest of the row arrives.
1572  *
1573  * If -1 is returned, the end-of-data signal has been recognized (and removed
1574  * from libpq's input buffer).  The caller *must* next call PQendcopy and
1575  * then return to normal processing.
1576  *
1577  * RETURNS:
1578  *       -1    if the end-of-copy-data marker has been recognized
1579  *       0         if no data is available
1580  *       >0    the number of bytes returned.
1581  *
1582  * The data returned will not extend beyond a data-row boundary.  If possible
1583  * a whole row will be returned at one time.  But if the buffer offered by
1584  * the caller is too small to hold a row sent by the backend, then a partial
1585  * data row will be returned.  In text mode this can be detected by testing
1586  * whether the last returned byte is '\n' or not.
1587  *
1588  * The returned data is *not* null-terminated.
1589  */
1590
1591 int
1592 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
1593 {
1594         if (!conn)
1595                 return -1;
1596
1597         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1598                 return pqGetlineAsync3(conn, buffer, bufsize);
1599         else
1600                 return pqGetlineAsync2(conn, buffer, bufsize);
1601 }
1602
1603 /*
1604  * PQputline -- sends a string to the backend during COPY IN.
1605  * Returns 0 if OK, EOF if not.
1606  *
1607  * This is deprecated primarily because the return convention doesn't allow
1608  * caller to tell the difference between a hard error and a nonblock-mode
1609  * send failure.
1610  */
1611 int
1612 PQputline(PGconn *conn, const char *s)
1613 {
1614         return PQputnbytes(conn, s, strlen(s));
1615 }
1616
1617 /*
1618  * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
1619  * Returns 0 if OK, EOF if not.
1620  */
1621 int
1622 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
1623 {
1624         if (PQputCopyData(conn, buffer, nbytes) > 0)
1625                 return 0;
1626         else
1627                 return EOF;
1628 }
1629
1630 /*
1631  * PQendcopy
1632  *              After completing the data transfer portion of a copy in/out,
1633  *              the application must call this routine to finish the command protocol.
1634  *
1635  * When using protocol 3.0 this is deprecated; it's cleaner to use PQgetResult
1636  * to get the transfer status.  Note however that when using 2.0 protocol,
1637  * recovering from a copy failure often requires a PQreset.  PQendcopy will
1638  * take care of that, PQgetResult won't.
1639  *
1640  * RETURNS:
1641  *              0 on success
1642  *              1 on failure
1643  */
1644 int
1645 PQendcopy(PGconn *conn)
1646 {
1647         if (!conn)
1648                 return 0;
1649
1650         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1651                 return pqEndcopy3(conn);
1652         else
1653                 return pqEndcopy2(conn);
1654 }
1655
1656
1657 /* ----------------
1658  *              PQfn -  Send a function call to the POSTGRES backend.
1659  *
1660  *              conn                    : backend connection
1661  *              fnid                    : function id
1662  *              result_buf              : pointer to result buffer (&int if integer)
1663  *              result_len              : length of return value.
1664  *              actual_result_len: actual length returned. (differs from result_len
1665  *                                                for varlena structures.)
1666  *              result_type             : If the result is an integer, this must be 1,
1667  *                                                otherwise this should be 0
1668  *              args                    : pointer to an array of function arguments.
1669  *                                                (each has length, if integer, and value/pointer)
1670  *              nargs                   : # of arguments in args array.
1671  *
1672  * RETURNS
1673  *              PGresult with status = PGRES_COMMAND_OK if successful.
1674  *                      *actual_result_len is > 0 if there is a return value, 0 if not.
1675  *              PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
1676  *              NULL on communications failure.  conn->errorMessage will be set.
1677  * ----------------
1678  */
1679
1680 PGresult *
1681 PQfn(PGconn *conn,
1682          int fnid,
1683          int *result_buf,
1684          int *actual_result_len,
1685          int result_is_int,
1686          const PQArgBlock *args,
1687          int nargs)
1688 {
1689         *actual_result_len = 0;
1690
1691         if (!conn)
1692                 return NULL;
1693
1694         /* clear the error string */
1695         resetPQExpBuffer(&conn->errorMessage);
1696
1697         if (conn->sock < 0 || conn->asyncStatus != PGASYNC_IDLE ||
1698                 conn->result != NULL)
1699         {
1700                 printfPQExpBuffer(&conn->errorMessage,
1701                                                   libpq_gettext("connection in wrong state\n"));
1702                 return NULL;
1703         }
1704
1705         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1706                 return pqFunctionCall3(conn, fnid,
1707                                                            result_buf, actual_result_len,
1708                                                            result_is_int,
1709                                                            args, nargs);
1710         else
1711                 return pqFunctionCall2(conn, fnid,
1712                                                            result_buf, actual_result_len,
1713                                                            result_is_int,
1714                                                            args, nargs);
1715 }
1716
1717
1718 /* ====== accessor funcs for PGresult ======== */
1719
1720 ExecStatusType
1721 PQresultStatus(const PGresult *res)
1722 {
1723         if (!res)
1724                 return PGRES_FATAL_ERROR;
1725         return res->resultStatus;
1726 }
1727
1728 char *
1729 PQresStatus(ExecStatusType status)
1730 {
1731         if (status < 0 || status >= sizeof pgresStatus / sizeof pgresStatus[0])
1732                 return libpq_gettext("invalid ExecStatusType code");
1733         return pgresStatus[status];
1734 }
1735
1736 char *
1737 PQresultErrorMessage(const PGresult *res)
1738 {
1739         if (!res || !res->errMsg)
1740                 return "";
1741         return res->errMsg;
1742 }
1743
1744 char *
1745 PQresultErrorField(const PGresult *res, int fieldcode)
1746 {
1747         PGMessageField *pfield;
1748
1749         if (!res)
1750                 return NULL;
1751         for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
1752         {
1753                 if (pfield->code == fieldcode)
1754                         return pfield->contents;
1755         }
1756         return NULL;
1757 }
1758
1759 int
1760 PQntuples(const PGresult *res)
1761 {
1762         if (!res)
1763                 return 0;
1764         return res->ntups;
1765 }
1766
1767 int
1768 PQnfields(const PGresult *res)
1769 {
1770         if (!res)
1771                 return 0;
1772         return res->numAttributes;
1773 }
1774
1775 int
1776 PQbinaryTuples(const PGresult *res)
1777 {
1778         if (!res)
1779                 return 0;
1780         return res->binary;
1781 }
1782
1783 /*
1784  * Helper routines to range-check field numbers and tuple numbers.
1785  * Return TRUE if OK, FALSE if not
1786  */
1787
1788 static int
1789 check_field_number(const PGresult *res, int field_num)
1790 {
1791         if (!res)
1792                 return FALSE;                   /* no way to display error message... */
1793         if (field_num < 0 || field_num >= res->numAttributes)
1794         {
1795                 pqInternalNotice(&res->noticeHooks,
1796                                                  "column number %d is out of range 0..%d",
1797                                                  field_num, res->numAttributes - 1);
1798                 return FALSE;
1799         }
1800         return TRUE;
1801 }
1802
1803 static int
1804 check_tuple_field_number(const PGresult *res,
1805                                                  int tup_num, int field_num)
1806 {
1807         if (!res)
1808                 return FALSE;                   /* no way to display error message... */
1809         if (tup_num < 0 || tup_num >= res->ntups)
1810         {
1811                 pqInternalNotice(&res->noticeHooks,
1812                                                  "row number %d is out of range 0..%d",
1813                                                  tup_num, res->ntups - 1);
1814                 return FALSE;
1815         }
1816         if (field_num < 0 || field_num >= res->numAttributes)
1817         {
1818                 pqInternalNotice(&res->noticeHooks,
1819                                                  "column number %d is out of range 0..%d",
1820                                                  field_num, res->numAttributes - 1);
1821                 return FALSE;
1822         }
1823         return TRUE;
1824 }
1825
1826 /*
1827  * returns NULL if the field_num is invalid
1828  */
1829 char *
1830 PQfname(const PGresult *res, int field_num)
1831 {
1832         if (!check_field_number(res, field_num))
1833                 return NULL;
1834         if (res->attDescs)
1835                 return res->attDescs[field_num].name;
1836         else
1837                 return NULL;
1838 }
1839
1840 /*
1841  * PQfnumber: find column number given column name
1842  *
1843  * The column name is parsed as if it were in a SQL statement, including
1844  * case-folding and double-quote processing.  But note a possible gotcha:
1845  * downcasing in the frontend might follow different locale rules than
1846  * downcasing in the backend...
1847  *
1848  * Returns -1 if no match.      In the present backend it is also possible
1849  * to have multiple matches, in which case the first one is found.
1850  */
1851 int
1852 PQfnumber(const PGresult *res, const char *field_name)
1853 {
1854         char       *field_case;
1855         bool            in_quotes;
1856         char       *iptr;
1857         char       *optr;
1858         int                     i;
1859
1860         if (!res)
1861                 return -1;
1862
1863         /*
1864          * Note: it is correct to reject a zero-length input string; the
1865          * proper input to match a zero-length field name would be "".
1866          */
1867         if (field_name == NULL ||
1868                 field_name[0] == '\0' ||
1869                 res->attDescs == NULL)
1870                 return -1;
1871
1872         /*
1873          * Note: this code will not reject partially quoted strings, eg
1874          * foo"BAR"foo will become fooBARfoo when it probably ought to be an
1875          * error condition.
1876          */
1877         field_case = strdup(field_name);
1878         if (field_case == NULL)
1879                 return -1;                              /* grotty */
1880
1881         in_quotes = false;
1882         optr = field_case;
1883         for (iptr = field_case; *iptr; iptr++)
1884         {
1885                 char            c = *iptr;
1886
1887                 if (in_quotes)
1888                 {
1889                         if (c == '"')
1890                         {
1891                                 if (iptr[1] == '"')
1892                                 {
1893                                         /* doubled quotes become a single quote */
1894                                         *optr++ = '"';
1895                                         iptr++;
1896                                 }
1897                                 else
1898                                         in_quotes = false;
1899                         }
1900                         else
1901                                 *optr++ = c;
1902                 }
1903                 else if (c == '"')
1904                         in_quotes = true;
1905                 else
1906                 {
1907                         c = pg_tolower((unsigned char) c);
1908                         *optr++ = c;
1909                 }
1910         }
1911         *optr = '\0';
1912
1913         for (i = 0; i < res->numAttributes; i++)
1914         {
1915                 if (strcmp(field_case, res->attDescs[i].name) == 0)
1916                 {
1917                         free(field_case);
1918                         return i;
1919                 }
1920         }
1921         free(field_case);
1922         return -1;
1923 }
1924
1925 Oid
1926 PQftable(const PGresult *res, int field_num)
1927 {
1928         if (!check_field_number(res, field_num))
1929                 return InvalidOid;
1930         if (res->attDescs)
1931                 return res->attDescs[field_num].tableid;
1932         else
1933                 return InvalidOid;
1934 }
1935
1936 int
1937 PQftablecol(const PGresult *res, int field_num)
1938 {
1939         if (!check_field_number(res, field_num))
1940                 return 0;
1941         if (res->attDescs)
1942                 return res->attDescs[field_num].columnid;
1943         else
1944                 return 0;
1945 }
1946
1947 int
1948 PQfformat(const PGresult *res, int field_num)
1949 {
1950         if (!check_field_number(res, field_num))
1951                 return 0;
1952         if (res->attDescs)
1953                 return res->attDescs[field_num].format;
1954         else
1955                 return 0;
1956 }
1957
1958 Oid
1959 PQftype(const PGresult *res, int field_num)
1960 {
1961         if (!check_field_number(res, field_num))
1962                 return InvalidOid;
1963         if (res->attDescs)
1964                 return res->attDescs[field_num].typid;
1965         else
1966                 return InvalidOid;
1967 }
1968
1969 int
1970 PQfsize(const PGresult *res, int field_num)
1971 {
1972         if (!check_field_number(res, field_num))
1973                 return 0;
1974         if (res->attDescs)
1975                 return res->attDescs[field_num].typlen;
1976         else
1977                 return 0;
1978 }
1979
1980 int
1981 PQfmod(const PGresult *res, int field_num)
1982 {
1983         if (!check_field_number(res, field_num))
1984                 return 0;
1985         if (res->attDescs)
1986                 return res->attDescs[field_num].atttypmod;
1987         else
1988                 return 0;
1989 }
1990
1991 char *
1992 PQcmdStatus(PGresult *res)
1993 {
1994         if (!res)
1995                 return NULL;
1996         return res->cmdStatus;
1997 }
1998
1999 /*
2000  * PQoidStatus -
2001  *      if the last command was an INSERT, return the oid string
2002  *      if not, return ""
2003  */
2004 char *
2005 PQoidStatus(const PGresult *res)
2006 {
2007         /*
2008          * This must be enough to hold the result. Don't laugh, this is better
2009          * than what this function used to do.
2010          */
2011         static char buf[24];
2012
2013         size_t          len;
2014
2015         if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2016                 return "";
2017
2018         len = strspn(res->cmdStatus + 7, "0123456789");
2019         if (len > 23)
2020                 len = 23;
2021         strncpy(buf, res->cmdStatus + 7, len);
2022         buf[len] = '\0';
2023
2024         return buf;
2025 }
2026
2027 /*
2028  * PQoidValue -
2029  *      a perhaps preferable form of the above which just returns
2030  *      an Oid type
2031  */
2032 Oid
2033 PQoidValue(const PGresult *res)
2034 {
2035         char       *endptr = NULL;
2036         unsigned long result;
2037
2038         if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2039                 return InvalidOid;
2040
2041 #ifdef WIN32
2042         SetLastError(0);
2043 #else
2044         errno = 0;
2045 #endif
2046         result = strtoul(res->cmdStatus + 7, &endptr, 10);
2047
2048         if (!endptr || (*endptr != ' ' && *endptr != '\0') || errno == ERANGE)
2049                 return InvalidOid;
2050         else
2051                 return (Oid) result;
2052 }
2053
2054
2055 /*
2056  * PQcmdTuples -
2057  *      If the last command was an INSERT/UPDATE/DELETE/MOVE/FETCH, return a
2058  *      string containing the number of inserted/affected tuples. If not,
2059  *      return "".
2060  *
2061  *      XXX: this should probably return an int
2062  */
2063 char *
2064 PQcmdTuples(PGresult *res)
2065 {
2066         char       *p;
2067
2068         if (!res)
2069                 return "";
2070
2071         if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
2072         {
2073                 p = res->cmdStatus + 6;
2074                 p++;
2075                 /* INSERT: skip oid */
2076                 while (*p != ' ' && *p)
2077                         p++;
2078         }
2079         else if (strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
2080                          strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
2081                 p = res->cmdStatus + 6;
2082         else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
2083                 p = res->cmdStatus + 5;
2084         else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0)
2085                 p = res->cmdStatus + 4;
2086         else
2087                 return "";
2088
2089         p++;
2090
2091         if (*p == 0)
2092         {
2093                 pqInternalNotice(&res->noticeHooks,
2094                                                  "could not interpret result from server: %s",
2095                                                  res->cmdStatus);
2096                 return "";
2097         }
2098
2099         return p;
2100 }
2101
2102 /*
2103  * PQgetvalue:
2104  *      return the value of field 'field_num' of row 'tup_num'
2105  */
2106 char *
2107 PQgetvalue(const PGresult *res, int tup_num, int field_num)
2108 {
2109         if (!check_tuple_field_number(res, tup_num, field_num))
2110                 return NULL;
2111         return res->tuples[tup_num][field_num].value;
2112 }
2113
2114 /* PQgetlength:
2115  *      returns the actual length of a field value in bytes.
2116  */
2117 int
2118 PQgetlength(const PGresult *res, int tup_num, int field_num)
2119 {
2120         if (!check_tuple_field_number(res, tup_num, field_num))
2121                 return 0;
2122         if (res->tuples[tup_num][field_num].len != NULL_LEN)
2123                 return res->tuples[tup_num][field_num].len;
2124         else
2125                 return 0;
2126 }
2127
2128 /* PQgetisnull:
2129  *      returns the null status of a field value.
2130  */
2131 int
2132 PQgetisnull(const PGresult *res, int tup_num, int field_num)
2133 {
2134         if (!check_tuple_field_number(res, tup_num, field_num))
2135                 return 1;                               /* pretend it is null */
2136         if (res->tuples[tup_num][field_num].len == NULL_LEN)
2137                 return 1;
2138         else
2139                 return 0;
2140 }
2141
2142 /* PQsetnonblocking:
2143  *      sets the PGconn's database connection non-blocking if the arg is TRUE
2144  *      or makes it non-blocking if the arg is FALSE, this will not protect
2145  *      you from PQexec(), you'll only be safe when using the non-blocking API.
2146  *      Needs to be called only on a connected database connection.
2147  */
2148 int
2149 PQsetnonblocking(PGconn *conn, int arg)
2150 {
2151         bool            barg;
2152
2153         if (!conn || conn->status == CONNECTION_BAD)
2154                 return -1;
2155
2156         barg = (arg ? TRUE : FALSE);
2157
2158         /* early out if the socket is already in the state requested */
2159         if (barg == conn->nonblocking)
2160                 return (0);
2161
2162         /*
2163          * to guarantee constancy for flushing/query/result-polling behavior
2164          * we need to flush the send queue at this point in order to guarantee
2165          * proper behavior. this is ok because either they are making a
2166          * transition _from_ or _to_ blocking mode, either way we can block
2167          * them.
2168          */
2169         /* if we are going from blocking to non-blocking flush here */
2170         if (pqFlush(conn))
2171                 return (-1);
2172
2173         conn->nonblocking = barg;
2174
2175         return (0);
2176 }
2177
2178 /*
2179  * return the blocking status of the database connection
2180  *              TRUE == nonblocking, FALSE == blocking
2181  */
2182 int
2183 PQisnonblocking(const PGconn *conn)
2184 {
2185         return (pqIsnonblocking(conn));
2186 }
2187
2188 /* try to force data out, really only useful for non-blocking users */
2189 int
2190 PQflush(PGconn *conn)
2191 {
2192         return (pqFlush(conn));
2193 }
2194
2195
2196 /*
2197  *              PQfreemem - safely frees memory allocated
2198  *
2199  * Needed mostly by Win32, unless multithreaded DLL (/MD in VC6)
2200  * Used for freeing memory from PQescapeByte()a/PQunescapeBytea()
2201  */
2202 void
2203 PQfreemem(void *ptr)
2204 {
2205         free(ptr);
2206 }
2207
2208 /*
2209  * PQfreeNotify - free's the memory associated with a PGnotify
2210  *
2211  * This function is here only for binary backward compatibility.
2212  * New code should use PQfreemem().  A macro will automatically map
2213  * calls to PQfreemem.  It should be removed in the future.  bjm 2003-03-24
2214  */
2215
2216 #undef PQfreeNotify
2217 void            PQfreeNotify(PGnotify *notify);
2218
2219 void
2220 PQfreeNotify(PGnotify *notify)
2221 {
2222         PQfreemem(notify);
2223 }
2224
2225
2226 /*
2227  * Escaping arbitrary strings to get valid SQL literal strings.
2228  *
2229  * Replaces "\\" with "\\\\" and "'" with "''".
2230  *
2231  * length is the length of the source string.  (Note: if a terminating NUL
2232  * is encountered sooner, PQescapeString stops short of "length"; the behavior
2233  * is thus rather like strncpy.)
2234  *
2235  * For safety the buffer at "to" must be at least 2*length + 1 bytes long.
2236  * A terminating NUL character is added to the output string, whether the
2237  * input is NUL-terminated or not.
2238  *
2239  * Returns the actual length of the output (not counting the terminating NUL).
2240  */
2241 size_t
2242 PQescapeString(char *to, const char *from, size_t length)
2243 {
2244         const char *source = from;
2245         char       *target = to;
2246         size_t          remaining = length;
2247
2248         while (remaining > 0 && *source != '\0')
2249         {
2250                 switch (*source)
2251                 {
2252                         case '\\':
2253                                 *target++ = '\\';
2254                                 *target++ = '\\';
2255                                 break;
2256
2257                         case '\'':
2258                                 *target++ = '\'';
2259                                 *target++ = '\'';
2260                                 break;
2261
2262                         default:
2263                                 *target++ = *source;
2264                                 break;
2265                 }
2266                 source++;
2267                 remaining--;
2268         }
2269
2270         /* Write the terminating NUL character. */
2271         *target = '\0';
2272
2273         return target - to;
2274 }
2275
2276 /*
2277  *              PQescapeBytea   - converts from binary string to the
2278  *              minimal encoding necessary to include the string in an SQL
2279  *              INSERT statement with a bytea type column as the target.
2280  *
2281  *              The following transformations are applied
2282  *              '\0' == ASCII  0 == \\000
2283  *              '\'' == ASCII 39 == \'
2284  *              '\\' == ASCII 92 == \\\\
2285  *              anything < 0x20, or > 0x7e ---> \\ooo
2286  *                                                                              (where ooo is an octal expression)
2287  */
2288 unsigned char *
2289 PQescapeBytea(const unsigned char *bintext, size_t binlen, size_t *bytealen)
2290 {
2291         const unsigned char *vp;
2292         unsigned char *rp;
2293         unsigned char *result;
2294         size_t          i;
2295         size_t          len;
2296
2297         /*
2298          * empty string has 1 char ('\0')
2299          */
2300         len = 1;
2301
2302         vp = bintext;
2303         for (i = binlen; i > 0; i--, vp++)
2304         {
2305                 if (*vp < 0x20 || *vp > 0x7e)
2306                         len += 5;                       /* '5' is for '\\ooo' */
2307                 else if (*vp == '\'')
2308                         len += 2;
2309                 else if (*vp == '\\')
2310                         len += 4;
2311                 else
2312                         len++;
2313         }
2314
2315         rp = result = (unsigned char *) malloc(len);
2316         if (rp == NULL)
2317                 return NULL;
2318
2319         vp = bintext;
2320         *bytealen = len;
2321
2322         for (i = binlen; i > 0; i--, vp++)
2323         {
2324                 if (*vp < 0x20 || *vp > 0x7e)
2325                 {
2326                         (void) sprintf(rp, "\\\\%03o", *vp);
2327                         rp += 5;
2328                 }
2329                 else if (*vp == '\'')
2330                 {
2331                         rp[0] = '\\';
2332                         rp[1] = '\'';
2333                         rp += 2;
2334                 }
2335                 else if (*vp == '\\')
2336                 {
2337                         rp[0] = '\\';
2338                         rp[1] = '\\';
2339                         rp[2] = '\\';
2340                         rp[3] = '\\';
2341                         rp += 4;
2342                 }
2343                 else
2344                         *rp++ = *vp;
2345         }
2346         *rp = '\0';
2347
2348         return result;
2349 }
2350
2351 #define ISFIRSTOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '3')
2352 #define ISOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '7')
2353 #define OCTVAL(CH) ((CH) - '0')
2354
2355 /*
2356  *              PQunescapeBytea - converts the null terminated string representation
2357  *              of a bytea, strtext, into binary, filling a buffer. It returns a
2358  *              pointer to the buffer (or NULL on error), and the size of the
2359  *              buffer in retbuflen. The pointer may subsequently be used as an
2360  *              argument to the function free(3). It is the reverse of PQescapeBytea.
2361  *
2362  *              The following transformations are made:
2363  *              \\       == ASCII 92 == \
2364  *              \ooo == a byte whose value = ooo (ooo is an octal number)
2365  *              \x       == x (x is any character not matched by the above transformations)
2366  */
2367 unsigned char *
2368 PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
2369 {
2370         size_t          strtextlen,
2371                                 buflen;
2372         unsigned char *buffer,
2373                            *tmpbuf;
2374         size_t          i,
2375                                 j;
2376
2377         if (strtext == NULL)
2378                 return NULL;
2379
2380         strtextlen = strlen(strtext);
2381
2382         /*
2383          * Length of input is max length of output, but add one to avoid
2384          * unportable malloc(0) if input is zero-length.
2385          */
2386         buffer = (unsigned char *) malloc(strtextlen + 1);
2387         if (buffer == NULL)
2388                 return NULL;
2389
2390         for (i = j = 0; i < strtextlen;)
2391         {
2392                 switch (strtext[i])
2393                 {
2394                         case '\\':
2395                                 i++;
2396                                 if (strtext[i] == '\\')
2397                                         buffer[j++] = strtext[i++];
2398                                 else
2399                                 {
2400                                         if ((ISFIRSTOCTDIGIT(strtext[i])) &&
2401                                                 (ISOCTDIGIT(strtext[i + 1])) &&
2402                                                 (ISOCTDIGIT(strtext[i + 2])))
2403                                         {
2404                                                 int                     byte;
2405
2406                                                 byte = OCTVAL(strtext[i++]);
2407                                                 byte = (byte << 3) + OCTVAL(strtext[i++]);
2408                                                 byte = (byte << 3) + OCTVAL(strtext[i++]);
2409                                                 buffer[j++] = byte;
2410                                         }
2411                                 }
2412
2413                                 /*
2414                                  * Note: if we see '\' followed by something that isn't a
2415                                  * recognized escape sequence, we loop around having done
2416                                  * nothing except advance i.  Therefore the something will
2417                                  * be emitted as ordinary data on the next cycle. Corner
2418                                  * case: '\' at end of string will just be discarded.
2419                                  */
2420                                 break;
2421
2422                         default:
2423                                 buffer[j++] = strtext[i++];
2424                                 break;
2425                 }
2426         }
2427         buflen = j;                                     /* buflen is the length of the dequoted
2428                                                                  * data */
2429
2430         /* Shrink the buffer to be no larger than necessary */
2431         /* +1 avoids unportable behavior when buflen==0 */
2432         tmpbuf = realloc(buffer, buflen + 1);
2433
2434         /* It would only be a very brain-dead realloc that could fail, but... */
2435         if (!tmpbuf)
2436         {
2437                 free(buffer);
2438                 return NULL;
2439         }
2440
2441         *retbuflen = buflen;
2442         return tmpbuf;
2443 }