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