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