1 /*-------------------------------------------------------------------------
4 * functions related to sending a query down to the backend
6 * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/interfaces/libpq/fe-exec.c
13 *-------------------------------------------------------------------------
15 #include "postgres_fe.h"
28 #include "libpq-int.h"
29 #include "mb/pg_wchar.h"
31 /* keep this in same order as ExecStatusType in libpq-fe.h */
32 char *const pgresStatus[] = {
39 "PGRES_NONFATAL_ERROR",
46 * static state needed by PQescapeString and PQescapeBytea; initialize to
47 * values that result in backward-compatible behavior
49 static int static_client_encoding = PG_SQL_ASCII;
50 static bool static_std_strings = false;
53 static PGEvent *dupEvents(PGEvent *events, int count, size_t *memSize);
54 static bool pqAddTuple(PGresult *res, PGresAttValue *tup,
55 const char **errmsgp);
56 static bool PQsendQueryStart(PGconn *conn);
57 static int PQsendQueryGuts(PGconn *conn,
61 const Oid *paramTypes,
62 const char *const *paramValues,
63 const int *paramLengths,
64 const int *paramFormats,
66 static void parseInput(PGconn *conn);
67 static PGresult *getCopyResult(PGconn *conn, ExecStatusType copytype);
68 static bool PQexecStart(PGconn *conn);
69 static PGresult *PQexecFinish(PGconn *conn);
70 static int PQsendDescribe(PGconn *conn, char desc_type,
71 const char *desc_target);
72 static int check_field_number(const PGresult *res, int field_num);
76 * Space management for PGresult.
78 * Formerly, libpq did a separate malloc() for each field of each tuple
79 * returned by a query. This was remarkably expensive --- malloc/free
80 * consumed a sizable part of the application's runtime. And there is
81 * no real need to keep track of the fields separately, since they will
82 * all be freed together when the PGresult is released. So now, we grab
83 * large blocks of storage from malloc and allocate space for query data
84 * within these blocks, using a trivially simple allocator. This reduces
85 * the number of malloc/free calls dramatically, and it also avoids
86 * fragmentation of the malloc storage arena.
87 * The PGresult structure itself is still malloc'd separately. We could
88 * combine it with the first allocation block, but that would waste space
89 * for the common case that no extra storage is actually needed (that is,
90 * the SQL command did not return tuples).
92 * We also malloc the top-level array of tuple pointers separately, because
93 * we need to be able to enlarge it via realloc, and our trivial space
94 * allocator doesn't handle that effectively. (Too bad the FE/BE protocol
95 * doesn't tell us up front how many tuples will be returned.)
96 * All other subsidiary storage for a PGresult is kept in PGresult_data blocks
97 * of size PGRESULT_DATA_BLOCKSIZE. The overhead at the start of each block
98 * is just a link to the next one, if any. Free-space management info is
99 * kept in the owning PGresult.
100 * A query returning a small amount of data will thus require three malloc
101 * calls: one for the PGresult, one for the tuples pointer array, and one
102 * PGresult_data block.
104 * Only the most recently allocated PGresult_data block is a candidate to
105 * have more stuff added to it --- any extra space left over in older blocks
106 * is wasted. We could be smarter and search the whole chain, but the point
107 * here is to be simple and fast. Typical applications do not keep a PGresult
108 * around very long anyway, so some wasted space within one is not a problem.
110 * Tuning constants for the space allocator are:
111 * PGRESULT_DATA_BLOCKSIZE: size of a standard allocation block, in bytes
112 * PGRESULT_ALIGN_BOUNDARY: assumed alignment requirement for binary data
113 * PGRESULT_SEP_ALLOC_THRESHOLD: objects bigger than this are given separate
114 * blocks, instead of being crammed into a regular allocation block.
115 * Requirements for correct function are:
116 * PGRESULT_ALIGN_BOUNDARY must be a multiple of the alignment requirements
117 * of all machine data types. (Currently this is set from configure
118 * tests, so it should be OK automatically.)
119 * PGRESULT_SEP_ALLOC_THRESHOLD + PGRESULT_BLOCK_OVERHEAD <=
120 * PGRESULT_DATA_BLOCKSIZE
121 * pqResultAlloc assumes an object smaller than the threshold will fit
123 * The amount of space wasted at the end of a block could be as much as
124 * PGRESULT_SEP_ALLOC_THRESHOLD, so it doesn't pay to make that too large.
128 #define PGRESULT_DATA_BLOCKSIZE 2048
129 #define PGRESULT_ALIGN_BOUNDARY MAXIMUM_ALIGNOF /* from configure */
130 #define PGRESULT_BLOCK_OVERHEAD Max(sizeof(PGresult_data), PGRESULT_ALIGN_BOUNDARY)
131 #define PGRESULT_SEP_ALLOC_THRESHOLD (PGRESULT_DATA_BLOCKSIZE / 2)
135 * PQmakeEmptyPGresult
136 * returns a newly allocated, initialized PGresult with given status.
137 * If conn is not NULL and status indicates an error, the conn's
138 * errorMessage is copied. Also, any PGEvents are copied from the conn.
141 PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
145 result = (PGresult *) malloc(sizeof(PGresult));
150 result->numAttributes = 0;
151 result->attDescs = NULL;
152 result->tuples = NULL;
153 result->tupArrSize = 0;
154 result->numParameters = 0;
155 result->paramDescs = NULL;
156 result->resultStatus = status;
157 result->cmdStatus[0] = '\0';
159 result->events = NULL;
161 result->errMsg = NULL;
162 result->errFields = NULL;
163 result->errQuery = NULL;
164 result->null_field[0] = '\0';
165 result->curBlock = NULL;
166 result->curOffset = 0;
167 result->spaceLeft = 0;
168 result->memorySize = sizeof(PGresult);
172 /* copy connection data we might need for operations on PGresult */
173 result->noticeHooks = conn->noticeHooks;
174 result->client_encoding = conn->client_encoding;
176 /* consider copying conn's errorMessage */
179 case PGRES_EMPTY_QUERY:
180 case PGRES_COMMAND_OK:
181 case PGRES_TUPLES_OK:
184 case PGRES_COPY_BOTH:
185 case PGRES_SINGLE_TUPLE:
186 /* non-error cases */
189 pqSetResultError(result, conn->errorMessage.data);
193 /* copy events last; result must be valid if we need to PQclear */
194 if (conn->nEvents > 0)
196 result->events = dupEvents(conn->events, conn->nEvents,
197 &result->memorySize);
203 result->nEvents = conn->nEvents;
209 result->noticeHooks.noticeRec = NULL;
210 result->noticeHooks.noticeRecArg = NULL;
211 result->noticeHooks.noticeProc = NULL;
212 result->noticeHooks.noticeProcArg = NULL;
213 result->client_encoding = PG_SQL_ASCII;
222 * Set the attributes for a given result. This function fails if there are
223 * already attributes contained in the provided result. The call is
224 * ignored if numAttributes is zero or attDescs is NULL. If the
225 * function fails, it returns zero. If the function succeeds, it
226 * returns a non-zero value.
229 PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs)
233 /* If attrs already exist, they cannot be overwritten. */
234 if (!res || res->numAttributes > 0)
237 /* ignore no-op request */
238 if (numAttributes <= 0 || !attDescs)
241 res->attDescs = (PGresAttDesc *)
242 PQresultAlloc(res, numAttributes * sizeof(PGresAttDesc));
247 res->numAttributes = numAttributes;
248 memcpy(res->attDescs, attDescs, numAttributes * sizeof(PGresAttDesc));
250 /* deep-copy the attribute names, and determine format */
252 for (i = 0; i < res->numAttributes; i++)
254 if (res->attDescs[i].name)
255 res->attDescs[i].name = pqResultStrdup(res, res->attDescs[i].name);
257 res->attDescs[i].name = res->null_field;
259 if (!res->attDescs[i].name)
262 if (res->attDescs[i].format == 0)
272 * Returns a deep copy of the provided 'src' PGresult, which cannot be NULL.
273 * The 'flags' argument controls which portions of the result will or will
274 * NOT be copied. The created result is always put into the
275 * PGRES_TUPLES_OK status. The source result error message is not copied,
276 * although cmdStatus is.
278 * To set custom attributes, use PQsetResultAttrs. That function requires
279 * that there are no attrs contained in the result, so to use that
280 * function you cannot use the PG_COPYRES_ATTRS or PG_COPYRES_TUPLES
281 * options with this function.
284 * PG_COPYRES_ATTRS - Copy the source result's attributes
286 * PG_COPYRES_TUPLES - Copy the source result's tuples. This implies
287 * copying the attrs, seeing how the attrs are needed by the tuples.
289 * PG_COPYRES_EVENTS - Copy the source result's events.
291 * PG_COPYRES_NOTICEHOOKS - Copy the source result's notice hooks.
294 PQcopyResult(const PGresult *src, int flags)
302 dest = PQmakeEmptyPGresult(NULL, PGRES_TUPLES_OK);
306 /* Always copy these over. Is cmdStatus really useful here? */
307 dest->client_encoding = src->client_encoding;
308 strcpy(dest->cmdStatus, src->cmdStatus);
311 if (flags & (PG_COPYRES_ATTRS | PG_COPYRES_TUPLES))
313 if (!PQsetResultAttrs(dest, src->numAttributes, src->attDescs))
320 /* Wants to copy tuples? */
321 if (flags & PG_COPYRES_TUPLES)
326 for (tup = 0; tup < src->ntups; tup++)
328 for (field = 0; field < src->numAttributes; field++)
330 if (!PQsetvalue(dest, tup, field,
331 src->tuples[tup][field].value,
332 src->tuples[tup][field].len))
341 /* Wants to copy notice hooks? */
342 if (flags & PG_COPYRES_NOTICEHOOKS)
343 dest->noticeHooks = src->noticeHooks;
345 /* Wants to copy PGEvents? */
346 if ((flags & PG_COPYRES_EVENTS) && src->nEvents > 0)
348 dest->events = dupEvents(src->events, src->nEvents,
355 dest->nEvents = src->nEvents;
358 /* Okay, trigger PGEVT_RESULTCOPY event */
359 for (i = 0; i < dest->nEvents; i++)
361 if (src->events[i].resultInitialized)
363 PGEventResultCopy evt;
367 if (!dest->events[i].proc(PGEVT_RESULTCOPY, &evt,
368 dest->events[i].passThrough))
373 dest->events[i].resultInitialized = true;
381 * Copy an array of PGEvents (with no extra space for more).
382 * Does not duplicate the event instance data, sets this to NULL.
383 * Also, the resultInitialized flags are all cleared.
384 * The total space allocated is added to *memSize.
387 dupEvents(PGEvent *events, int count, size_t *memSize)
393 if (!events || count <= 0)
396 msize = count * sizeof(PGEvent);
397 newEvents = (PGEvent *) malloc(msize);
401 for (i = 0; i < count; i++)
403 newEvents[i].proc = events[i].proc;
404 newEvents[i].passThrough = events[i].passThrough;
405 newEvents[i].data = NULL;
406 newEvents[i].resultInitialized = false;
407 newEvents[i].name = strdup(events[i].name);
408 if (!newEvents[i].name)
411 free(newEvents[i].name);
415 msize += strlen(events[i].name) + 1;
424 * Sets the value for a tuple field. The tup_num must be less than or
425 * equal to PQntuples(res). If it is equal, a new tuple is created and
426 * added to the result.
427 * Returns a non-zero value for success and zero for failure.
428 * (On failure, we report the specific problem via pqInternalNotice.)
431 PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len)
433 PGresAttValue *attval;
434 const char *errmsg = NULL;
436 /* Note that this check also protects us against null "res" */
437 if (!check_field_number(res, field_num))
440 /* Invalid tup_num, must be <= ntups */
441 if (tup_num < 0 || tup_num > res->ntups)
443 pqInternalNotice(&res->noticeHooks,
444 "row number %d is out of range 0..%d",
445 tup_num, res->ntups);
449 /* need to allocate a new tuple? */
450 if (tup_num == res->ntups)
455 tup = (PGresAttValue *)
456 pqResultAlloc(res, res->numAttributes * sizeof(PGresAttValue),
462 /* initialize each column to NULL */
463 for (i = 0; i < res->numAttributes; i++)
465 tup[i].len = NULL_LEN;
466 tup[i].value = res->null_field;
469 /* add it to the array */
470 if (!pqAddTuple(res, tup, &errmsg))
474 attval = &res->tuples[tup_num][field_num];
476 /* treat either NULL_LEN or NULL value pointer as a NULL field */
477 if (len == NULL_LEN || value == NULL)
479 attval->len = NULL_LEN;
480 attval->value = res->null_field;
485 attval->value = res->null_field;
489 attval->value = (char *) pqResultAlloc(res, len + 1, true);
493 memcpy(attval->value, value, len);
494 attval->value[len] = '\0';
500 * Report failure via pqInternalNotice. If preceding code didn't provide
501 * an error message, assume "out of memory" was meant.
505 errmsg = libpq_gettext("out of memory");
506 pqInternalNotice(&res->noticeHooks, "%s", errmsg);
512 * pqResultAlloc - exported routine to allocate local storage in a PGresult.
514 * We force all such allocations to be maxaligned, since we don't know
515 * whether the value might be binary.
518 PQresultAlloc(PGresult *res, size_t nBytes)
520 return pqResultAlloc(res, nBytes, true);
525 * Allocate subsidiary storage for a PGresult.
527 * nBytes is the amount of space needed for the object.
528 * If isBinary is true, we assume that we need to align the object on
529 * a machine allocation boundary.
530 * If isBinary is false, we assume the object is a char string and can
531 * be allocated on any byte boundary.
534 pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
537 PGresult_data *block;
543 return res->null_field;
546 * If alignment is needed, round up the current position to an alignment
551 int offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
555 res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
556 res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
560 /* If there's enough space in the current block, no problem. */
561 if (nBytes <= (size_t) res->spaceLeft)
563 space = res->curBlock->space + res->curOffset;
564 res->curOffset += nBytes;
565 res->spaceLeft -= nBytes;
570 * If the requested object is very large, give it its own block; this
571 * avoids wasting what might be most of the current block to start a new
572 * block. (We'd have to special-case requests bigger than the block size
573 * anyway.) The object is always given binary alignment in this case.
575 if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
577 size_t alloc_size = nBytes + PGRESULT_BLOCK_OVERHEAD;
579 block = (PGresult_data *) malloc(alloc_size);
582 res->memorySize += alloc_size;
583 space = block->space + PGRESULT_BLOCK_OVERHEAD;
587 * Tuck special block below the active block, so that we don't
588 * have to waste the free space in the active block.
590 block->next = res->curBlock->next;
591 res->curBlock->next = block;
595 /* Must set up the new block as the first active block. */
597 res->curBlock = block;
598 res->spaceLeft = 0; /* be sure it's marked full */
603 /* Otherwise, start a new block. */
604 block = (PGresult_data *) malloc(PGRESULT_DATA_BLOCKSIZE);
607 res->memorySize += PGRESULT_DATA_BLOCKSIZE;
608 block->next = res->curBlock;
609 res->curBlock = block;
612 /* object needs full alignment */
613 res->curOffset = PGRESULT_BLOCK_OVERHEAD;
614 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - PGRESULT_BLOCK_OVERHEAD;
618 /* we can cram it right after the overhead pointer */
619 res->curOffset = sizeof(PGresult_data);
620 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - sizeof(PGresult_data);
623 space = block->space + res->curOffset;
624 res->curOffset += nBytes;
625 res->spaceLeft -= nBytes;
630 * PQresultMemorySize -
631 * Returns total space allocated for the PGresult.
634 PQresultMemorySize(const PGresult *res)
638 return res->memorySize;
643 * Like strdup, but the space is subsidiary PGresult space.
646 pqResultStrdup(PGresult *res, const char *str)
648 char *space = (char *) pqResultAlloc(res, strlen(str) + 1, false);
657 * assign a new error message to a PGresult
660 pqSetResultError(PGresult *res, const char *msg)
665 res->errMsg = pqResultStrdup(res, msg);
671 * pqCatenateResultError -
672 * concatenate a new error message to the one already in a PGresult
675 pqCatenateResultError(PGresult *res, const char *msg)
677 PQExpBufferData errorBuf;
681 initPQExpBuffer(&errorBuf);
683 appendPQExpBufferStr(&errorBuf, res->errMsg);
684 appendPQExpBufferStr(&errorBuf, msg);
685 pqSetResultError(res, errorBuf.data);
686 termPQExpBuffer(&errorBuf);
691 * free's the memory associated with a PGresult
694 PQclear(PGresult *res)
696 PGresult_data *block;
702 for (i = 0; i < res->nEvents; i++)
704 /* only send DESTROY to successfully-initialized event procs */
705 if (res->events[i].resultInitialized)
707 PGEventResultDestroy evt;
710 (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
711 res->events[i].passThrough);
713 free(res->events[i].name);
719 /* Free all the subsidiary blocks */
720 while ((block = res->curBlock) != NULL)
722 res->curBlock = block->next;
726 /* Free the top-level tuple pointer array */
730 /* zero out the pointer fields to catch programming errors */
731 res->attDescs = NULL;
733 res->paramDescs = NULL;
734 res->errFields = NULL;
737 /* res->curBlock was zeroed out earlier */
739 /* Free the PGresult structure itself */
744 * Handy subroutine to deallocate any partially constructed async result.
746 * Any "next" result gets cleared too.
749 pqClearAsyncResult(PGconn *conn)
752 PQclear(conn->result);
754 if (conn->next_result)
755 PQclear(conn->next_result);
756 conn->next_result = NULL;
760 * This subroutine deletes any existing async result, sets conn->result
761 * to a PGresult with status PGRES_FATAL_ERROR, and stores the current
762 * contents of conn->errorMessage into that result. It differs from a
763 * plain call on PQmakeEmptyPGresult() in that if there is already an
764 * async result with status PGRES_FATAL_ERROR, the current error message
765 * is APPENDED to the old error message instead of replacing it. This
766 * behavior lets us report multiple error conditions properly, if necessary.
767 * (An example where this is needed is when the backend sends an 'E' message
768 * and immediately closes the connection --- we want to report both the
769 * backend error and the connection closure error.)
772 pqSaveErrorResult(PGconn *conn)
775 * If no old async result, just let PQmakeEmptyPGresult make one. Likewise
776 * if old result is not an error message.
778 if (conn->result == NULL ||
779 conn->result->resultStatus != PGRES_FATAL_ERROR ||
780 conn->result->errMsg == NULL)
782 pqClearAsyncResult(conn);
783 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
787 /* Else, concatenate error message to existing async result. */
788 pqCatenateResultError(conn->result, conn->errorMessage.data);
793 * As above, and append conn->write_err_msg to whatever other error we have.
794 * This is used when we've detected a write failure and have exhausted our
795 * chances of reporting something else instead.
798 pqSaveWriteError(PGconn *conn)
801 * Ensure conn->result is an error result, and add anything in
802 * conn->errorMessage to it.
804 pqSaveErrorResult(conn);
807 * Now append write_err_msg to that. If it's null because of previous
808 * strdup failure, do what we can. (It's likely our machinations here are
809 * all getting OOM failures as well, but ...)
811 if (conn->write_err_msg && conn->write_err_msg[0] != '\0')
812 pqCatenateResultError(conn->result, conn->write_err_msg);
814 pqCatenateResultError(conn->result,
815 libpq_gettext("write to server failed\n"));
819 * This subroutine prepares an async result object for return to the caller.
820 * If there is not already an async result object, build an error object
821 * using whatever is in conn->errorMessage. In any case, clear the async
822 * result storage and make sure PQerrorMessage will agree with the result's
826 pqPrepareAsyncResult(PGconn *conn)
831 * conn->result is the PGresult to return. If it is NULL (which probably
832 * shouldn't happen) we assume there is an appropriate error message in
833 * conn->errorMessage.
837 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
841 * Make sure PQerrorMessage agrees with result; it could be different
842 * if we have concatenated messages.
844 resetPQExpBuffer(&conn->errorMessage);
845 appendPQExpBufferStr(&conn->errorMessage,
846 PQresultErrorMessage(res));
850 * Replace conn->result with next_result, if any. In the normal case
851 * there isn't a next result and we're just dropping ownership of the
852 * current result. In single-row mode this restores the situation to what
853 * it was before we created the current single-row result.
855 conn->result = conn->next_result;
856 conn->next_result = NULL;
862 * pqInternalNotice - produce an internally-generated notice message
864 * A format string and optional arguments can be passed. Note that we do
865 * libpq_gettext() here, so callers need not.
867 * The supplied text is taken as primary message (ie., it should not include
868 * a trailing newline, and should not be more than one line).
871 pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
877 if (hooks->noticeRec == NULL)
878 return; /* nobody home to receive notice? */
880 /* Format the message */
882 vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
884 msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
886 /* Make a PGresult to pass to the notice receiver */
887 res = PQmakeEmptyPGresult(NULL, PGRES_NONFATAL_ERROR);
890 res->noticeHooks = *hooks;
893 * Set up fields of notice.
895 pqSaveMessageField(res, PG_DIAG_MESSAGE_PRIMARY, msgBuf);
896 pqSaveMessageField(res, PG_DIAG_SEVERITY, libpq_gettext("NOTICE"));
897 pqSaveMessageField(res, PG_DIAG_SEVERITY_NONLOCALIZED, "NOTICE");
898 /* XXX should provide a SQLSTATE too? */
901 * Result text is always just the primary message + newline. If we can't
902 * allocate it, don't bother invoking the receiver.
904 res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, false);
907 sprintf(res->errMsg, "%s\n", msgBuf);
910 * Pass to receiver, then free it.
912 res->noticeHooks.noticeRec(res->noticeHooks.noticeRecArg, res);
919 * add a row pointer to the PGresult structure, growing it if necessary
920 * Returns true if OK, false if an error prevented adding the row
922 * On error, *errmsgp can be set to an error string to be returned.
923 * If it is left NULL, the error is presumed to be "out of memory".
926 pqAddTuple(PGresult *res, PGresAttValue *tup, const char **errmsgp)
928 if (res->ntups >= res->tupArrSize)
931 * Try to grow the array.
933 * We can use realloc because shallow copying of the structure is
934 * okay. Note that the first time through, res->tuples is NULL. While
935 * ANSI says that realloc() should act like malloc() in that case,
936 * some old C libraries (like SunOS 4.1.x) coredump instead. On
937 * failure realloc is supposed to return NULL without damaging the
938 * existing allocation. Note that the positions beyond res->ntups are
939 * garbage, not necessarily NULL.
942 PGresAttValue **newTuples;
945 * Since we use integers for row numbers, we can't support more than
946 * INT_MAX rows. Make sure we allow that many, though.
948 if (res->tupArrSize <= INT_MAX / 2)
949 newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
950 else if (res->tupArrSize < INT_MAX)
954 *errmsgp = libpq_gettext("PGresult cannot support more than INT_MAX tuples");
959 * Also, on 32-bit platforms we could, in theory, overflow size_t even
960 * before newSize gets to INT_MAX. (In practice we'd doubtless hit
961 * OOM long before that, but let's check.)
963 #if INT_MAX >= (SIZE_MAX / 2)
964 if (newSize > SIZE_MAX / sizeof(PGresAttValue *))
966 *errmsgp = libpq_gettext("size_t overflow");
971 if (res->tuples == NULL)
972 newTuples = (PGresAttValue **)
973 malloc(newSize * sizeof(PGresAttValue *));
975 newTuples = (PGresAttValue **)
976 realloc(res->tuples, newSize * sizeof(PGresAttValue *));
978 return false; /* malloc or realloc failed */
980 (newSize - res->tupArrSize) * sizeof(PGresAttValue *);
981 res->tupArrSize = newSize;
982 res->tuples = newTuples;
984 res->tuples[res->ntups] = tup;
990 * pqSaveMessageField - save one field of an error or notice message
993 pqSaveMessageField(PGresult *res, char code, const char *value)
995 PGMessageField *pfield;
997 pfield = (PGMessageField *)
999 offsetof(PGMessageField, contents) +
1003 return; /* out of memory? */
1004 pfield->code = code;
1005 strcpy(pfield->contents, value);
1006 pfield->next = res->errFields;
1007 res->errFields = pfield;
1011 * pqSaveParameterStatus - remember parameter status sent by backend
1014 pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
1016 pgParameterStatus *pstatus;
1017 pgParameterStatus *prev;
1020 fprintf(conn->Pfdebug, "pqSaveParameterStatus: '%s' = '%s'\n",
1024 * Forget any old information about the parameter
1026 for (pstatus = conn->pstatus, prev = NULL;
1028 prev = pstatus, pstatus = pstatus->next)
1030 if (strcmp(pstatus->name, name) == 0)
1033 prev->next = pstatus->next;
1035 conn->pstatus = pstatus->next;
1036 free(pstatus); /* frees name and value strings too */
1042 * Store new info as a single malloc block
1044 pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
1045 strlen(name) + strlen(value) + 2);
1050 ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
1051 pstatus->name = ptr;
1053 ptr += strlen(name) + 1;
1054 pstatus->value = ptr;
1056 pstatus->next = conn->pstatus;
1057 conn->pstatus = pstatus;
1061 * Special hacks: remember client_encoding and
1062 * standard_conforming_strings, and convert server version to a numeric
1063 * form. We keep the first two of these in static variables as well, so
1064 * that PQescapeString and PQescapeBytea can behave somewhat sanely (at
1065 * least in single-connection-using programs).
1067 if (strcmp(name, "client_encoding") == 0)
1069 conn->client_encoding = pg_char_to_encoding(value);
1070 /* if we don't recognize the encoding name, fall back to SQL_ASCII */
1071 if (conn->client_encoding < 0)
1072 conn->client_encoding = PG_SQL_ASCII;
1073 static_client_encoding = conn->client_encoding;
1075 else if (strcmp(name, "standard_conforming_strings") == 0)
1077 conn->std_strings = (strcmp(value, "on") == 0);
1078 static_std_strings = conn->std_strings;
1080 else if (strcmp(name, "server_version") == 0)
1087 cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
1091 /* old style, e.g. 9.6.1 */
1092 conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
1098 /* new style, e.g. 10.1 */
1099 conn->sversion = 100 * 100 * vmaj + vmin;
1103 /* old style without minor version, e.g. 9.6devel */
1104 conn->sversion = (100 * vmaj + vmin) * 100;
1109 /* new style without minor version, e.g. 10devel */
1110 conn->sversion = 100 * 100 * vmaj;
1113 conn->sversion = 0; /* unknown */
1120 * Add the received row to the current async result (conn->result).
1121 * Returns 1 if OK, 0 if error occurred.
1123 * On error, *errmsgp can be set to an error string to be returned.
1124 * If it is left NULL, the error is presumed to be "out of memory".
1126 * In single-row mode, we create a new result holding just the current row,
1127 * stashing the previous result in conn->next_result so that it becomes
1128 * active again after pqPrepareAsyncResult(). This allows the result metadata
1129 * (column descriptions) to be carried forward to each result row.
1132 pqRowProcessor(PGconn *conn, const char **errmsgp)
1134 PGresult *res = conn->result;
1135 int nfields = res->numAttributes;
1136 const PGdataValue *columns = conn->rowBuf;
1141 * In single-row mode, make a new PGresult that will hold just this one
1142 * row; the original conn->result is left unchanged so that it can be used
1143 * again as the template for future rows.
1145 if (conn->singleRowMode)
1147 /* Copy everything that should be in the result at this point */
1148 res = PQcopyResult(res,
1149 PG_COPYRES_ATTRS | PG_COPYRES_EVENTS |
1150 PG_COPYRES_NOTICEHOOKS);
1156 * Basically we just allocate space in the PGresult for each field and
1157 * copy the data over.
1159 * Note: on malloc failure, we return 0 leaving *errmsgp still NULL, which
1160 * caller will take to mean "out of memory". This is preferable to trying
1161 * to set up such a message here, because evidently there's not enough
1162 * memory for gettext() to do anything.
1164 tup = (PGresAttValue *)
1165 pqResultAlloc(res, nfields * sizeof(PGresAttValue), true);
1169 for (i = 0; i < nfields; i++)
1171 int clen = columns[i].len;
1176 tup[i].len = NULL_LEN;
1177 tup[i].value = res->null_field;
1181 bool isbinary = (res->attDescs[i].format != 0);
1184 val = (char *) pqResultAlloc(res, clen + 1, isbinary);
1188 /* copy and zero-terminate the data (even if it's binary) */
1189 memcpy(val, columns[i].value, clen);
1197 /* And add the tuple to the PGresult's tuple array */
1198 if (!pqAddTuple(res, tup, errmsgp))
1202 * Success. In single-row mode, make the result available to the client
1205 if (conn->singleRowMode)
1207 /* Change result status to special single-row value */
1208 res->resultStatus = PGRES_SINGLE_TUPLE;
1209 /* Stash old result for re-use later */
1210 conn->next_result = conn->result;
1212 /* And mark the result ready to return */
1213 conn->asyncStatus = PGASYNC_READY;
1219 /* release locally allocated PGresult, if we made one */
1220 if (res != conn->result)
1228 * Submit a query, but don't wait for it to finish
1230 * Returns: 1 if successfully submitted
1231 * 0 if error (conn->errorMessage is set)
1234 PQsendQuery(PGconn *conn, const char *query)
1236 if (!PQsendQueryStart(conn))
1239 /* check the argument */
1242 printfPQExpBuffer(&conn->errorMessage,
1243 libpq_gettext("command string is a null pointer\n"));
1247 /* construct the outgoing Query message */
1248 if (pqPutMsgStart('Q', false, conn) < 0 ||
1249 pqPuts(query, conn) < 0 ||
1250 pqPutMsgEnd(conn) < 0)
1252 /* error message should be set up already */
1256 /* remember we are using simple query protocol */
1257 conn->queryclass = PGQUERY_SIMPLE;
1259 /* and remember the query text too, if possible */
1260 /* if insufficient memory, last_query just winds up NULL */
1261 if (conn->last_query)
1262 free(conn->last_query);
1263 conn->last_query = strdup(query);
1266 * Give the data a push. In nonblock mode, don't complain if we're unable
1267 * to send it all; PQgetResult() will do any additional flushing needed.
1269 if (pqFlush(conn) < 0)
1271 /* error message should be set up already */
1275 /* OK, it's launched! */
1276 conn->asyncStatus = PGASYNC_BUSY;
1282 * Like PQsendQuery, but use protocol 3.0 so we can pass parameters
1285 PQsendQueryParams(PGconn *conn,
1286 const char *command,
1288 const Oid *paramTypes,
1289 const char *const *paramValues,
1290 const int *paramLengths,
1291 const int *paramFormats,
1294 if (!PQsendQueryStart(conn))
1297 /* check the arguments */
1300 printfPQExpBuffer(&conn->errorMessage,
1301 libpq_gettext("command string is a null pointer\n"));
1304 if (nParams < 0 || nParams > 65535)
1306 printfPQExpBuffer(&conn->errorMessage,
1307 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1311 return PQsendQueryGuts(conn,
1313 "", /* use unnamed statement */
1324 * Submit a Parse message, but don't wait for it to finish
1326 * Returns: 1 if successfully submitted
1327 * 0 if error (conn->errorMessage is set)
1330 PQsendPrepare(PGconn *conn,
1331 const char *stmtName, const char *query,
1332 int nParams, const Oid *paramTypes)
1334 if (!PQsendQueryStart(conn))
1337 /* check the arguments */
1340 printfPQExpBuffer(&conn->errorMessage,
1341 libpq_gettext("statement name is a null pointer\n"));
1346 printfPQExpBuffer(&conn->errorMessage,
1347 libpq_gettext("command string is a null pointer\n"));
1350 if (nParams < 0 || nParams > 65535)
1352 printfPQExpBuffer(&conn->errorMessage,
1353 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1357 /* This isn't gonna work on a 2.0 server */
1358 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1360 printfPQExpBuffer(&conn->errorMessage,
1361 libpq_gettext("function requires at least protocol version 3.0\n"));
1365 /* construct the Parse message */
1366 if (pqPutMsgStart('P', false, conn) < 0 ||
1367 pqPuts(stmtName, conn) < 0 ||
1368 pqPuts(query, conn) < 0)
1371 if (nParams > 0 && paramTypes)
1375 if (pqPutInt(nParams, 2, conn) < 0)
1377 for (i = 0; i < nParams; i++)
1379 if (pqPutInt(paramTypes[i], 4, conn) < 0)
1385 if (pqPutInt(0, 2, conn) < 0)
1388 if (pqPutMsgEnd(conn) < 0)
1391 /* construct the Sync message */
1392 if (pqPutMsgStart('S', false, conn) < 0 ||
1393 pqPutMsgEnd(conn) < 0)
1396 /* remember we are doing just a Parse */
1397 conn->queryclass = PGQUERY_PREPARE;
1399 /* and remember the query text too, if possible */
1400 /* if insufficient memory, last_query just winds up NULL */
1401 if (conn->last_query)
1402 free(conn->last_query);
1403 conn->last_query = strdup(query);
1406 * Give the data a push. In nonblock mode, don't complain if we're unable
1407 * to send it all; PQgetResult() will do any additional flushing needed.
1409 if (pqFlush(conn) < 0)
1412 /* OK, it's launched! */
1413 conn->asyncStatus = PGASYNC_BUSY;
1417 /* error message should be set up already */
1422 * PQsendQueryPrepared
1423 * Like PQsendQuery, but execute a previously prepared statement,
1424 * using protocol 3.0 so we can pass parameters
1427 PQsendQueryPrepared(PGconn *conn,
1428 const char *stmtName,
1430 const char *const *paramValues,
1431 const int *paramLengths,
1432 const int *paramFormats,
1435 if (!PQsendQueryStart(conn))
1438 /* check the arguments */
1441 printfPQExpBuffer(&conn->errorMessage,
1442 libpq_gettext("statement name is a null pointer\n"));
1445 if (nParams < 0 || nParams > 65535)
1447 printfPQExpBuffer(&conn->errorMessage,
1448 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1452 return PQsendQueryGuts(conn,
1453 NULL, /* no command to parse */
1456 NULL, /* no param types */
1464 * Common startup code for PQsendQuery and sibling routines
1467 PQsendQueryStart(PGconn *conn)
1472 /* clear the error string */
1473 resetPQExpBuffer(&conn->errorMessage);
1475 /* Don't try to send if we know there's no live connection. */
1476 if (conn->status != CONNECTION_OK)
1478 printfPQExpBuffer(&conn->errorMessage,
1479 libpq_gettext("no connection to the server\n"));
1482 /* Can't send while already busy, either. */
1483 if (conn->asyncStatus != PGASYNC_IDLE)
1485 printfPQExpBuffer(&conn->errorMessage,
1486 libpq_gettext("another command is already in progress\n"));
1490 /* initialize async result-accumulation state */
1491 pqClearAsyncResult(conn);
1493 /* reset single-row processing mode */
1494 conn->singleRowMode = false;
1496 /* ready to send command message */
1502 * Common code for protocol-3.0 query sending
1503 * PQsendQueryStart should be done already
1505 * command may be NULL to indicate we use an already-prepared statement
1508 PQsendQueryGuts(PGconn *conn,
1509 const char *command,
1510 const char *stmtName,
1512 const Oid *paramTypes,
1513 const char *const *paramValues,
1514 const int *paramLengths,
1515 const int *paramFormats,
1520 /* This isn't gonna work on a 2.0 server */
1521 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1523 printfPQExpBuffer(&conn->errorMessage,
1524 libpq_gettext("function requires at least protocol version 3.0\n"));
1529 * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync,
1530 * using specified statement name and the unnamed portal.
1535 /* construct the Parse message */
1536 if (pqPutMsgStart('P', false, conn) < 0 ||
1537 pqPuts(stmtName, conn) < 0 ||
1538 pqPuts(command, conn) < 0)
1540 if (nParams > 0 && paramTypes)
1542 if (pqPutInt(nParams, 2, conn) < 0)
1544 for (i = 0; i < nParams; i++)
1546 if (pqPutInt(paramTypes[i], 4, conn) < 0)
1552 if (pqPutInt(0, 2, conn) < 0)
1555 if (pqPutMsgEnd(conn) < 0)
1559 /* Construct the Bind message */
1560 if (pqPutMsgStart('B', false, conn) < 0 ||
1561 pqPuts("", conn) < 0 ||
1562 pqPuts(stmtName, conn) < 0)
1565 /* Send parameter formats */
1566 if (nParams > 0 && paramFormats)
1568 if (pqPutInt(nParams, 2, conn) < 0)
1570 for (i = 0; i < nParams; i++)
1572 if (pqPutInt(paramFormats[i], 2, conn) < 0)
1578 if (pqPutInt(0, 2, conn) < 0)
1582 if (pqPutInt(nParams, 2, conn) < 0)
1585 /* Send parameters */
1586 for (i = 0; i < nParams; i++)
1588 if (paramValues && paramValues[i])
1592 if (paramFormats && paramFormats[i] != 0)
1594 /* binary parameter */
1596 nbytes = paramLengths[i];
1599 printfPQExpBuffer(&conn->errorMessage,
1600 libpq_gettext("length must be given for binary parameter\n"));
1606 /* text parameter, do not use paramLengths */
1607 nbytes = strlen(paramValues[i]);
1609 if (pqPutInt(nbytes, 4, conn) < 0 ||
1610 pqPutnchar(paramValues[i], nbytes, conn) < 0)
1615 /* take the param as NULL */
1616 if (pqPutInt(-1, 4, conn) < 0)
1620 if (pqPutInt(1, 2, conn) < 0 ||
1621 pqPutInt(resultFormat, 2, conn))
1623 if (pqPutMsgEnd(conn) < 0)
1626 /* construct the Describe Portal message */
1627 if (pqPutMsgStart('D', false, conn) < 0 ||
1628 pqPutc('P', conn) < 0 ||
1629 pqPuts("", conn) < 0 ||
1630 pqPutMsgEnd(conn) < 0)
1633 /* construct the Execute message */
1634 if (pqPutMsgStart('E', false, conn) < 0 ||
1635 pqPuts("", conn) < 0 ||
1636 pqPutInt(0, 4, conn) < 0 ||
1637 pqPutMsgEnd(conn) < 0)
1640 /* construct the Sync message */
1641 if (pqPutMsgStart('S', false, conn) < 0 ||
1642 pqPutMsgEnd(conn) < 0)
1645 /* remember we are using extended query protocol */
1646 conn->queryclass = PGQUERY_EXTENDED;
1648 /* and remember the query text too, if possible */
1649 /* if insufficient memory, last_query just winds up NULL */
1650 if (conn->last_query)
1651 free(conn->last_query);
1653 conn->last_query = strdup(command);
1655 conn->last_query = NULL;
1658 * Give the data a push. In nonblock mode, don't complain if we're unable
1659 * to send it all; PQgetResult() will do any additional flushing needed.
1661 if (pqFlush(conn) < 0)
1664 /* OK, it's launched! */
1665 conn->asyncStatus = PGASYNC_BUSY;
1669 /* error message should be set up already */
1674 * Select row-by-row processing mode
1677 PQsetSingleRowMode(PGconn *conn)
1680 * Only allow setting the flag when we have launched a query and not yet
1681 * received any results.
1685 if (conn->asyncStatus != PGASYNC_BUSY)
1687 if (conn->queryclass != PGQUERY_SIMPLE &&
1688 conn->queryclass != PGQUERY_EXTENDED)
1694 conn->singleRowMode = true;
1699 * Consume any available input from the backend
1700 * 0 return: some kind of trouble
1701 * 1 return: no problem
1704 PQconsumeInput(PGconn *conn)
1710 * for non-blocking connections try to flush the send-queue, otherwise we
1711 * may never get a response for something that may not have already been
1712 * sent because it's in our write buffer!
1714 if (pqIsnonblocking(conn))
1716 if (pqFlush(conn) < 0)
1721 * Load more data, if available. We do this no matter what state we are
1722 * in, since we are probably getting called because the application wants
1723 * to get rid of a read-select condition. Note that we will NOT block
1724 * waiting for more input.
1726 if (pqReadData(conn) < 0)
1729 /* Parsing of the data waits till later. */
1735 * parseInput: if appropriate, parse input data from backend
1736 * until input is exhausted or a stopping state is reached.
1737 * Note that this function will NOT attempt to read more data from the backend.
1740 parseInput(PGconn *conn)
1742 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1743 pqParseInput3(conn);
1745 pqParseInput2(conn);
1750 * Return true if PQgetResult would block waiting for input.
1754 PQisBusy(PGconn *conn)
1759 /* Parse any available data, if our state permits. */
1763 * PQgetResult will return immediately in all states except BUSY, or if we
1764 * had a write failure.
1766 return conn->asyncStatus == PGASYNC_BUSY || conn->write_failed;
1772 * Get the next PGresult produced by a query. Returns NULL if no
1773 * query work remains or an error has occurred (e.g. out of
1778 PQgetResult(PGconn *conn)
1785 /* Parse any available data, if our state permits. */
1788 /* If not ready to return something, block until we are. */
1789 while (conn->asyncStatus == PGASYNC_BUSY)
1794 * If data remains unsent, send it. Else we might be waiting for the
1795 * result of a command the backend hasn't even got yet.
1797 while ((flushResult = pqFlush(conn)) > 0)
1799 if (pqWait(false, true, conn))
1807 * Wait for some more data, and load it. (Note: if the connection has
1808 * been lost, pqWait should return immediately because the socket
1809 * should be read-ready, either with the last server data or with an
1810 * EOF indication. We expect therefore that this won't result in any
1811 * undue delay in reporting a previous write failure.)
1814 pqWait(true, false, conn) ||
1815 pqReadData(conn) < 0)
1818 * conn->errorMessage has been set by pqWait or pqReadData. We
1819 * want to append it to any already-received error message.
1821 pqSaveErrorResult(conn);
1822 conn->asyncStatus = PGASYNC_IDLE;
1823 return pqPrepareAsyncResult(conn);
1830 * If we had a write error, but nothing above obtained a query result
1831 * or detected a read error, report the write error.
1833 if (conn->write_failed && conn->asyncStatus == PGASYNC_BUSY)
1835 pqSaveWriteError(conn);
1836 conn->asyncStatus = PGASYNC_IDLE;
1837 return pqPrepareAsyncResult(conn);
1841 /* Return the appropriate thing. */
1842 switch (conn->asyncStatus)
1845 res = NULL; /* query is complete */
1848 res = pqPrepareAsyncResult(conn);
1849 /* Set the state back to BUSY, allowing parsing to proceed. */
1850 conn->asyncStatus = PGASYNC_BUSY;
1852 case PGASYNC_COPY_IN:
1853 res = getCopyResult(conn, PGRES_COPY_IN);
1855 case PGASYNC_COPY_OUT:
1856 res = getCopyResult(conn, PGRES_COPY_OUT);
1858 case PGASYNC_COPY_BOTH:
1859 res = getCopyResult(conn, PGRES_COPY_BOTH);
1862 printfPQExpBuffer(&conn->errorMessage,
1863 libpq_gettext("unexpected asyncStatus: %d\n"),
1864 (int) conn->asyncStatus);
1865 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1873 for (i = 0; i < res->nEvents; i++)
1875 PGEventResultCreate evt;
1879 if (!res->events[i].proc(PGEVT_RESULTCREATE, &evt,
1880 res->events[i].passThrough))
1882 printfPQExpBuffer(&conn->errorMessage,
1883 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_RESULTCREATE event\n"),
1884 res->events[i].name);
1885 pqSetResultError(res, conn->errorMessage.data);
1886 res->resultStatus = PGRES_FATAL_ERROR;
1889 res->events[i].resultInitialized = true;
1898 * Helper for PQgetResult: generate result for COPY-in-progress cases
1901 getCopyResult(PGconn *conn, ExecStatusType copytype)
1904 * If the server connection has been lost, don't pretend everything is
1905 * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
1906 * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
1907 * error in the earlier steps in PQgetResult). The text returned in the
1908 * result is whatever is in conn->errorMessage; we hope that was filled
1909 * with something relevant when the lost connection was detected.
1911 if (conn->status != CONNECTION_OK)
1913 pqSaveErrorResult(conn);
1914 conn->asyncStatus = PGASYNC_IDLE;
1915 return pqPrepareAsyncResult(conn);
1918 /* If we have an async result for the COPY, return that */
1919 if (conn->result && conn->result->resultStatus == copytype)
1920 return pqPrepareAsyncResult(conn);
1922 /* Otherwise, invent a suitable PGresult */
1923 return PQmakeEmptyPGresult(conn, copytype);
1929 * send a query to the backend and package up the result in a PGresult
1931 * If the query was not even sent, return NULL; conn->errorMessage is set to
1932 * a relevant message.
1933 * If the query was sent, a new PGresult is returned (which could indicate
1934 * either success or failure).
1935 * The user is responsible for freeing the PGresult via PQclear()
1936 * when done with it.
1939 PQexec(PGconn *conn, const char *query)
1941 if (!PQexecStart(conn))
1943 if (!PQsendQuery(conn, query))
1945 return PQexecFinish(conn);
1950 * Like PQexec, but use protocol 3.0 so we can pass parameters
1953 PQexecParams(PGconn *conn,
1954 const char *command,
1956 const Oid *paramTypes,
1957 const char *const *paramValues,
1958 const int *paramLengths,
1959 const int *paramFormats,
1962 if (!PQexecStart(conn))
1964 if (!PQsendQueryParams(conn, command,
1965 nParams, paramTypes, paramValues, paramLengths,
1966 paramFormats, resultFormat))
1968 return PQexecFinish(conn);
1973 * Creates a prepared statement by issuing a v3.0 parse message.
1975 * If the query was not even sent, return NULL; conn->errorMessage is set to
1976 * a relevant message.
1977 * If the query was sent, a new PGresult is returned (which could indicate
1978 * either success or failure).
1979 * The user is responsible for freeing the PGresult via PQclear()
1980 * when done with it.
1983 PQprepare(PGconn *conn,
1984 const char *stmtName, const char *query,
1985 int nParams, const Oid *paramTypes)
1987 if (!PQexecStart(conn))
1989 if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
1991 return PQexecFinish(conn);
1996 * Like PQexec, but execute a previously prepared statement,
1997 * using protocol 3.0 so we can pass parameters
2000 PQexecPrepared(PGconn *conn,
2001 const char *stmtName,
2003 const char *const *paramValues,
2004 const int *paramLengths,
2005 const int *paramFormats,
2008 if (!PQexecStart(conn))
2010 if (!PQsendQueryPrepared(conn, stmtName,
2011 nParams, paramValues, paramLengths,
2012 paramFormats, resultFormat))
2014 return PQexecFinish(conn);
2018 * Common code for PQexec and sibling routines: prepare to send command
2021 PQexecStart(PGconn *conn)
2029 * Silently discard any prior query result that application didn't eat.
2030 * This is probably poor design, but it's here for backward compatibility.
2032 while ((result = PQgetResult(conn)) != NULL)
2034 ExecStatusType resultStatus = result->resultStatus;
2036 PQclear(result); /* only need its status */
2037 if (resultStatus == PGRES_COPY_IN)
2039 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2041 /* In protocol 3, we can get out of a COPY IN state */
2042 if (PQputCopyEnd(conn,
2043 libpq_gettext("COPY terminated by new PQexec")) < 0)
2045 /* keep waiting to swallow the copy's failure message */
2049 /* In older protocols we have to punt */
2050 printfPQExpBuffer(&conn->errorMessage,
2051 libpq_gettext("COPY IN state must be terminated first\n"));
2055 else if (resultStatus == PGRES_COPY_OUT)
2057 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2060 * In protocol 3, we can get out of a COPY OUT state: we just
2061 * switch back to BUSY and allow the remaining COPY data to be
2062 * dropped on the floor.
2064 conn->asyncStatus = PGASYNC_BUSY;
2065 /* keep waiting to swallow the copy's completion message */
2069 /* In older protocols we have to punt */
2070 printfPQExpBuffer(&conn->errorMessage,
2071 libpq_gettext("COPY OUT state must be terminated first\n"));
2075 else if (resultStatus == PGRES_COPY_BOTH)
2077 /* We don't allow PQexec during COPY BOTH */
2078 printfPQExpBuffer(&conn->errorMessage,
2079 libpq_gettext("PQexec not allowed during COPY BOTH\n"));
2082 /* check for loss of connection, too */
2083 if (conn->status == CONNECTION_BAD)
2087 /* OK to send a command */
2092 * Common code for PQexec and sibling routines: wait for command result
2095 PQexecFinish(PGconn *conn)
2098 PGresult *lastResult;
2101 * For backwards compatibility, return the last result if there are more
2102 * than one --- but merge error messages if we get more than one error
2105 * We have to stop if we see copy in/out/both, however. We will resume
2106 * parsing after application performs the data transfer.
2108 * Also stop if the connection is lost (else we'll loop infinitely).
2111 while ((result = PQgetResult(conn)) != NULL)
2115 if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
2116 result->resultStatus == PGRES_FATAL_ERROR)
2118 pqCatenateResultError(lastResult, result->errMsg);
2120 result = lastResult;
2123 * Make sure PQerrorMessage agrees with concatenated result
2125 resetPQExpBuffer(&conn->errorMessage);
2126 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
2129 PQclear(lastResult);
2131 lastResult = result;
2132 if (result->resultStatus == PGRES_COPY_IN ||
2133 result->resultStatus == PGRES_COPY_OUT ||
2134 result->resultStatus == PGRES_COPY_BOTH ||
2135 conn->status == CONNECTION_BAD)
2143 * PQdescribePrepared
2144 * Obtain information about a previously prepared statement
2146 * If the query was not even sent, return NULL; conn->errorMessage is set to
2147 * a relevant message.
2148 * If the query was sent, a new PGresult is returned (which could indicate
2149 * either success or failure). On success, the PGresult contains status
2150 * PGRES_COMMAND_OK, and its parameter and column-heading fields describe
2151 * the statement's inputs and outputs respectively.
2152 * The user is responsible for freeing the PGresult via PQclear()
2153 * when done with it.
2156 PQdescribePrepared(PGconn *conn, const char *stmt)
2158 if (!PQexecStart(conn))
2160 if (!PQsendDescribe(conn, 'S', stmt))
2162 return PQexecFinish(conn);
2167 * Obtain information about a previously created portal
2169 * This is much like PQdescribePrepared, except that no parameter info is
2170 * returned. Note that at the moment, libpq doesn't really expose portals
2171 * to the client; but this can be used with a portal created by a SQL
2172 * DECLARE CURSOR command.
2175 PQdescribePortal(PGconn *conn, const char *portal)
2177 if (!PQexecStart(conn))
2179 if (!PQsendDescribe(conn, 'P', portal))
2181 return PQexecFinish(conn);
2185 * PQsendDescribePrepared
2186 * Submit a Describe Statement command, but don't wait for it to finish
2188 * Returns: 1 if successfully submitted
2189 * 0 if error (conn->errorMessage is set)
2192 PQsendDescribePrepared(PGconn *conn, const char *stmt)
2194 return PQsendDescribe(conn, 'S', stmt);
2198 * PQsendDescribePortal
2199 * Submit a Describe Portal command, but don't wait for it to finish
2201 * Returns: 1 if successfully submitted
2202 * 0 if error (conn->errorMessage is set)
2205 PQsendDescribePortal(PGconn *conn, const char *portal)
2207 return PQsendDescribe(conn, 'P', portal);
2212 * Common code to send a Describe command
2214 * Available options for desc_type are
2215 * 'S' to describe a prepared statement; or
2216 * 'P' to describe a portal.
2217 * Returns 1 on success and 0 on failure.
2220 PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
2222 /* Treat null desc_target as empty string */
2226 if (!PQsendQueryStart(conn))
2229 /* This isn't gonna work on a 2.0 server */
2230 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2232 printfPQExpBuffer(&conn->errorMessage,
2233 libpq_gettext("function requires at least protocol version 3.0\n"));
2237 /* construct the Describe message */
2238 if (pqPutMsgStart('D', false, conn) < 0 ||
2239 pqPutc(desc_type, conn) < 0 ||
2240 pqPuts(desc_target, conn) < 0 ||
2241 pqPutMsgEnd(conn) < 0)
2244 /* construct the Sync message */
2245 if (pqPutMsgStart('S', false, conn) < 0 ||
2246 pqPutMsgEnd(conn) < 0)
2249 /* remember we are doing a Describe */
2250 conn->queryclass = PGQUERY_DESCRIBE;
2252 /* reset last_query string (not relevant now) */
2253 if (conn->last_query)
2255 free(conn->last_query);
2256 conn->last_query = NULL;
2260 * Give the data a push. In nonblock mode, don't complain if we're unable
2261 * to send it all; PQgetResult() will do any additional flushing needed.
2263 if (pqFlush(conn) < 0)
2266 /* OK, it's launched! */
2267 conn->asyncStatus = PGASYNC_BUSY;
2271 /* error message should be set up already */
2277 * returns a PGnotify* structure of the latest async notification
2278 * that has not yet been handled
2280 * returns NULL, if there is currently
2281 * no unhandled async notification from the backend
2283 * the CALLER is responsible for FREE'ing the structure returned
2285 * Note that this function does not read any new data from the socket;
2286 * so usually, caller should call PQconsumeInput() first.
2289 PQnotifies(PGconn *conn)
2296 /* Parse any available data to see if we can extract NOTIFY messages. */
2299 event = conn->notifyHead;
2302 conn->notifyHead = event->next;
2303 if (!conn->notifyHead)
2304 conn->notifyTail = NULL;
2305 event->next = NULL; /* don't let app see the internal state */
2311 * PQputCopyData - send some data to the backend during COPY IN or COPY BOTH
2313 * Returns 1 if successful, 0 if data could not be sent (only possible
2314 * in nonblock mode), or -1 if an error occurs.
2317 PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
2321 if (conn->asyncStatus != PGASYNC_COPY_IN &&
2322 conn->asyncStatus != PGASYNC_COPY_BOTH)
2324 printfPQExpBuffer(&conn->errorMessage,
2325 libpq_gettext("no COPY in progress\n"));
2330 * Process any NOTICE or NOTIFY messages that might be pending in the
2331 * input buffer. Since the server might generate many notices during the
2332 * COPY, we want to clean those out reasonably promptly to prevent
2333 * indefinite expansion of the input buffer. (Note: the actual read of
2334 * input data into the input buffer happens down inside pqSendSome, but
2335 * it's not authorized to get rid of the data again.)
2342 * Try to flush any previously sent data in preference to growing the
2343 * output buffer. If we can't enlarge the buffer enough to hold the
2344 * data, return 0 in the nonblock case, else hard error. (For
2345 * simplicity, always assume 5 bytes of overhead even in protocol 2.0
2348 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2350 if (pqFlush(conn) < 0)
2352 if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2354 return pqIsnonblocking(conn) ? 0 : -1;
2356 /* Send the data (too simple to delegate to fe-protocol files) */
2357 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2359 if (pqPutMsgStart('d', false, conn) < 0 ||
2360 pqPutnchar(buffer, nbytes, conn) < 0 ||
2361 pqPutMsgEnd(conn) < 0)
2366 if (pqPutMsgStart(0, false, conn) < 0 ||
2367 pqPutnchar(buffer, nbytes, conn) < 0 ||
2368 pqPutMsgEnd(conn) < 0)
2376 * PQputCopyEnd - send EOF indication to the backend during COPY IN
2378 * After calling this, use PQgetResult() to check command completion status.
2380 * Returns 1 if successful, 0 if data could not be sent (only possible
2381 * in nonblock mode), or -1 if an error occurs.
2384 PQputCopyEnd(PGconn *conn, const char *errormsg)
2388 if (conn->asyncStatus != PGASYNC_COPY_IN &&
2389 conn->asyncStatus != PGASYNC_COPY_BOTH)
2391 printfPQExpBuffer(&conn->errorMessage,
2392 libpq_gettext("no COPY in progress\n"));
2397 * Send the COPY END indicator. This is simple enough that we don't
2398 * bother delegating it to the fe-protocol files.
2400 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2404 /* Send COPY FAIL */
2405 if (pqPutMsgStart('f', false, conn) < 0 ||
2406 pqPuts(errormsg, conn) < 0 ||
2407 pqPutMsgEnd(conn) < 0)
2412 /* Send COPY DONE */
2413 if (pqPutMsgStart('c', false, conn) < 0 ||
2414 pqPutMsgEnd(conn) < 0)
2419 * If we sent the COPY command in extended-query mode, we must issue a
2422 if (conn->queryclass != PGQUERY_SIMPLE)
2424 if (pqPutMsgStart('S', false, conn) < 0 ||
2425 pqPutMsgEnd(conn) < 0)
2433 /* Oops, no way to do this in 2.0 */
2434 printfPQExpBuffer(&conn->errorMessage,
2435 libpq_gettext("function requires at least protocol version 3.0\n"));
2440 /* Send old-style end-of-data marker */
2441 if (pqPutMsgStart(0, false, conn) < 0 ||
2442 pqPutnchar("\\.\n", 3, conn) < 0 ||
2443 pqPutMsgEnd(conn) < 0)
2448 /* Return to active duty */
2449 if (conn->asyncStatus == PGASYNC_COPY_BOTH)
2450 conn->asyncStatus = PGASYNC_COPY_OUT;
2452 conn->asyncStatus = PGASYNC_BUSY;
2453 resetPQExpBuffer(&conn->errorMessage);
2455 /* Try to flush data */
2456 if (pqFlush(conn) < 0)
2463 * PQgetCopyData - read a row of data from the backend during COPY OUT
2466 * If successful, sets *buffer to point to a malloc'd row of data, and
2467 * returns row length (always > 0) as result.
2468 * Returns 0 if no row available yet (only possible if async is true),
2469 * -1 if end of copy (consult PQgetResult), or -2 if error (consult
2473 PQgetCopyData(PGconn *conn, char **buffer, int async)
2475 *buffer = NULL; /* for all failure cases */
2478 if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2479 conn->asyncStatus != PGASYNC_COPY_BOTH)
2481 printfPQExpBuffer(&conn->errorMessage,
2482 libpq_gettext("no COPY in progress\n"));
2485 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2486 return pqGetCopyData3(conn, buffer, async);
2488 return pqGetCopyData2(conn, buffer, async);
2492 * PQgetline - gets a newline-terminated string from the backend.
2494 * Chiefly here so that applications can use "COPY <rel> to stdout"
2495 * and read the output string. Returns a null-terminated string in s.
2497 * XXX this routine is now deprecated, because it can't handle binary data.
2498 * If called during a COPY BINARY we return EOF.
2500 * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
2501 * the terminating \n (like gets(3)).
2503 * CAUTION: the caller is responsible for detecting the end-of-copy signal
2504 * (a line containing just "\.") when using this routine.
2507 * EOF if error (eg, invalid arguments are given)
2508 * 0 if EOL is reached (i.e., \n has been read)
2509 * (this is required for backward-compatibility -- this
2510 * routine used to always return EOF or 0, assuming that
2511 * the line ended within maxlen bytes.)
2512 * 1 in other cases (i.e., the buffer was filled before \n is reached)
2515 PQgetline(PGconn *conn, char *s, int maxlen)
2517 if (!s || maxlen <= 0)
2520 /* maxlen must be at least 3 to hold the \. terminator! */
2527 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2528 return pqGetline3(conn, s, maxlen);
2530 return pqGetline2(conn, s, maxlen);
2534 * PQgetlineAsync - gets a COPY data row without blocking.
2536 * This routine is for applications that want to do "COPY <rel> to stdout"
2537 * asynchronously, that is without blocking. Having issued the COPY command
2538 * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
2539 * and this routine until the end-of-data signal is detected. Unlike
2540 * PQgetline, this routine takes responsibility for detecting end-of-data.
2542 * On each call, PQgetlineAsync will return data if a complete data row
2543 * is available in libpq's input buffer. Otherwise, no data is returned
2544 * until the rest of the row arrives.
2546 * If -1 is returned, the end-of-data signal has been recognized (and removed
2547 * from libpq's input buffer). The caller *must* next call PQendcopy and
2548 * then return to normal processing.
2551 * -1 if the end-of-copy-data marker has been recognized
2552 * 0 if no data is available
2553 * >0 the number of bytes returned.
2555 * The data returned will not extend beyond a data-row boundary. If possible
2556 * a whole row will be returned at one time. But if the buffer offered by
2557 * the caller is too small to hold a row sent by the backend, then a partial
2558 * data row will be returned. In text mode this can be detected by testing
2559 * whether the last returned byte is '\n' or not.
2561 * The returned data is *not* null-terminated.
2565 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
2570 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2571 return pqGetlineAsync3(conn, buffer, bufsize);
2573 return pqGetlineAsync2(conn, buffer, bufsize);
2577 * PQputline -- sends a string to the backend during COPY IN.
2578 * Returns 0 if OK, EOF if not.
2580 * This is deprecated primarily because the return convention doesn't allow
2581 * caller to tell the difference between a hard error and a nonblock-mode
2585 PQputline(PGconn *conn, const char *s)
2587 return PQputnbytes(conn, s, strlen(s));
2591 * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
2592 * Returns 0 if OK, EOF if not.
2595 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
2597 if (PQputCopyData(conn, buffer, nbytes) > 0)
2605 * After completing the data transfer portion of a copy in/out,
2606 * the application must call this routine to finish the command protocol.
2608 * When using protocol 3.0 this is deprecated; it's cleaner to use PQgetResult
2609 * to get the transfer status. Note however that when using 2.0 protocol,
2610 * recovering from a copy failure often requires a PQreset. PQendcopy will
2611 * take care of that, PQgetResult won't.
2618 PQendcopy(PGconn *conn)
2623 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2624 return pqEndcopy3(conn);
2626 return pqEndcopy2(conn);
2631 * PQfn - Send a function call to the POSTGRES backend.
2633 * conn : backend connection
2634 * fnid : OID of function to be called
2635 * result_buf : pointer to result buffer
2636 * result_len : actual length of result is returned here
2637 * result_is_int : If the result is an integer, this must be 1,
2638 * otherwise this should be 0
2639 * args : pointer to an array of function arguments
2640 * (each has length, if integer, and value/pointer)
2641 * nargs : # of arguments in args array.
2644 * PGresult with status = PGRES_COMMAND_OK if successful.
2645 * *result_len is > 0 if there is a return value, 0 if not.
2646 * PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
2647 * NULL on communications failure. conn->errorMessage will be set.
2657 const PQArgBlock *args,
2665 /* clear the error string */
2666 resetPQExpBuffer(&conn->errorMessage);
2668 if (conn->sock == PGINVALID_SOCKET || conn->asyncStatus != PGASYNC_IDLE ||
2669 conn->result != NULL)
2671 printfPQExpBuffer(&conn->errorMessage,
2672 libpq_gettext("connection in wrong state\n"));
2676 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2677 return pqFunctionCall3(conn, fnid,
2678 result_buf, result_len,
2682 return pqFunctionCall2(conn, fnid,
2683 result_buf, result_len,
2689 /* ====== accessor funcs for PGresult ======== */
2692 PQresultStatus(const PGresult *res)
2695 return PGRES_FATAL_ERROR;
2696 return res->resultStatus;
2700 PQresStatus(ExecStatusType status)
2702 if ((unsigned int) status >= sizeof pgresStatus / sizeof pgresStatus[0])
2703 return libpq_gettext("invalid ExecStatusType code");
2704 return pgresStatus[status];
2708 PQresultErrorMessage(const PGresult *res)
2710 if (!res || !res->errMsg)
2716 PQresultVerboseErrorMessage(const PGresult *res,
2717 PGVerbosity verbosity,
2718 PGContextVisibility show_context)
2720 PQExpBufferData workBuf;
2723 * Because the caller is expected to free the result string, we must
2724 * strdup any constant result. We use plain strdup and document that
2725 * callers should expect NULL if out-of-memory.
2728 (res->resultStatus != PGRES_FATAL_ERROR &&
2729 res->resultStatus != PGRES_NONFATAL_ERROR))
2730 return strdup(libpq_gettext("PGresult is not an error result\n"));
2732 initPQExpBuffer(&workBuf);
2735 * Currently, we pass this off to fe-protocol3.c in all cases; it will
2736 * behave reasonably sanely with an error reported by fe-protocol2.c as
2737 * well. If necessary, we could record the protocol version in PGresults
2738 * so as to be able to invoke a version-specific message formatter, but
2739 * for now there's no need.
2741 pqBuildErrorMessage3(&workBuf, res, verbosity, show_context);
2743 /* If insufficient memory to format the message, fail cleanly */
2744 if (PQExpBufferDataBroken(workBuf))
2746 termPQExpBuffer(&workBuf);
2747 return strdup(libpq_gettext("out of memory\n"));
2750 return workBuf.data;
2754 PQresultErrorField(const PGresult *res, int fieldcode)
2756 PGMessageField *pfield;
2760 for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
2762 if (pfield->code == fieldcode)
2763 return pfield->contents;
2769 PQntuples(const PGresult *res)
2777 PQnfields(const PGresult *res)
2781 return res->numAttributes;
2785 PQbinaryTuples(const PGresult *res)
2793 * Helper routines to range-check field numbers and tuple numbers.
2794 * Return true if OK, false if not
2798 check_field_number(const PGresult *res, int field_num)
2801 return false; /* no way to display error message... */
2802 if (field_num < 0 || field_num >= res->numAttributes)
2804 pqInternalNotice(&res->noticeHooks,
2805 "column number %d is out of range 0..%d",
2806 field_num, res->numAttributes - 1);
2813 check_tuple_field_number(const PGresult *res,
2814 int tup_num, int field_num)
2817 return false; /* no way to display error message... */
2818 if (tup_num < 0 || tup_num >= res->ntups)
2820 pqInternalNotice(&res->noticeHooks,
2821 "row number %d is out of range 0..%d",
2822 tup_num, res->ntups - 1);
2825 if (field_num < 0 || field_num >= res->numAttributes)
2827 pqInternalNotice(&res->noticeHooks,
2828 "column number %d is out of range 0..%d",
2829 field_num, res->numAttributes - 1);
2836 check_param_number(const PGresult *res, int param_num)
2839 return false; /* no way to display error message... */
2840 if (param_num < 0 || param_num >= res->numParameters)
2842 pqInternalNotice(&res->noticeHooks,
2843 "parameter number %d is out of range 0..%d",
2844 param_num, res->numParameters - 1);
2852 * returns NULL if the field_num is invalid
2855 PQfname(const PGresult *res, int field_num)
2857 if (!check_field_number(res, field_num))
2860 return res->attDescs[field_num].name;
2866 * PQfnumber: find column number given column name
2868 * The column name is parsed as if it were in a SQL statement, including
2869 * case-folding and double-quote processing. But note a possible gotcha:
2870 * downcasing in the frontend might follow different locale rules than
2871 * downcasing in the backend...
2873 * Returns -1 if no match. In the present backend it is also possible
2874 * to have multiple matches, in which case the first one is found.
2877 PQfnumber(const PGresult *res, const char *field_name)
2881 bool all_lower = true;
2890 * Note: it is correct to reject a zero-length input string; the proper
2891 * input to match a zero-length field name would be "".
2893 if (field_name == NULL ||
2894 field_name[0] == '\0' ||
2895 res->attDescs == NULL)
2899 * Check if we can avoid the strdup() and related work because the
2900 * passed-in string wouldn't be changed before we do the check anyway.
2902 for (iptr = field_name; *iptr; iptr++)
2906 if (c == '"' || c != pg_tolower((unsigned char) c))
2914 for (i = 0; i < res->numAttributes; i++)
2915 if (strcmp(field_name, res->attDescs[i].name) == 0)
2918 /* Fall through to the normal check if that didn't work out. */
2921 * Note: this code will not reject partially quoted strings, eg
2922 * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
2925 field_case = strdup(field_name);
2926 if (field_case == NULL)
2927 return -1; /* grotty */
2931 for (iptr = field_case; *iptr; iptr++)
2941 /* doubled quotes become a single quote */
2955 c = pg_tolower((unsigned char) c);
2961 for (i = 0; i < res->numAttributes; i++)
2963 if (strcmp(field_case, res->attDescs[i].name) == 0)
2974 PQftable(const PGresult *res, int field_num)
2976 if (!check_field_number(res, field_num))
2979 return res->attDescs[field_num].tableid;
2985 PQftablecol(const PGresult *res, int field_num)
2987 if (!check_field_number(res, field_num))
2990 return res->attDescs[field_num].columnid;
2996 PQfformat(const PGresult *res, int field_num)
2998 if (!check_field_number(res, field_num))
3001 return res->attDescs[field_num].format;
3007 PQftype(const PGresult *res, int field_num)
3009 if (!check_field_number(res, field_num))
3012 return res->attDescs[field_num].typid;
3018 PQfsize(const PGresult *res, int field_num)
3020 if (!check_field_number(res, field_num))
3023 return res->attDescs[field_num].typlen;
3029 PQfmod(const PGresult *res, int field_num)
3031 if (!check_field_number(res, field_num))
3034 return res->attDescs[field_num].atttypmod;
3040 PQcmdStatus(PGresult *res)
3044 return res->cmdStatus;
3049 * if the last command was an INSERT, return the oid string
3053 PQoidStatus(const PGresult *res)
3056 * This must be enough to hold the result. Don't laugh, this is better
3057 * than what this function used to do.
3059 static char buf[24];
3063 if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
3066 len = strspn(res->cmdStatus + 7, "0123456789");
3067 if (len > sizeof(buf) - 1)
3068 len = sizeof(buf) - 1;
3069 memcpy(buf, res->cmdStatus + 7, len);
3077 * a perhaps preferable form of the above which just returns
3081 PQoidValue(const PGresult *res)
3083 char *endptr = NULL;
3084 unsigned long result;
3087 strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
3088 res->cmdStatus[7] < '0' ||
3089 res->cmdStatus[7] > '9')
3092 result = strtoul(res->cmdStatus + 7, &endptr, 10);
3094 if (!endptr || (*endptr != ' ' && *endptr != '\0'))
3097 return (Oid) result;
3103 * If the last command was INSERT/UPDATE/DELETE/MOVE/FETCH/COPY, return
3104 * a string containing the number of inserted/affected tuples. If not,
3107 * XXX: this should probably return an int
3110 PQcmdTuples(PGresult *res)
3118 if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3120 p = res->cmdStatus + 7;
3121 /* INSERT: skip oid and space */
3122 while (*p && *p != ' ')
3125 goto interpret_error; /* no space? */
3128 else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3129 strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3130 strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3131 p = res->cmdStatus + 7;
3132 else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
3133 p = res->cmdStatus + 6;
3134 else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3135 strncmp(res->cmdStatus, "COPY ", 5) == 0)
3136 p = res->cmdStatus + 5;
3140 /* check that we have an integer (at least one digit, nothing else) */
3141 for (c = p; *c; c++)
3143 if (!isdigit((unsigned char) *c))
3144 goto interpret_error;
3147 goto interpret_error;
3152 pqInternalNotice(&res->noticeHooks,
3153 "could not interpret result from server: %s",
3160 * return the value of field 'field_num' of row 'tup_num'
3163 PQgetvalue(const PGresult *res, int tup_num, int field_num)
3165 if (!check_tuple_field_number(res, tup_num, field_num))
3167 return res->tuples[tup_num][field_num].value;
3171 * returns the actual length of a field value in bytes.
3174 PQgetlength(const PGresult *res, int tup_num, int field_num)
3176 if (!check_tuple_field_number(res, tup_num, field_num))
3178 if (res->tuples[tup_num][field_num].len != NULL_LEN)
3179 return res->tuples[tup_num][field_num].len;
3185 * returns the null status of a field value.
3188 PQgetisnull(const PGresult *res, int tup_num, int field_num)
3190 if (!check_tuple_field_number(res, tup_num, field_num))
3191 return 1; /* pretend it is null */
3192 if (res->tuples[tup_num][field_num].len == NULL_LEN)
3199 * returns the number of input parameters of a prepared statement.
3202 PQnparams(const PGresult *res)
3206 return res->numParameters;
3210 * returns type Oid of the specified statement parameter.
3213 PQparamtype(const PGresult *res, int param_num)
3215 if (!check_param_number(res, param_num))
3217 if (res->paramDescs)
3218 return res->paramDescs[param_num].typid;
3224 /* PQsetnonblocking:
3225 * sets the PGconn's database connection non-blocking if the arg is true
3226 * or makes it blocking if the arg is false, this will not protect
3227 * you from PQexec(), you'll only be safe when using the non-blocking API.
3228 * Needs to be called only on a connected database connection.
3231 PQsetnonblocking(PGconn *conn, int arg)
3235 if (!conn || conn->status == CONNECTION_BAD)
3238 barg = (arg ? true : false);
3240 /* early out if the socket is already in the state requested */
3241 if (barg == conn->nonblocking)
3245 * to guarantee constancy for flushing/query/result-polling behavior we
3246 * need to flush the send queue at this point in order to guarantee proper
3247 * behavior. this is ok because either they are making a transition _from_
3248 * or _to_ blocking mode, either way we can block them.
3250 /* if we are going from blocking to non-blocking flush here */
3254 conn->nonblocking = barg;
3260 * return the blocking status of the database connection
3261 * true == nonblocking, false == blocking
3264 PQisnonblocking(const PGconn *conn)
3266 return pqIsnonblocking(conn);
3269 /* libpq is thread-safe? */
3271 PQisthreadsafe(void)
3273 #ifdef ENABLE_THREAD_SAFETY
3281 /* try to force data out, really only useful for non-blocking users */
3283 PQflush(PGconn *conn)
3285 return pqFlush(conn);
3290 * PQfreemem - safely frees memory allocated
3292 * Needed mostly by Win32, unless multithreaded DLL (/MD in VC6)
3293 * Used for freeing memory from PQescapeBytea()/PQunescapeBytea()
3296 PQfreemem(void *ptr)
3302 * PQfreeNotify - free's the memory associated with a PGnotify
3304 * This function is here only for binary backward compatibility.
3305 * New code should use PQfreemem(). A macro will automatically map
3306 * calls to PQfreemem. It should be removed in the future. bjm 2003-03-24
3310 void PQfreeNotify(PGnotify *notify);
3313 PQfreeNotify(PGnotify *notify)
3320 * Escaping arbitrary strings to get valid SQL literal strings.
3322 * Replaces "'" with "''", and if not std_strings, replaces "\" with "\\".
3324 * length is the length of the source string. (Note: if a terminating NUL
3325 * is encountered sooner, PQescapeString stops short of "length"; the behavior
3326 * is thus rather like strncpy.)
3328 * For safety the buffer at "to" must be at least 2*length + 1 bytes long.
3329 * A terminating NUL character is added to the output string, whether the
3330 * input is NUL-terminated or not.
3332 * Returns the actual length of the output (not counting the terminating NUL).
3335 PQescapeStringInternal(PGconn *conn,
3336 char *to, const char *from, size_t length,
3338 int encoding, bool std_strings)
3340 const char *source = from;
3342 size_t remaining = length;
3347 while (remaining > 0 && *source != '\0')
3353 /* Fast path for plain ASCII */
3354 if (!IS_HIGHBIT_SET(c))
3356 /* Apply quoting if needed */
3357 if (SQL_STR_DOUBLE(c, !std_strings))
3359 /* Copy the character */
3366 /* Slow path for possible multibyte characters */
3367 len = pg_encoding_mblen(encoding, source);
3369 /* Copy the character */
3370 for (i = 0; i < len; i++)
3372 if (remaining == 0 || *source == '\0')
3374 *target++ = *source++;
3379 * If we hit premature end of string (ie, incomplete multibyte
3380 * character), try to pad out to the correct length with spaces. We
3381 * may not be able to pad completely, but we will always be able to
3382 * insert at least one pad space (since we'd not have quoted a
3383 * multibyte character). This should be enough to make a string that
3384 * the server will error out on.
3391 printfPQExpBuffer(&conn->errorMessage,
3392 libpq_gettext("incomplete multibyte character\n"));
3393 for (; i < len; i++)
3395 if (((size_t) (target - to)) / 2 >= length)
3403 /* Write the terminating NUL character. */
3410 PQescapeStringConn(PGconn *conn,
3411 char *to, const char *from, size_t length,
3416 /* force empty-string result */
3422 return PQescapeStringInternal(conn, to, from, length, error,
3423 conn->client_encoding,
3428 PQescapeString(char *to, const char *from, size_t length)
3430 return PQescapeStringInternal(NULL, to, from, length, NULL,
3431 static_client_encoding,
3432 static_std_strings);
3437 * Escape arbitrary strings. If as_ident is true, we escape the result
3438 * as an identifier; if false, as a literal. The result is returned in
3439 * a newly allocated buffer. If we fail due to an encoding violation or out
3440 * of memory condition, we return NULL, storing an error message into conn.
3443 PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
3448 int num_quotes = 0; /* single or double, depending on as_ident */
3449 int num_backslashes = 0;
3452 char quote_char = as_ident ? '"' : '\'';
3454 /* We must have a connection, else fail immediately. */
3458 /* Scan the string for characters that must be escaped. */
3459 for (s = str; (s - str) < len && *s != '\0'; ++s)
3461 if (*s == quote_char)
3463 else if (*s == '\\')
3465 else if (IS_HIGHBIT_SET(*s))
3469 /* Slow path for possible multibyte characters */
3470 charlen = pg_encoding_mblen(conn->client_encoding, s);
3472 /* Multibyte character overruns allowable length. */
3473 if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
3475 printfPQExpBuffer(&conn->errorMessage,
3476 libpq_gettext("incomplete multibyte character\n"));
3480 /* Adjust s, bearing in mind that for loop will increment it. */
3485 /* Allocate output buffer. */
3486 input_len = s - str;
3487 result_size = input_len + num_quotes + 3; /* two quotes, plus a NUL */
3488 if (!as_ident && num_backslashes > 0)
3489 result_size += num_backslashes + 2;
3490 result = rp = (char *) malloc(result_size);
3493 printfPQExpBuffer(&conn->errorMessage,
3494 libpq_gettext("out of memory\n"));
3499 * If we are escaping a literal that contains backslashes, we use the
3500 * escape string syntax so that the result is correct under either value
3501 * of standard_conforming_strings. We also emit a leading space in this
3502 * case, to guard against the possibility that the result might be
3503 * interpolated immediately following an identifier.
3505 if (!as_ident && num_backslashes > 0)
3511 /* Opening quote. */
3515 * Use fast path if possible.
3517 * We've already verified that the input string is well-formed in the
3518 * current encoding. If it contains no quotes and, in the case of
3519 * literal-escaping, no backslashes, then we can just copy it directly to
3520 * the output buffer, adding the necessary quotes.
3522 * If not, we must rescan the input and process each character
3525 if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
3527 memcpy(rp, str, input_len);
3532 for (s = str; s - str < input_len; ++s)
3534 if (*s == quote_char || (!as_ident && *s == '\\'))
3539 else if (!IS_HIGHBIT_SET(*s))
3543 int i = pg_encoding_mblen(conn->client_encoding, s);
3550 ++s; /* for loop will provide the final increment */
3556 /* Closing quote and terminating NUL. */
3564 PQescapeLiteral(PGconn *conn, const char *str, size_t len)
3566 return PQescapeInternal(conn, str, len, false);
3570 PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
3572 return PQescapeInternal(conn, str, len, true);
3575 /* HEX encoding support for bytea */
3576 static const char hextbl[] = "0123456789abcdef";
3578 static const int8 hexlookup[128] = {
3579 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3580 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3581 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3582 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
3583 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3584 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3585 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3586 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3594 if (c > 0 && c < 127)
3595 res = hexlookup[(unsigned char) c];
3602 * PQescapeBytea - converts from binary string to the
3603 * minimal encoding necessary to include the string in an SQL
3604 * INSERT statement with a bytea type column as the target.
3606 * We can use either hex or escape (traditional) encoding.
3607 * In escape mode, the following transformations are applied:
3608 * '\0' == ASCII 0 == \000
3609 * '\'' == ASCII 39 == ''
3610 * '\\' == ASCII 92 == \\
3611 * anything < 0x20, or > 0x7e ---> \ooo
3612 * (where ooo is an octal expression)
3614 * If not std_strings, all backslashes sent to the output are doubled.
3616 static unsigned char *
3617 PQescapeByteaInternal(PGconn *conn,
3618 const unsigned char *from, size_t from_length,
3619 size_t *to_length, bool std_strings, bool use_hex)
3621 const unsigned char *vp;
3623 unsigned char *result;
3626 size_t bslash_len = (std_strings ? 1 : 2);
3629 * empty string has 1 char ('\0')
3635 len += bslash_len + 1 + 2 * from_length;
3640 for (i = from_length; i > 0; i--, vp++)
3642 if (*vp < 0x20 || *vp > 0x7e)
3643 len += bslash_len + 3;
3644 else if (*vp == '\'')
3646 else if (*vp == '\\')
3647 len += bslash_len + bslash_len;
3654 rp = result = (unsigned char *) malloc(len);
3658 printfPQExpBuffer(&conn->errorMessage,
3659 libpq_gettext("out of memory\n"));
3672 for (i = from_length; i > 0; i--, vp++)
3674 unsigned char c = *vp;
3678 *rp++ = hextbl[(c >> 4) & 0xF];
3679 *rp++ = hextbl[c & 0xF];
3681 else if (c < 0x20 || c > 0x7e)
3686 *rp++ = (c >> 6) + '0';
3687 *rp++ = ((c >> 3) & 07) + '0';
3688 *rp++ = (c & 07) + '0';
3714 PQescapeByteaConn(PGconn *conn,
3715 const unsigned char *from, size_t from_length,
3720 return PQescapeByteaInternal(conn, from, from_length, to_length,
3722 (conn->sversion >= 90000));
3726 PQescapeBytea(const unsigned char *from, size_t from_length, size_t *to_length)
3728 return PQescapeByteaInternal(NULL, from, from_length, to_length,
3730 false /* can't use hex */ );
3734 #define ISFIRSTOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '3')
3735 #define ISOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '7')
3736 #define OCTVAL(CH) ((CH) - '0')
3739 * PQunescapeBytea - converts the null terminated string representation
3740 * of a bytea, strtext, into binary, filling a buffer. It returns a
3741 * pointer to the buffer (or NULL on error), and the size of the
3742 * buffer in retbuflen. The pointer may subsequently be used as an
3743 * argument to the function PQfreemem.
3745 * The following transformations are made:
3746 * \\ == ASCII 92 == \
3747 * \ooo == a byte whose value = ooo (ooo is an octal number)
3748 * \x == x (x is any character not matched by the above transformations)
3751 PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
3755 unsigned char *buffer,
3760 if (strtext == NULL)
3763 strtextlen = strlen((const char *) strtext);
3765 if (strtext[0] == '\\' && strtext[1] == 'x')
3767 const unsigned char *s;
3770 buflen = (strtextlen - 2) / 2;
3771 /* Avoid unportable malloc(0) */
3772 buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
3784 * Bad input is silently ignored. Note that this includes
3785 * whitespace between hex pairs, which is allowed by byteain.
3788 if (!*s || v1 == (char) -1)
3791 if (v2 != (char) -1)
3792 *p++ = (v1 << 4) | v2;
3795 buflen = p - buffer;
3800 * Length of input is max length of output, but add one to avoid
3801 * unportable malloc(0) if input is zero-length.
3803 buffer = (unsigned char *) malloc(strtextlen + 1);
3807 for (i = j = 0; i < strtextlen;)
3813 if (strtext[i] == '\\')
3814 buffer[j++] = strtext[i++];
3817 if ((ISFIRSTOCTDIGIT(strtext[i])) &&
3818 (ISOCTDIGIT(strtext[i + 1])) &&
3819 (ISOCTDIGIT(strtext[i + 2])))
3823 byte = OCTVAL(strtext[i++]);
3824 byte = (byte << 3) + OCTVAL(strtext[i++]);
3825 byte = (byte << 3) + OCTVAL(strtext[i++]);
3831 * Note: if we see '\' followed by something that isn't a
3832 * recognized escape sequence, we loop around having done
3833 * nothing except advance i. Therefore the something will
3834 * be emitted as ordinary data on the next cycle. Corner
3835 * case: '\' at end of string will just be discarded.
3840 buffer[j++] = strtext[i++];
3844 buflen = j; /* buflen is the length of the dequoted data */
3847 /* Shrink the buffer to be no larger than necessary */
3848 /* +1 avoids unportable behavior when buflen==0 */
3849 tmpbuf = realloc(buffer, buflen + 1);
3851 /* It would only be a very brain-dead realloc that could fail, but... */
3858 *retbuflen = buflen;