1 /*-------------------------------------------------------------------------
4 * functions related to sending a query down to the backend
6 * Portions Copyright (c) 1996-2014, 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"
21 #include "libpq-int.h"
23 #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);
54 static bool pqAddTuple(PGresult *res, PGresAttValue *tup);
55 static bool PQsendQueryStart(PGconn *conn);
56 static int PQsendQueryGuts(PGconn *conn,
60 const Oid *paramTypes,
61 const char *const * paramValues,
62 const int *paramLengths,
63 const int *paramFormats,
65 static void parseInput(PGconn *conn);
66 static PGresult *getCopyResult(PGconn *conn, ExecStatusType copytype);
67 static bool PQexecStart(PGconn *conn);
68 static PGresult *PQexecFinish(PGconn *conn);
69 static int PQsendDescribe(PGconn *conn, char desc_type,
70 const char *desc_target);
71 static int check_field_number(const PGresult *res, int field_num);
75 * Space management for PGresult.
77 * Formerly, libpq did a separate malloc() for each field of each tuple
78 * returned by a query. This was remarkably expensive --- malloc/free
79 * consumed a sizable part of the application's runtime. And there is
80 * no real need to keep track of the fields separately, since they will
81 * all be freed together when the PGresult is released. So now, we grab
82 * large blocks of storage from malloc and allocate space for query data
83 * within these blocks, using a trivially simple allocator. This reduces
84 * the number of malloc/free calls dramatically, and it also avoids
85 * fragmentation of the malloc storage arena.
86 * The PGresult structure itself is still malloc'd separately. We could
87 * combine it with the first allocation block, but that would waste space
88 * for the common case that no extra storage is actually needed (that is,
89 * the SQL command did not return tuples).
91 * We also malloc the top-level array of tuple pointers separately, because
92 * we need to be able to enlarge it via realloc, and our trivial space
93 * allocator doesn't handle that effectively. (Too bad the FE/BE protocol
94 * doesn't tell us up front how many tuples will be returned.)
95 * All other subsidiary storage for a PGresult is kept in PGresult_data blocks
96 * of size PGRESULT_DATA_BLOCKSIZE. The overhead at the start of each block
97 * is just a link to the next one, if any. Free-space management info is
98 * kept in the owning PGresult.
99 * A query returning a small amount of data will thus require three malloc
100 * calls: one for the PGresult, one for the tuples pointer array, and one
101 * PGresult_data block.
103 * Only the most recently allocated PGresult_data block is a candidate to
104 * have more stuff added to it --- any extra space left over in older blocks
105 * is wasted. We could be smarter and search the whole chain, but the point
106 * here is to be simple and fast. Typical applications do not keep a PGresult
107 * around very long anyway, so some wasted space within one is not a problem.
109 * Tuning constants for the space allocator are:
110 * PGRESULT_DATA_BLOCKSIZE: size of a standard allocation block, in bytes
111 * PGRESULT_ALIGN_BOUNDARY: assumed alignment requirement for binary data
112 * PGRESULT_SEP_ALLOC_THRESHOLD: objects bigger than this are given separate
113 * blocks, instead of being crammed into a regular allocation block.
114 * Requirements for correct function are:
115 * PGRESULT_ALIGN_BOUNDARY must be a multiple of the alignment requirements
116 * of all machine data types. (Currently this is set from configure
117 * tests, so it should be OK automatically.)
118 * PGRESULT_SEP_ALLOC_THRESHOLD + PGRESULT_BLOCK_OVERHEAD <=
119 * PGRESULT_DATA_BLOCKSIZE
120 * pqResultAlloc assumes an object smaller than the threshold will fit
122 * The amount of space wasted at the end of a block could be as much as
123 * PGRESULT_SEP_ALLOC_THRESHOLD, so it doesn't pay to make that too large.
127 #define PGRESULT_DATA_BLOCKSIZE 2048
128 #define PGRESULT_ALIGN_BOUNDARY MAXIMUM_ALIGNOF /* from configure */
129 #define PGRESULT_BLOCK_OVERHEAD Max(sizeof(PGresult_data), PGRESULT_ALIGN_BOUNDARY)
130 #define PGRESULT_SEP_ALLOC_THRESHOLD (PGRESULT_DATA_BLOCKSIZE / 2)
134 * PQmakeEmptyPGresult
135 * returns a newly allocated, initialized PGresult with given status.
136 * If conn is not NULL and status indicates an error, the conn's
137 * errorMessage is copied. Also, any PGEvents are copied from the conn.
140 PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
144 result = (PGresult *) malloc(sizeof(PGresult));
149 result->numAttributes = 0;
150 result->attDescs = NULL;
151 result->tuples = NULL;
152 result->tupArrSize = 0;
153 result->numParameters = 0;
154 result->paramDescs = NULL;
155 result->resultStatus = status;
156 result->cmdStatus[0] = '\0';
158 result->events = NULL;
160 result->errMsg = NULL;
161 result->errFields = NULL;
162 result->null_field[0] = '\0';
163 result->curBlock = NULL;
164 result->curOffset = 0;
165 result->spaceLeft = 0;
169 /* copy connection data we might need for operations on PGresult */
170 result->noticeHooks = conn->noticeHooks;
171 result->client_encoding = conn->client_encoding;
173 /* consider copying conn's errorMessage */
176 case PGRES_EMPTY_QUERY:
177 case PGRES_COMMAND_OK:
178 case PGRES_TUPLES_OK:
181 case PGRES_COPY_BOTH:
182 case PGRES_SINGLE_TUPLE:
183 /* non-error cases */
186 pqSetResultError(result, conn->errorMessage.data);
190 /* copy events last; result must be valid if we need to PQclear */
191 if (conn->nEvents > 0)
193 result->events = dupEvents(conn->events, conn->nEvents);
199 result->nEvents = conn->nEvents;
205 result->noticeHooks.noticeRec = NULL;
206 result->noticeHooks.noticeRecArg = NULL;
207 result->noticeHooks.noticeProc = NULL;
208 result->noticeHooks.noticeProcArg = NULL;
209 result->client_encoding = PG_SQL_ASCII;
218 * Set the attributes for a given result. This function fails if there are
219 * already attributes contained in the provided result. The call is
220 * ignored if numAttributes is zero or attDescs is NULL. If the
221 * function fails, it returns zero. If the function succeeds, it
222 * returns a non-zero value.
225 PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs)
229 /* If attrs already exist, they cannot be overwritten. */
230 if (!res || res->numAttributes > 0)
233 /* ignore no-op request */
234 if (numAttributes <= 0 || !attDescs)
237 res->attDescs = (PGresAttDesc *)
238 PQresultAlloc(res, numAttributes * sizeof(PGresAttDesc));
243 res->numAttributes = numAttributes;
244 memcpy(res->attDescs, attDescs, numAttributes * sizeof(PGresAttDesc));
246 /* deep-copy the attribute names, and determine format */
248 for (i = 0; i < res->numAttributes; i++)
250 if (res->attDescs[i].name)
251 res->attDescs[i].name = pqResultStrdup(res, res->attDescs[i].name);
253 res->attDescs[i].name = res->null_field;
255 if (!res->attDescs[i].name)
258 if (res->attDescs[i].format == 0)
268 * Returns a deep copy of the provided 'src' PGresult, which cannot be NULL.
269 * The 'flags' argument controls which portions of the result will or will
270 * NOT be copied. The created result is always put into the
271 * PGRES_TUPLES_OK status. The source result error message is not copied,
272 * although cmdStatus is.
274 * To set custom attributes, use PQsetResultAttrs. That function requires
275 * that there are no attrs contained in the result, so to use that
276 * function you cannot use the PG_COPYRES_ATTRS or PG_COPYRES_TUPLES
277 * options with this function.
280 * PG_COPYRES_ATTRS - Copy the source result's attributes
282 * PG_COPYRES_TUPLES - Copy the source result's tuples. This implies
283 * copying the attrs, seeing how the attrs are needed by the tuples.
285 * PG_COPYRES_EVENTS - Copy the source result's events.
287 * PG_COPYRES_NOTICEHOOKS - Copy the source result's notice hooks.
290 PQcopyResult(const PGresult *src, int flags)
298 dest = PQmakeEmptyPGresult(NULL, PGRES_TUPLES_OK);
302 /* Always copy these over. Is cmdStatus really useful here? */
303 dest->client_encoding = src->client_encoding;
304 strcpy(dest->cmdStatus, src->cmdStatus);
307 if (flags & (PG_COPYRES_ATTRS | PG_COPYRES_TUPLES))
309 if (!PQsetResultAttrs(dest, src->numAttributes, src->attDescs))
316 /* Wants to copy tuples? */
317 if (flags & PG_COPYRES_TUPLES)
322 for (tup = 0; tup < src->ntups; tup++)
324 for (field = 0; field < src->numAttributes; field++)
326 if (!PQsetvalue(dest, tup, field,
327 src->tuples[tup][field].value,
328 src->tuples[tup][field].len))
337 /* Wants to copy notice hooks? */
338 if (flags & PG_COPYRES_NOTICEHOOKS)
339 dest->noticeHooks = src->noticeHooks;
341 /* Wants to copy PGEvents? */
342 if ((flags & PG_COPYRES_EVENTS) && src->nEvents > 0)
344 dest->events = dupEvents(src->events, src->nEvents);
350 dest->nEvents = src->nEvents;
353 /* Okay, trigger PGEVT_RESULTCOPY event */
354 for (i = 0; i < dest->nEvents; i++)
356 if (src->events[i].resultInitialized)
358 PGEventResultCopy evt;
362 if (!dest->events[i].proc(PGEVT_RESULTCOPY, &evt,
363 dest->events[i].passThrough))
368 dest->events[i].resultInitialized = TRUE;
376 * Copy an array of PGEvents (with no extra space for more).
377 * Does not duplicate the event instance data, sets this to NULL.
378 * Also, the resultInitialized flags are all cleared.
381 dupEvents(PGEvent *events, int count)
386 if (!events || count <= 0)
389 newEvents = (PGEvent *) malloc(count * sizeof(PGEvent));
393 for (i = 0; i < count; i++)
395 newEvents[i].proc = events[i].proc;
396 newEvents[i].passThrough = events[i].passThrough;
397 newEvents[i].data = NULL;
398 newEvents[i].resultInitialized = FALSE;
399 newEvents[i].name = strdup(events[i].name);
400 if (!newEvents[i].name)
403 free(newEvents[i].name);
414 * Sets the value for a tuple field. The tup_num must be less than or
415 * equal to PQntuples(res). If it is equal, a new tuple is created and
416 * added to the result.
417 * Returns a non-zero value for success and zero for failure.
420 PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len)
422 PGresAttValue *attval;
424 if (!check_field_number(res, field_num))
427 /* Invalid tup_num, must be <= ntups */
428 if (tup_num < 0 || tup_num > res->ntups)
431 /* need to allocate a new tuple? */
432 if (tup_num == res->ntups)
437 tup = (PGresAttValue *)
438 pqResultAlloc(res, res->numAttributes * sizeof(PGresAttValue),
444 /* initialize each column to NULL */
445 for (i = 0; i < res->numAttributes; i++)
447 tup[i].len = NULL_LEN;
448 tup[i].value = res->null_field;
451 /* add it to the array */
452 if (!pqAddTuple(res, tup))
456 attval = &res->tuples[tup_num][field_num];
458 /* treat either NULL_LEN or NULL value pointer as a NULL field */
459 if (len == NULL_LEN || value == NULL)
461 attval->len = NULL_LEN;
462 attval->value = res->null_field;
467 attval->value = res->null_field;
471 attval->value = (char *) pqResultAlloc(res, len + 1, TRUE);
475 memcpy(attval->value, value, len);
476 attval->value[len] = '\0';
483 * pqResultAlloc - exported routine to allocate local storage in a PGresult.
485 * We force all such allocations to be maxaligned, since we don't know
486 * whether the value might be binary.
489 PQresultAlloc(PGresult *res, size_t nBytes)
491 return pqResultAlloc(res, nBytes, TRUE);
496 * Allocate subsidiary storage for a PGresult.
498 * nBytes is the amount of space needed for the object.
499 * If isBinary is true, we assume that we need to align the object on
500 * a machine allocation boundary.
501 * If isBinary is false, we assume the object is a char string and can
502 * be allocated on any byte boundary.
505 pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
508 PGresult_data *block;
514 return res->null_field;
517 * If alignment is needed, round up the current position to an alignment
522 int offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
526 res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
527 res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
531 /* If there's enough space in the current block, no problem. */
532 if (nBytes <= (size_t) res->spaceLeft)
534 space = res->curBlock->space + res->curOffset;
535 res->curOffset += nBytes;
536 res->spaceLeft -= nBytes;
541 * If the requested object is very large, give it its own block; this
542 * avoids wasting what might be most of the current block to start a new
543 * block. (We'd have to special-case requests bigger than the block size
544 * anyway.) The object is always given binary alignment in this case.
546 if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
548 block = (PGresult_data *) malloc(nBytes + PGRESULT_BLOCK_OVERHEAD);
551 space = block->space + PGRESULT_BLOCK_OVERHEAD;
555 * Tuck special block below the active block, so that we don't
556 * have to waste the free space in the active block.
558 block->next = res->curBlock->next;
559 res->curBlock->next = block;
563 /* Must set up the new block as the first active block. */
565 res->curBlock = block;
566 res->spaceLeft = 0; /* be sure it's marked full */
571 /* Otherwise, start a new block. */
572 block = (PGresult_data *) malloc(PGRESULT_DATA_BLOCKSIZE);
575 block->next = res->curBlock;
576 res->curBlock = block;
579 /* object needs full alignment */
580 res->curOffset = PGRESULT_BLOCK_OVERHEAD;
581 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - PGRESULT_BLOCK_OVERHEAD;
585 /* we can cram it right after the overhead pointer */
586 res->curOffset = sizeof(PGresult_data);
587 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - sizeof(PGresult_data);
590 space = block->space + res->curOffset;
591 res->curOffset += nBytes;
592 res->spaceLeft -= nBytes;
598 * Like strdup, but the space is subsidiary PGresult space.
601 pqResultStrdup(PGresult *res, const char *str)
603 char *space = (char *) pqResultAlloc(res, strlen(str) + 1, FALSE);
612 * assign a new error message to a PGresult
615 pqSetResultError(PGresult *res, const char *msg)
620 res->errMsg = pqResultStrdup(res, msg);
626 * pqCatenateResultError -
627 * concatenate a new error message to the one already in a PGresult
630 pqCatenateResultError(PGresult *res, const char *msg)
632 PQExpBufferData errorBuf;
636 initPQExpBuffer(&errorBuf);
638 appendPQExpBufferStr(&errorBuf, res->errMsg);
639 appendPQExpBufferStr(&errorBuf, msg);
640 pqSetResultError(res, errorBuf.data);
641 termPQExpBuffer(&errorBuf);
646 * free's the memory associated with a PGresult
649 PQclear(PGresult *res)
651 PGresult_data *block;
657 for (i = 0; i < res->nEvents; i++)
659 /* only send DESTROY to successfully-initialized event procs */
660 if (res->events[i].resultInitialized)
662 PGEventResultDestroy evt;
665 (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
666 res->events[i].passThrough);
668 free(res->events[i].name);
674 /* Free all the subsidiary blocks */
675 while ((block = res->curBlock) != NULL)
677 res->curBlock = block->next;
681 /* Free the top-level tuple pointer array */
685 /* zero out the pointer fields to catch programming errors */
686 res->attDescs = NULL;
688 res->paramDescs = NULL;
689 res->errFields = NULL;
692 /* res->curBlock was zeroed out earlier */
694 /* Free the PGresult structure itself */
699 * Handy subroutine to deallocate any partially constructed async result.
701 * Any "next" result gets cleared too.
704 pqClearAsyncResult(PGconn *conn)
707 PQclear(conn->result);
709 if (conn->next_result)
710 PQclear(conn->next_result);
711 conn->next_result = NULL;
715 * This subroutine deletes any existing async result, sets conn->result
716 * to a PGresult with status PGRES_FATAL_ERROR, and stores the current
717 * contents of conn->errorMessage into that result. It differs from a
718 * plain call on PQmakeEmptyPGresult() in that if there is already an
719 * async result with status PGRES_FATAL_ERROR, the current error message
720 * is APPENDED to the old error message instead of replacing it. This
721 * behavior lets us report multiple error conditions properly, if necessary.
722 * (An example where this is needed is when the backend sends an 'E' message
723 * and immediately closes the connection --- we want to report both the
724 * backend error and the connection closure error.)
727 pqSaveErrorResult(PGconn *conn)
730 * If no old async result, just let PQmakeEmptyPGresult make one. Likewise
731 * if old result is not an error message.
733 if (conn->result == NULL ||
734 conn->result->resultStatus != PGRES_FATAL_ERROR ||
735 conn->result->errMsg == NULL)
737 pqClearAsyncResult(conn);
738 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
742 /* Else, concatenate error message to existing async result. */
743 pqCatenateResultError(conn->result, conn->errorMessage.data);
748 * This subroutine prepares an async result object for return to the caller.
749 * If there is not already an async result object, build an error object
750 * using whatever is in conn->errorMessage. In any case, clear the async
751 * result storage and make sure PQerrorMessage will agree with the result's
755 pqPrepareAsyncResult(PGconn *conn)
760 * conn->result is the PGresult to return. If it is NULL (which probably
761 * shouldn't happen) we assume there is an appropriate error message in
762 * conn->errorMessage.
766 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
770 * Make sure PQerrorMessage agrees with result; it could be different
771 * if we have concatenated messages.
773 resetPQExpBuffer(&conn->errorMessage);
774 appendPQExpBufferStr(&conn->errorMessage,
775 PQresultErrorMessage(res));
779 * Replace conn->result with next_result, if any. In the normal case
780 * there isn't a next result and we're just dropping ownership of the
781 * current result. In single-row mode this restores the situation to what
782 * it was before we created the current single-row result.
784 conn->result = conn->next_result;
785 conn->next_result = NULL;
791 * pqInternalNotice - produce an internally-generated notice message
793 * A format string and optional arguments can be passed. Note that we do
794 * libpq_gettext() here, so callers need not.
796 * The supplied text is taken as primary message (ie., it should not include
797 * a trailing newline, and should not be more than one line).
800 pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
806 if (hooks->noticeRec == NULL)
807 return; /* nobody home to receive notice? */
809 /* Format the message */
811 vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
813 msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
815 /* Make a PGresult to pass to the notice receiver */
816 res = PQmakeEmptyPGresult(NULL, PGRES_NONFATAL_ERROR);
819 res->noticeHooks = *hooks;
822 * Set up fields of notice.
824 pqSaveMessageField(res, PG_DIAG_MESSAGE_PRIMARY, msgBuf);
825 pqSaveMessageField(res, PG_DIAG_SEVERITY, libpq_gettext("NOTICE"));
826 /* XXX should provide a SQLSTATE too? */
829 * Result text is always just the primary message + newline. If we can't
830 * allocate it, don't bother invoking the receiver.
832 res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, FALSE);
835 sprintf(res->errMsg, "%s\n", msgBuf);
838 * Pass to receiver, then free it.
840 (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
847 * add a row pointer to the PGresult structure, growing it if necessary
848 * Returns TRUE if OK, FALSE if not enough memory to add the row
851 pqAddTuple(PGresult *res, PGresAttValue *tup)
853 if (res->ntups >= res->tupArrSize)
856 * Try to grow the array.
858 * We can use realloc because shallow copying of the structure is
859 * okay. Note that the first time through, res->tuples is NULL. While
860 * ANSI says that realloc() should act like malloc() in that case,
861 * some old C libraries (like SunOS 4.1.x) coredump instead. On
862 * failure realloc is supposed to return NULL without damaging the
863 * existing allocation. Note that the positions beyond res->ntups are
864 * garbage, not necessarily NULL.
866 int newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
867 PGresAttValue **newTuples;
869 if (res->tuples == NULL)
870 newTuples = (PGresAttValue **)
871 malloc(newSize * sizeof(PGresAttValue *));
873 newTuples = (PGresAttValue **)
874 realloc(res->tuples, newSize * sizeof(PGresAttValue *));
876 return FALSE; /* malloc or realloc failed */
877 res->tupArrSize = newSize;
878 res->tuples = newTuples;
880 res->tuples[res->ntups] = tup;
886 * pqSaveMessageField - save one field of an error or notice message
889 pqSaveMessageField(PGresult *res, char code, const char *value)
891 PGMessageField *pfield;
893 pfield = (PGMessageField *)
895 sizeof(PGMessageField) + strlen(value),
898 return; /* out of memory? */
900 strcpy(pfield->contents, value);
901 pfield->next = res->errFields;
902 res->errFields = pfield;
906 * pqSaveParameterStatus - remember parameter status sent by backend
909 pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
911 pgParameterStatus *pstatus;
912 pgParameterStatus *prev;
915 fprintf(conn->Pfdebug, "pqSaveParameterStatus: '%s' = '%s'\n",
919 * Forget any old information about the parameter
921 for (pstatus = conn->pstatus, prev = NULL;
923 prev = pstatus, pstatus = pstatus->next)
925 if (strcmp(pstatus->name, name) == 0)
928 prev->next = pstatus->next;
930 conn->pstatus = pstatus->next;
931 free(pstatus); /* frees name and value strings too */
937 * Store new info as a single malloc block
939 pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
940 strlen(name) +strlen(value) + 2);
945 ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
948 ptr += strlen(name) + 1;
949 pstatus->value = ptr;
951 pstatus->next = conn->pstatus;
952 conn->pstatus = pstatus;
956 * Special hacks: remember client_encoding and
957 * standard_conforming_strings, and convert server version to a numeric
958 * form. We keep the first two of these in static variables as well, so
959 * that PQescapeString and PQescapeBytea can behave somewhat sanely (at
960 * least in single-connection-using programs).
962 if (strcmp(name, "client_encoding") == 0)
964 conn->client_encoding = pg_char_to_encoding(value);
965 /* if we don't recognize the encoding name, fall back to SQL_ASCII */
966 if (conn->client_encoding < 0)
967 conn->client_encoding = PG_SQL_ASCII;
968 static_client_encoding = conn->client_encoding;
970 else if (strcmp(name, "standard_conforming_strings") == 0)
972 conn->std_strings = (strcmp(value, "on") == 0);
973 static_std_strings = conn->std_strings;
975 else if (strcmp(name, "server_version") == 0)
982 cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
985 conn->sversion = 0; /* unknown */
990 conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
998 * Add the received row to the current async result (conn->result).
999 * Returns 1 if OK, 0 if error occurred.
1001 * On error, *errmsgp can be set to an error string to be returned.
1002 * If it is left NULL, the error is presumed to be "out of memory".
1004 * In single-row mode, we create a new result holding just the current row,
1005 * stashing the previous result in conn->next_result so that it becomes
1006 * active again after pqPrepareAsyncResult(). This allows the result metadata
1007 * (column descriptions) to be carried forward to each result row.
1010 pqRowProcessor(PGconn *conn, const char **errmsgp)
1012 PGresult *res = conn->result;
1013 int nfields = res->numAttributes;
1014 const PGdataValue *columns = conn->rowBuf;
1019 * In single-row mode, make a new PGresult that will hold just this one
1020 * row; the original conn->result is left unchanged so that it can be used
1021 * again as the template for future rows.
1023 if (conn->singleRowMode)
1025 /* Copy everything that should be in the result at this point */
1026 res = PQcopyResult(res,
1027 PG_COPYRES_ATTRS | PG_COPYRES_EVENTS |
1028 PG_COPYRES_NOTICEHOOKS);
1034 * Basically we just allocate space in the PGresult for each field and
1035 * copy the data over.
1037 * Note: on malloc failure, we return 0 leaving *errmsgp still NULL, which
1038 * caller will take to mean "out of memory". This is preferable to trying
1039 * to set up such a message here, because evidently there's not enough
1040 * memory for gettext() to do anything.
1042 tup = (PGresAttValue *)
1043 pqResultAlloc(res, nfields * sizeof(PGresAttValue), TRUE);
1047 for (i = 0; i < nfields; i++)
1049 int clen = columns[i].len;
1054 tup[i].len = NULL_LEN;
1055 tup[i].value = res->null_field;
1059 bool isbinary = (res->attDescs[i].format != 0);
1062 val = (char *) pqResultAlloc(res, clen + 1, isbinary);
1066 /* copy and zero-terminate the data (even if it's binary) */
1067 memcpy(val, columns[i].value, clen);
1075 /* And add the tuple to the PGresult's tuple array */
1076 if (!pqAddTuple(res, tup))
1080 * Success. In single-row mode, make the result available to the client
1083 if (conn->singleRowMode)
1085 /* Change result status to special single-row value */
1086 res->resultStatus = PGRES_SINGLE_TUPLE;
1087 /* Stash old result for re-use later */
1088 conn->next_result = conn->result;
1090 /* And mark the result ready to return */
1091 conn->asyncStatus = PGASYNC_READY;
1097 /* release locally allocated PGresult, if we made one */
1098 if (res != conn->result)
1106 * Submit a query, but don't wait for it to finish
1108 * Returns: 1 if successfully submitted
1109 * 0 if error (conn->errorMessage is set)
1112 PQsendQuery(PGconn *conn, const char *query)
1114 if (!PQsendQueryStart(conn))
1117 /* check the argument */
1120 printfPQExpBuffer(&conn->errorMessage,
1121 libpq_gettext("command string is a null pointer\n"));
1125 /* construct the outgoing Query message */
1126 if (pqPutMsgStart('Q', false, conn) < 0 ||
1127 pqPuts(query, conn) < 0 ||
1128 pqPutMsgEnd(conn) < 0)
1130 pqHandleSendFailure(conn);
1134 /* remember we are using simple query protocol */
1135 conn->queryclass = PGQUERY_SIMPLE;
1137 /* and remember the query text too, if possible */
1138 /* if insufficient memory, last_query just winds up NULL */
1139 if (conn->last_query)
1140 free(conn->last_query);
1141 conn->last_query = strdup(query);
1144 * Give the data a push. In nonblock mode, don't complain if we're unable
1145 * to send it all; PQgetResult() will do any additional flushing needed.
1147 if (pqFlush(conn) < 0)
1149 pqHandleSendFailure(conn);
1153 /* OK, it's launched! */
1154 conn->asyncStatus = PGASYNC_BUSY;
1160 * Like PQsendQuery, but use protocol 3.0 so we can pass parameters
1163 PQsendQueryParams(PGconn *conn,
1164 const char *command,
1166 const Oid *paramTypes,
1167 const char *const * paramValues,
1168 const int *paramLengths,
1169 const int *paramFormats,
1172 if (!PQsendQueryStart(conn))
1175 /* check the arguments */
1178 printfPQExpBuffer(&conn->errorMessage,
1179 libpq_gettext("command string is a null pointer\n"));
1182 if (nParams < 0 || nParams > 65535)
1184 printfPQExpBuffer(&conn->errorMessage,
1185 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1189 return PQsendQueryGuts(conn,
1191 "", /* use unnamed statement */
1202 * Submit a Parse message, but don't wait for it to finish
1204 * Returns: 1 if successfully submitted
1205 * 0 if error (conn->errorMessage is set)
1208 PQsendPrepare(PGconn *conn,
1209 const char *stmtName, const char *query,
1210 int nParams, const Oid *paramTypes)
1212 if (!PQsendQueryStart(conn))
1215 /* check the arguments */
1218 printfPQExpBuffer(&conn->errorMessage,
1219 libpq_gettext("statement name is a null pointer\n"));
1224 printfPQExpBuffer(&conn->errorMessage,
1225 libpq_gettext("command string is a null pointer\n"));
1228 if (nParams < 0 || nParams > 65535)
1230 printfPQExpBuffer(&conn->errorMessage,
1231 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1235 /* This isn't gonna work on a 2.0 server */
1236 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1238 printfPQExpBuffer(&conn->errorMessage,
1239 libpq_gettext("function requires at least protocol version 3.0\n"));
1243 /* construct the Parse message */
1244 if (pqPutMsgStart('P', false, conn) < 0 ||
1245 pqPuts(stmtName, conn) < 0 ||
1246 pqPuts(query, conn) < 0)
1249 if (nParams > 0 && paramTypes)
1253 if (pqPutInt(nParams, 2, conn) < 0)
1255 for (i = 0; i < nParams; i++)
1257 if (pqPutInt(paramTypes[i], 4, conn) < 0)
1263 if (pqPutInt(0, 2, conn) < 0)
1266 if (pqPutMsgEnd(conn) < 0)
1269 /* construct the Sync message */
1270 if (pqPutMsgStart('S', false, conn) < 0 ||
1271 pqPutMsgEnd(conn) < 0)
1274 /* remember we are doing just a Parse */
1275 conn->queryclass = PGQUERY_PREPARE;
1277 /* and remember the query text too, if possible */
1278 /* if insufficient memory, last_query just winds up NULL */
1279 if (conn->last_query)
1280 free(conn->last_query);
1281 conn->last_query = strdup(query);
1284 * Give the data a push. In nonblock mode, don't complain if we're unable
1285 * to send it all; PQgetResult() will do any additional flushing needed.
1287 if (pqFlush(conn) < 0)
1290 /* OK, it's launched! */
1291 conn->asyncStatus = PGASYNC_BUSY;
1295 pqHandleSendFailure(conn);
1300 * PQsendQueryPrepared
1301 * Like PQsendQuery, but execute a previously prepared statement,
1302 * using protocol 3.0 so we can pass parameters
1305 PQsendQueryPrepared(PGconn *conn,
1306 const char *stmtName,
1308 const char *const * paramValues,
1309 const int *paramLengths,
1310 const int *paramFormats,
1313 if (!PQsendQueryStart(conn))
1316 /* check the arguments */
1319 printfPQExpBuffer(&conn->errorMessage,
1320 libpq_gettext("statement name is a null pointer\n"));
1323 if (nParams < 0 || nParams > 65535)
1325 printfPQExpBuffer(&conn->errorMessage,
1326 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1330 return PQsendQueryGuts(conn,
1331 NULL, /* no command to parse */
1334 NULL, /* no param types */
1342 * Common startup code for PQsendQuery and sibling routines
1345 PQsendQueryStart(PGconn *conn)
1350 /* clear the error string */
1351 resetPQExpBuffer(&conn->errorMessage);
1353 /* Don't try to send if we know there's no live connection. */
1354 if (conn->status != CONNECTION_OK)
1356 printfPQExpBuffer(&conn->errorMessage,
1357 libpq_gettext("no connection to the server\n"));
1360 /* Can't send while already busy, either. */
1361 if (conn->asyncStatus != PGASYNC_IDLE)
1363 printfPQExpBuffer(&conn->errorMessage,
1364 libpq_gettext("another command is already in progress\n"));
1368 /* initialize async result-accumulation state */
1369 conn->result = NULL;
1370 conn->next_result = NULL;
1372 /* reset single-row processing mode */
1373 conn->singleRowMode = false;
1375 /* ready to send command message */
1381 * Common code for protocol-3.0 query sending
1382 * PQsendQueryStart should be done already
1384 * command may be NULL to indicate we use an already-prepared statement
1387 PQsendQueryGuts(PGconn *conn,
1388 const char *command,
1389 const char *stmtName,
1391 const Oid *paramTypes,
1392 const char *const * paramValues,
1393 const int *paramLengths,
1394 const int *paramFormats,
1399 /* This isn't gonna work on a 2.0 server */
1400 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1402 printfPQExpBuffer(&conn->errorMessage,
1403 libpq_gettext("function requires at least protocol version 3.0\n"));
1408 * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync,
1409 * using specified statement name and the unnamed portal.
1414 /* construct the Parse message */
1415 if (pqPutMsgStart('P', false, conn) < 0 ||
1416 pqPuts(stmtName, conn) < 0 ||
1417 pqPuts(command, conn) < 0)
1419 if (nParams > 0 && paramTypes)
1421 if (pqPutInt(nParams, 2, conn) < 0)
1423 for (i = 0; i < nParams; i++)
1425 if (pqPutInt(paramTypes[i], 4, conn) < 0)
1431 if (pqPutInt(0, 2, conn) < 0)
1434 if (pqPutMsgEnd(conn) < 0)
1438 /* Construct the Bind message */
1439 if (pqPutMsgStart('B', false, conn) < 0 ||
1440 pqPuts("", conn) < 0 ||
1441 pqPuts(stmtName, conn) < 0)
1444 /* Send parameter formats */
1445 if (nParams > 0 && paramFormats)
1447 if (pqPutInt(nParams, 2, conn) < 0)
1449 for (i = 0; i < nParams; i++)
1451 if (pqPutInt(paramFormats[i], 2, conn) < 0)
1457 if (pqPutInt(0, 2, conn) < 0)
1461 if (pqPutInt(nParams, 2, conn) < 0)
1464 /* Send parameters */
1465 for (i = 0; i < nParams; i++)
1467 if (paramValues && paramValues[i])
1471 if (paramFormats && paramFormats[i] != 0)
1473 /* binary parameter */
1475 nbytes = paramLengths[i];
1478 printfPQExpBuffer(&conn->errorMessage,
1479 libpq_gettext("length must be given for binary parameter\n"));
1485 /* text parameter, do not use paramLengths */
1486 nbytes = strlen(paramValues[i]);
1488 if (pqPutInt(nbytes, 4, conn) < 0 ||
1489 pqPutnchar(paramValues[i], nbytes, conn) < 0)
1494 /* take the param as NULL */
1495 if (pqPutInt(-1, 4, conn) < 0)
1499 if (pqPutInt(1, 2, conn) < 0 ||
1500 pqPutInt(resultFormat, 2, conn))
1502 if (pqPutMsgEnd(conn) < 0)
1505 /* construct the Describe Portal message */
1506 if (pqPutMsgStart('D', false, conn) < 0 ||
1507 pqPutc('P', conn) < 0 ||
1508 pqPuts("", conn) < 0 ||
1509 pqPutMsgEnd(conn) < 0)
1512 /* construct the Execute message */
1513 if (pqPutMsgStart('E', false, conn) < 0 ||
1514 pqPuts("", conn) < 0 ||
1515 pqPutInt(0, 4, conn) < 0 ||
1516 pqPutMsgEnd(conn) < 0)
1519 /* construct the Sync message */
1520 if (pqPutMsgStart('S', false, conn) < 0 ||
1521 pqPutMsgEnd(conn) < 0)
1524 /* remember we are using extended query protocol */
1525 conn->queryclass = PGQUERY_EXTENDED;
1527 /* and remember the query text too, if possible */
1528 /* if insufficient memory, last_query just winds up NULL */
1529 if (conn->last_query)
1530 free(conn->last_query);
1532 conn->last_query = strdup(command);
1534 conn->last_query = NULL;
1537 * Give the data a push. In nonblock mode, don't complain if we're unable
1538 * to send it all; PQgetResult() will do any additional flushing needed.
1540 if (pqFlush(conn) < 0)
1543 /* OK, it's launched! */
1544 conn->asyncStatus = PGASYNC_BUSY;
1548 pqHandleSendFailure(conn);
1553 * pqHandleSendFailure: try to clean up after failure to send command.
1555 * Primarily, what we want to accomplish here is to process an async
1556 * NOTICE message that the backend might have sent just before it died.
1558 * NOTE: this routine should only be called in PGASYNC_IDLE state.
1561 pqHandleSendFailure(PGconn *conn)
1564 * Accept any available input data, ignoring errors. Note that if
1565 * pqReadData decides the backend has closed the channel, it will close
1566 * our side of the socket --- that's just what we want here.
1568 while (pqReadData(conn) > 0)
1569 /* loop until no more data readable */ ;
1572 * Parse any available input messages. Since we are in PGASYNC_IDLE
1573 * state, only NOTICE and NOTIFY messages will be eaten.
1579 * Select row-by-row processing mode
1582 PQsetSingleRowMode(PGconn *conn)
1585 * Only allow setting the flag when we have launched a query and not yet
1586 * received any results.
1590 if (conn->asyncStatus != PGASYNC_BUSY)
1592 if (conn->queryclass != PGQUERY_SIMPLE &&
1593 conn->queryclass != PGQUERY_EXTENDED)
1599 conn->singleRowMode = true;
1604 * Consume any available input from the backend
1605 * 0 return: some kind of trouble
1606 * 1 return: no problem
1609 PQconsumeInput(PGconn *conn)
1615 * for non-blocking connections try to flush the send-queue, otherwise we
1616 * may never get a response for something that may not have already been
1617 * sent because it's in our write buffer!
1619 if (pqIsnonblocking(conn))
1621 if (pqFlush(conn) < 0)
1626 * Load more data, if available. We do this no matter what state we are
1627 * in, since we are probably getting called because the application wants
1628 * to get rid of a read-select condition. Note that we will NOT block
1629 * waiting for more input.
1631 if (pqReadData(conn) < 0)
1634 /* Parsing of the data waits till later. */
1640 * parseInput: if appropriate, parse input data from backend
1641 * until input is exhausted or a stopping state is reached.
1642 * Note that this function will NOT attempt to read more data from the backend.
1645 parseInput(PGconn *conn)
1647 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1648 pqParseInput3(conn);
1650 pqParseInput2(conn);
1655 * Return TRUE if PQgetResult would block waiting for input.
1659 PQisBusy(PGconn *conn)
1664 /* Parse any available data, if our state permits. */
1667 /* PQgetResult will return immediately in all states except BUSY. */
1668 return conn->asyncStatus == PGASYNC_BUSY;
1674 * Get the next PGresult produced by a query. Returns NULL if no
1675 * query work remains or an error has occurred (e.g. out of
1680 PQgetResult(PGconn *conn)
1687 /* Parse any available data, if our state permits. */
1690 /* If not ready to return something, block until we are. */
1691 while (conn->asyncStatus == PGASYNC_BUSY)
1696 * If data remains unsent, send it. Else we might be waiting for the
1697 * result of a command the backend hasn't even got yet.
1699 while ((flushResult = pqFlush(conn)) > 0)
1701 if (pqWait(FALSE, TRUE, conn))
1708 /* Wait for some more data, and load it. */
1710 pqWait(TRUE, FALSE, conn) ||
1711 pqReadData(conn) < 0)
1714 * conn->errorMessage has been set by pqWait or pqReadData. We
1715 * want to append it to any already-received error message.
1717 pqSaveErrorResult(conn);
1718 conn->asyncStatus = PGASYNC_IDLE;
1719 return pqPrepareAsyncResult(conn);
1726 /* Return the appropriate thing. */
1727 switch (conn->asyncStatus)
1730 res = NULL; /* query is complete */
1733 res = pqPrepareAsyncResult(conn);
1734 /* Set the state back to BUSY, allowing parsing to proceed. */
1735 conn->asyncStatus = PGASYNC_BUSY;
1737 case PGASYNC_COPY_IN:
1738 res = getCopyResult(conn, PGRES_COPY_IN);
1740 case PGASYNC_COPY_OUT:
1741 res = getCopyResult(conn, PGRES_COPY_OUT);
1743 case PGASYNC_COPY_BOTH:
1744 res = getCopyResult(conn, PGRES_COPY_BOTH);
1747 printfPQExpBuffer(&conn->errorMessage,
1748 libpq_gettext("unexpected asyncStatus: %d\n"),
1749 (int) conn->asyncStatus);
1750 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1758 for (i = 0; i < res->nEvents; i++)
1760 PGEventResultCreate evt;
1764 if (!res->events[i].proc(PGEVT_RESULTCREATE, &evt,
1765 res->events[i].passThrough))
1767 printfPQExpBuffer(&conn->errorMessage,
1768 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_RESULTCREATE event\n"),
1769 res->events[i].name);
1770 pqSetResultError(res, conn->errorMessage.data);
1771 res->resultStatus = PGRES_FATAL_ERROR;
1774 res->events[i].resultInitialized = TRUE;
1783 * Helper for PQgetResult: generate result for COPY-in-progress cases
1786 getCopyResult(PGconn *conn, ExecStatusType copytype)
1789 * If the server connection has been lost, don't pretend everything is
1790 * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
1791 * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
1792 * error in the earlier steps in PQgetResult). The text returned in the
1793 * result is whatever is in conn->errorMessage; we hope that was filled
1794 * with something relevant when the lost connection was detected.
1796 if (conn->status != CONNECTION_OK)
1798 pqSaveErrorResult(conn);
1799 conn->asyncStatus = PGASYNC_IDLE;
1800 return pqPrepareAsyncResult(conn);
1803 /* If we have an async result for the COPY, return that */
1804 if (conn->result && conn->result->resultStatus == copytype)
1805 return pqPrepareAsyncResult(conn);
1807 /* Otherwise, invent a suitable PGresult */
1808 return PQmakeEmptyPGresult(conn, copytype);
1814 * send a query to the backend and package up the result in a PGresult
1816 * If the query was not even sent, return NULL; conn->errorMessage is set to
1817 * a relevant message.
1818 * If the query was sent, a new PGresult is returned (which could indicate
1819 * either success or failure).
1820 * The user is responsible for freeing the PGresult via PQclear()
1821 * when done with it.
1824 PQexec(PGconn *conn, const char *query)
1826 if (!PQexecStart(conn))
1828 if (!PQsendQuery(conn, query))
1830 return PQexecFinish(conn);
1835 * Like PQexec, but use protocol 3.0 so we can pass parameters
1838 PQexecParams(PGconn *conn,
1839 const char *command,
1841 const Oid *paramTypes,
1842 const char *const * paramValues,
1843 const int *paramLengths,
1844 const int *paramFormats,
1847 if (!PQexecStart(conn))
1849 if (!PQsendQueryParams(conn, command,
1850 nParams, paramTypes, paramValues, paramLengths,
1851 paramFormats, resultFormat))
1853 return PQexecFinish(conn);
1858 * Creates a prepared statement by issuing a v3.0 parse message.
1860 * If the query was not even sent, return NULL; conn->errorMessage is set to
1861 * a relevant message.
1862 * If the query was sent, a new PGresult is returned (which could indicate
1863 * either success or failure).
1864 * The user is responsible for freeing the PGresult via PQclear()
1865 * when done with it.
1868 PQprepare(PGconn *conn,
1869 const char *stmtName, const char *query,
1870 int nParams, const Oid *paramTypes)
1872 if (!PQexecStart(conn))
1874 if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
1876 return PQexecFinish(conn);
1881 * Like PQexec, but execute a previously prepared statement,
1882 * using protocol 3.0 so we can pass parameters
1885 PQexecPrepared(PGconn *conn,
1886 const char *stmtName,
1888 const char *const * paramValues,
1889 const int *paramLengths,
1890 const int *paramFormats,
1893 if (!PQexecStart(conn))
1895 if (!PQsendQueryPrepared(conn, stmtName,
1896 nParams, paramValues, paramLengths,
1897 paramFormats, resultFormat))
1899 return PQexecFinish(conn);
1903 * Common code for PQexec and sibling routines: prepare to send command
1906 PQexecStart(PGconn *conn)
1914 * Silently discard any prior query result that application didn't eat.
1915 * This is probably poor design, but it's here for backward compatibility.
1917 while ((result = PQgetResult(conn)) != NULL)
1919 ExecStatusType resultStatus = result->resultStatus;
1921 PQclear(result); /* only need its status */
1922 if (resultStatus == PGRES_COPY_IN)
1924 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1926 /* In protocol 3, we can get out of a COPY IN state */
1927 if (PQputCopyEnd(conn,
1928 libpq_gettext("COPY terminated by new PQexec")) < 0)
1930 /* keep waiting to swallow the copy's failure message */
1934 /* In older protocols we have to punt */
1935 printfPQExpBuffer(&conn->errorMessage,
1936 libpq_gettext("COPY IN state must be terminated first\n"));
1940 else if (resultStatus == PGRES_COPY_OUT)
1942 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1945 * In protocol 3, we can get out of a COPY OUT state: we just
1946 * switch back to BUSY and allow the remaining COPY data to be
1947 * dropped on the floor.
1949 conn->asyncStatus = PGASYNC_BUSY;
1950 /* keep waiting to swallow the copy's completion message */
1954 /* In older protocols we have to punt */
1955 printfPQExpBuffer(&conn->errorMessage,
1956 libpq_gettext("COPY OUT state must be terminated first\n"));
1960 else if (resultStatus == PGRES_COPY_BOTH)
1962 /* We don't allow PQexec during COPY BOTH */
1963 printfPQExpBuffer(&conn->errorMessage,
1964 libpq_gettext("PQexec not allowed during COPY BOTH\n"));
1967 /* check for loss of connection, too */
1968 if (conn->status == CONNECTION_BAD)
1972 /* OK to send a command */
1977 * Common code for PQexec and sibling routines: wait for command result
1980 PQexecFinish(PGconn *conn)
1983 PGresult *lastResult;
1986 * For backwards compatibility, return the last result if there are more
1987 * than one --- but merge error messages if we get more than one error
1990 * We have to stop if we see copy in/out/both, however. We will resume
1991 * parsing after application performs the data transfer.
1993 * Also stop if the connection is lost (else we'll loop infinitely).
1996 while ((result = PQgetResult(conn)) != NULL)
2000 if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
2001 result->resultStatus == PGRES_FATAL_ERROR)
2003 pqCatenateResultError(lastResult, result->errMsg);
2005 result = lastResult;
2008 * Make sure PQerrorMessage agrees with concatenated result
2010 resetPQExpBuffer(&conn->errorMessage);
2011 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
2014 PQclear(lastResult);
2016 lastResult = result;
2017 if (result->resultStatus == PGRES_COPY_IN ||
2018 result->resultStatus == PGRES_COPY_OUT ||
2019 result->resultStatus == PGRES_COPY_BOTH ||
2020 conn->status == CONNECTION_BAD)
2028 * PQdescribePrepared
2029 * Obtain information about a previously prepared statement
2031 * If the query was not even sent, return NULL; conn->errorMessage is set to
2032 * a relevant message.
2033 * If the query was sent, a new PGresult is returned (which could indicate
2034 * either success or failure). On success, the PGresult contains status
2035 * PGRES_COMMAND_OK, and its parameter and column-heading fields describe
2036 * the statement's inputs and outputs respectively.
2037 * The user is responsible for freeing the PGresult via PQclear()
2038 * when done with it.
2041 PQdescribePrepared(PGconn *conn, const char *stmt)
2043 if (!PQexecStart(conn))
2045 if (!PQsendDescribe(conn, 'S', stmt))
2047 return PQexecFinish(conn);
2052 * Obtain information about a previously created portal
2054 * This is much like PQdescribePrepared, except that no parameter info is
2055 * returned. Note that at the moment, libpq doesn't really expose portals
2056 * to the client; but this can be used with a portal created by a SQL
2057 * DECLARE CURSOR command.
2060 PQdescribePortal(PGconn *conn, const char *portal)
2062 if (!PQexecStart(conn))
2064 if (!PQsendDescribe(conn, 'P', portal))
2066 return PQexecFinish(conn);
2070 * PQsendDescribePrepared
2071 * Submit a Describe Statement command, but don't wait for it to finish
2073 * Returns: 1 if successfully submitted
2074 * 0 if error (conn->errorMessage is set)
2077 PQsendDescribePrepared(PGconn *conn, const char *stmt)
2079 return PQsendDescribe(conn, 'S', stmt);
2083 * PQsendDescribePortal
2084 * Submit a Describe Portal command, but don't wait for it to finish
2086 * Returns: 1 if successfully submitted
2087 * 0 if error (conn->errorMessage is set)
2090 PQsendDescribePortal(PGconn *conn, const char *portal)
2092 return PQsendDescribe(conn, 'P', portal);
2097 * Common code to send a Describe command
2099 * Available options for desc_type are
2100 * 'S' to describe a prepared statement; or
2101 * 'P' to describe a portal.
2102 * Returns 1 on success and 0 on failure.
2105 PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
2107 /* Treat null desc_target as empty string */
2111 if (!PQsendQueryStart(conn))
2114 /* This isn't gonna work on a 2.0 server */
2115 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2117 printfPQExpBuffer(&conn->errorMessage,
2118 libpq_gettext("function requires at least protocol version 3.0\n"));
2122 /* construct the Describe message */
2123 if (pqPutMsgStart('D', false, conn) < 0 ||
2124 pqPutc(desc_type, conn) < 0 ||
2125 pqPuts(desc_target, conn) < 0 ||
2126 pqPutMsgEnd(conn) < 0)
2129 /* construct the Sync message */
2130 if (pqPutMsgStart('S', false, conn) < 0 ||
2131 pqPutMsgEnd(conn) < 0)
2134 /* remember we are doing a Describe */
2135 conn->queryclass = PGQUERY_DESCRIBE;
2137 /* reset last-query string (not relevant now) */
2138 if (conn->last_query)
2140 free(conn->last_query);
2141 conn->last_query = NULL;
2145 * Give the data a push. In nonblock mode, don't complain if we're unable
2146 * to send it all; PQgetResult() will do any additional flushing needed.
2148 if (pqFlush(conn) < 0)
2151 /* OK, it's launched! */
2152 conn->asyncStatus = PGASYNC_BUSY;
2156 pqHandleSendFailure(conn);
2162 * returns a PGnotify* structure of the latest async notification
2163 * that has not yet been handled
2165 * returns NULL, if there is currently
2166 * no unhandled async notification from the backend
2168 * the CALLER is responsible for FREE'ing the structure returned
2171 PQnotifies(PGconn *conn)
2178 /* Parse any available data to see if we can extract NOTIFY messages. */
2181 event = conn->notifyHead;
2184 conn->notifyHead = event->next;
2185 if (!conn->notifyHead)
2186 conn->notifyTail = NULL;
2187 event->next = NULL; /* don't let app see the internal state */
2193 * PQputCopyData - send some data to the backend during COPY IN or COPY BOTH
2195 * Returns 1 if successful, 0 if data could not be sent (only possible
2196 * in nonblock mode), or -1 if an error occurs.
2199 PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
2203 if (conn->asyncStatus != PGASYNC_COPY_IN &&
2204 conn->asyncStatus != PGASYNC_COPY_BOTH)
2206 printfPQExpBuffer(&conn->errorMessage,
2207 libpq_gettext("no COPY in progress\n"));
2212 * Process any NOTICE or NOTIFY messages that might be pending in the
2213 * input buffer. Since the server might generate many notices during the
2214 * COPY, we want to clean those out reasonably promptly to prevent
2215 * indefinite expansion of the input buffer. (Note: the actual read of
2216 * input data into the input buffer happens down inside pqSendSome, but
2217 * it's not authorized to get rid of the data again.)
2224 * Try to flush any previously sent data in preference to growing the
2225 * output buffer. If we can't enlarge the buffer enough to hold the
2226 * data, return 0 in the nonblock case, else hard error. (For
2227 * simplicity, always assume 5 bytes of overhead even in protocol 2.0
2230 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2232 if (pqFlush(conn) < 0)
2234 if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2236 return pqIsnonblocking(conn) ? 0 : -1;
2238 /* Send the data (too simple to delegate to fe-protocol files) */
2239 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2241 if (pqPutMsgStart('d', false, conn) < 0 ||
2242 pqPutnchar(buffer, nbytes, conn) < 0 ||
2243 pqPutMsgEnd(conn) < 0)
2248 if (pqPutMsgStart(0, false, conn) < 0 ||
2249 pqPutnchar(buffer, nbytes, conn) < 0 ||
2250 pqPutMsgEnd(conn) < 0)
2258 * PQputCopyEnd - send EOF indication to the backend during COPY IN
2260 * After calling this, use PQgetResult() to check command completion status.
2262 * Returns 1 if successful, 0 if data could not be sent (only possible
2263 * in nonblock mode), or -1 if an error occurs.
2266 PQputCopyEnd(PGconn *conn, const char *errormsg)
2270 if (conn->asyncStatus != PGASYNC_COPY_IN &&
2271 conn->asyncStatus != PGASYNC_COPY_BOTH)
2273 printfPQExpBuffer(&conn->errorMessage,
2274 libpq_gettext("no COPY in progress\n"));
2279 * Send the COPY END indicator. This is simple enough that we don't
2280 * bother delegating it to the fe-protocol files.
2282 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2286 /* Send COPY FAIL */
2287 if (pqPutMsgStart('f', false, conn) < 0 ||
2288 pqPuts(errormsg, conn) < 0 ||
2289 pqPutMsgEnd(conn) < 0)
2294 /* Send COPY DONE */
2295 if (pqPutMsgStart('c', false, conn) < 0 ||
2296 pqPutMsgEnd(conn) < 0)
2301 * If we sent the COPY command in extended-query mode, we must issue a
2304 if (conn->queryclass != PGQUERY_SIMPLE)
2306 if (pqPutMsgStart('S', false, conn) < 0 ||
2307 pqPutMsgEnd(conn) < 0)
2315 /* Ooops, no way to do this in 2.0 */
2316 printfPQExpBuffer(&conn->errorMessage,
2317 libpq_gettext("function requires at least protocol version 3.0\n"));
2322 /* Send old-style end-of-data marker */
2323 if (pqPutMsgStart(0, false, conn) < 0 ||
2324 pqPutnchar("\\.\n", 3, conn) < 0 ||
2325 pqPutMsgEnd(conn) < 0)
2330 /* Return to active duty */
2331 if (conn->asyncStatus == PGASYNC_COPY_BOTH)
2332 conn->asyncStatus = PGASYNC_COPY_OUT;
2334 conn->asyncStatus = PGASYNC_BUSY;
2335 resetPQExpBuffer(&conn->errorMessage);
2337 /* Try to flush data */
2338 if (pqFlush(conn) < 0)
2345 * PQgetCopyData - read a row of data from the backend during COPY OUT
2348 * If successful, sets *buffer to point to a malloc'd row of data, and
2349 * returns row length (always > 0) as result.
2350 * Returns 0 if no row available yet (only possible if async is true),
2351 * -1 if end of copy (consult PQgetResult), or -2 if error (consult
2355 PQgetCopyData(PGconn *conn, char **buffer, int async)
2357 *buffer = NULL; /* for all failure cases */
2360 if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2361 conn->asyncStatus != PGASYNC_COPY_BOTH)
2363 printfPQExpBuffer(&conn->errorMessage,
2364 libpq_gettext("no COPY in progress\n"));
2367 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2368 return pqGetCopyData3(conn, buffer, async);
2370 return pqGetCopyData2(conn, buffer, async);
2374 * PQgetline - gets a newline-terminated string from the backend.
2376 * Chiefly here so that applications can use "COPY <rel> to stdout"
2377 * and read the output string. Returns a null-terminated string in s.
2379 * XXX this routine is now deprecated, because it can't handle binary data.
2380 * If called during a COPY BINARY we return EOF.
2382 * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
2383 * the terminating \n (like gets(3)).
2385 * CAUTION: the caller is responsible for detecting the end-of-copy signal
2386 * (a line containing just "\.") when using this routine.
2389 * EOF if error (eg, invalid arguments are given)
2390 * 0 if EOL is reached (i.e., \n has been read)
2391 * (this is required for backward-compatibility -- this
2392 * routine used to always return EOF or 0, assuming that
2393 * the line ended within maxlen bytes.)
2394 * 1 in other cases (i.e., the buffer was filled before \n is reached)
2397 PQgetline(PGconn *conn, char *s, int maxlen)
2399 if (!s || maxlen <= 0)
2402 /* maxlen must be at least 3 to hold the \. terminator! */
2409 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2410 return pqGetline3(conn, s, maxlen);
2412 return pqGetline2(conn, s, maxlen);
2416 * PQgetlineAsync - gets a COPY data row without blocking.
2418 * This routine is for applications that want to do "COPY <rel> to stdout"
2419 * asynchronously, that is without blocking. Having issued the COPY command
2420 * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
2421 * and this routine until the end-of-data signal is detected. Unlike
2422 * PQgetline, this routine takes responsibility for detecting end-of-data.
2424 * On each call, PQgetlineAsync will return data if a complete data row
2425 * is available in libpq's input buffer. Otherwise, no data is returned
2426 * until the rest of the row arrives.
2428 * If -1 is returned, the end-of-data signal has been recognized (and removed
2429 * from libpq's input buffer). The caller *must* next call PQendcopy and
2430 * then return to normal processing.
2433 * -1 if the end-of-copy-data marker has been recognized
2434 * 0 if no data is available
2435 * >0 the number of bytes returned.
2437 * The data returned will not extend beyond a data-row boundary. If possible
2438 * a whole row will be returned at one time. But if the buffer offered by
2439 * the caller is too small to hold a row sent by the backend, then a partial
2440 * data row will be returned. In text mode this can be detected by testing
2441 * whether the last returned byte is '\n' or not.
2443 * The returned data is *not* null-terminated.
2447 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
2452 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2453 return pqGetlineAsync3(conn, buffer, bufsize);
2455 return pqGetlineAsync2(conn, buffer, bufsize);
2459 * PQputline -- sends a string to the backend during COPY IN.
2460 * Returns 0 if OK, EOF if not.
2462 * This is deprecated primarily because the return convention doesn't allow
2463 * caller to tell the difference between a hard error and a nonblock-mode
2467 PQputline(PGconn *conn, const char *s)
2469 return PQputnbytes(conn, s, strlen(s));
2473 * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
2474 * Returns 0 if OK, EOF if not.
2477 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
2479 if (PQputCopyData(conn, buffer, nbytes) > 0)
2487 * After completing the data transfer portion of a copy in/out,
2488 * the application must call this routine to finish the command protocol.
2490 * When using protocol 3.0 this is deprecated; it's cleaner to use PQgetResult
2491 * to get the transfer status. Note however that when using 2.0 protocol,
2492 * recovering from a copy failure often requires a PQreset. PQendcopy will
2493 * take care of that, PQgetResult won't.
2500 PQendcopy(PGconn *conn)
2505 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2506 return pqEndcopy3(conn);
2508 return pqEndcopy2(conn);
2513 * PQfn - Send a function call to the POSTGRES backend.
2515 * conn : backend connection
2516 * fnid : function id
2517 * result_buf : pointer to result buffer (&int if integer)
2518 * result_len : length of return value.
2519 * actual_result_len: actual length returned. (differs from result_len
2520 * for varlena structures.)
2521 * result_type : If the result is an integer, this must be 1,
2522 * otherwise this should be 0
2523 * args : pointer to an array of function arguments.
2524 * (each has length, if integer, and value/pointer)
2525 * nargs : # of arguments in args array.
2528 * PGresult with status = PGRES_COMMAND_OK if successful.
2529 * *actual_result_len is > 0 if there is a return value, 0 if not.
2530 * PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
2531 * NULL on communications failure. conn->errorMessage will be set.
2539 int *actual_result_len,
2541 const PQArgBlock *args,
2544 *actual_result_len = 0;
2549 /* clear the error string */
2550 resetPQExpBuffer(&conn->errorMessage);
2552 if (conn->sock == PGINVALID_SOCKET || conn->asyncStatus != PGASYNC_IDLE ||
2553 conn->result != NULL)
2555 printfPQExpBuffer(&conn->errorMessage,
2556 libpq_gettext("connection in wrong state\n"));
2560 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2561 return pqFunctionCall3(conn, fnid,
2562 result_buf, actual_result_len,
2566 return pqFunctionCall2(conn, fnid,
2567 result_buf, actual_result_len,
2573 /* ====== accessor funcs for PGresult ======== */
2576 PQresultStatus(const PGresult *res)
2579 return PGRES_FATAL_ERROR;
2580 return res->resultStatus;
2584 PQresStatus(ExecStatusType status)
2586 if ((unsigned int) status >= sizeof pgresStatus / sizeof pgresStatus[0])
2587 return libpq_gettext("invalid ExecStatusType code");
2588 return pgresStatus[status];
2592 PQresultErrorMessage(const PGresult *res)
2594 if (!res || !res->errMsg)
2600 PQresultErrorField(const PGresult *res, int fieldcode)
2602 PGMessageField *pfield;
2606 for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
2608 if (pfield->code == fieldcode)
2609 return pfield->contents;
2615 PQntuples(const PGresult *res)
2623 PQnfields(const PGresult *res)
2627 return res->numAttributes;
2631 PQbinaryTuples(const PGresult *res)
2639 * Helper routines to range-check field numbers and tuple numbers.
2640 * Return TRUE if OK, FALSE if not
2644 check_field_number(const PGresult *res, int field_num)
2647 return FALSE; /* no way to display error message... */
2648 if (field_num < 0 || field_num >= res->numAttributes)
2650 pqInternalNotice(&res->noticeHooks,
2651 "column number %d is out of range 0..%d",
2652 field_num, res->numAttributes - 1);
2659 check_tuple_field_number(const PGresult *res,
2660 int tup_num, int field_num)
2663 return FALSE; /* no way to display error message... */
2664 if (tup_num < 0 || tup_num >= res->ntups)
2666 pqInternalNotice(&res->noticeHooks,
2667 "row number %d is out of range 0..%d",
2668 tup_num, res->ntups - 1);
2671 if (field_num < 0 || field_num >= res->numAttributes)
2673 pqInternalNotice(&res->noticeHooks,
2674 "column number %d is out of range 0..%d",
2675 field_num, res->numAttributes - 1);
2682 check_param_number(const PGresult *res, int param_num)
2685 return FALSE; /* no way to display error message... */
2686 if (param_num < 0 || param_num >= res->numParameters)
2688 pqInternalNotice(&res->noticeHooks,
2689 "parameter number %d is out of range 0..%d",
2690 param_num, res->numParameters - 1);
2698 * returns NULL if the field_num is invalid
2701 PQfname(const PGresult *res, int field_num)
2703 if (!check_field_number(res, field_num))
2706 return res->attDescs[field_num].name;
2712 * PQfnumber: find column number given column name
2714 * The column name is parsed as if it were in a SQL statement, including
2715 * case-folding and double-quote processing. But note a possible gotcha:
2716 * downcasing in the frontend might follow different locale rules than
2717 * downcasing in the backend...
2719 * Returns -1 if no match. In the present backend it is also possible
2720 * to have multiple matches, in which case the first one is found.
2723 PQfnumber(const PGresult *res, const char *field_name)
2727 bool all_lower = true;
2736 * Note: it is correct to reject a zero-length input string; the proper
2737 * input to match a zero-length field name would be "".
2739 if (field_name == NULL ||
2740 field_name[0] == '\0' ||
2741 res->attDescs == NULL)
2745 * Check if we can avoid the strdup() and related work because the
2746 * passed-in string wouldn't be changed before we do the check anyway.
2748 for (iptr = field_name; *iptr; iptr++)
2752 if (c == '"' || c != pg_tolower((unsigned char) c))
2760 for (i = 0; i < res->numAttributes; i++)
2761 if (strcmp(field_name, res->attDescs[i].name) == 0)
2764 /* Fall through to the normal check if that didn't work out. */
2767 * Note: this code will not reject partially quoted strings, eg
2768 * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
2771 field_case = strdup(field_name);
2772 if (field_case == NULL)
2773 return -1; /* grotty */
2777 for (iptr = field_case; *iptr; iptr++)
2787 /* doubled quotes become a single quote */
2801 c = pg_tolower((unsigned char) c);
2807 for (i = 0; i < res->numAttributes; i++)
2809 if (strcmp(field_case, res->attDescs[i].name) == 0)
2820 PQftable(const PGresult *res, int field_num)
2822 if (!check_field_number(res, field_num))
2825 return res->attDescs[field_num].tableid;
2831 PQftablecol(const PGresult *res, int field_num)
2833 if (!check_field_number(res, field_num))
2836 return res->attDescs[field_num].columnid;
2842 PQfformat(const PGresult *res, int field_num)
2844 if (!check_field_number(res, field_num))
2847 return res->attDescs[field_num].format;
2853 PQftype(const PGresult *res, int field_num)
2855 if (!check_field_number(res, field_num))
2858 return res->attDescs[field_num].typid;
2864 PQfsize(const PGresult *res, int field_num)
2866 if (!check_field_number(res, field_num))
2869 return res->attDescs[field_num].typlen;
2875 PQfmod(const PGresult *res, int field_num)
2877 if (!check_field_number(res, field_num))
2880 return res->attDescs[field_num].atttypmod;
2886 PQcmdStatus(PGresult *res)
2890 return res->cmdStatus;
2895 * if the last command was an INSERT, return the oid string
2899 PQoidStatus(const PGresult *res)
2902 * This must be enough to hold the result. Don't laugh, this is better
2903 * than what this function used to do.
2905 static char buf[24];
2909 if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2912 len = strspn(res->cmdStatus + 7, "0123456789");
2915 strncpy(buf, res->cmdStatus + 7, len);
2923 * a perhaps preferable form of the above which just returns
2927 PQoidValue(const PGresult *res)
2929 char *endptr = NULL;
2930 unsigned long result;
2933 strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
2934 res->cmdStatus[7] < '0' ||
2935 res->cmdStatus[7] > '9')
2938 result = strtoul(res->cmdStatus + 7, &endptr, 10);
2940 if (!endptr || (*endptr != ' ' && *endptr != '\0'))
2943 return (Oid) result;
2949 * If the last command was INSERT/UPDATE/DELETE/MOVE/FETCH/COPY, return
2950 * a string containing the number of inserted/affected tuples. If not,
2953 * XXX: this should probably return an int
2956 PQcmdTuples(PGresult *res)
2964 if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
2966 p = res->cmdStatus + 7;
2967 /* INSERT: skip oid and space */
2968 while (*p && *p != ' ')
2971 goto interpret_error; /* no space? */
2974 else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
2975 strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
2976 strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
2977 p = res->cmdStatus + 7;
2978 else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
2979 p = res->cmdStatus + 6;
2980 else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
2981 strncmp(res->cmdStatus, "COPY ", 5) == 0)
2982 p = res->cmdStatus + 5;
2986 /* check that we have an integer (at least one digit, nothing else) */
2987 for (c = p; *c; c++)
2989 if (!isdigit((unsigned char) *c))
2990 goto interpret_error;
2993 goto interpret_error;
2998 pqInternalNotice(&res->noticeHooks,
2999 "could not interpret result from server: %s",
3006 * return the value of field 'field_num' of row 'tup_num'
3009 PQgetvalue(const PGresult *res, int tup_num, int field_num)
3011 if (!check_tuple_field_number(res, tup_num, field_num))
3013 return res->tuples[tup_num][field_num].value;
3017 * returns the actual length of a field value in bytes.
3020 PQgetlength(const PGresult *res, int tup_num, int field_num)
3022 if (!check_tuple_field_number(res, tup_num, field_num))
3024 if (res->tuples[tup_num][field_num].len != NULL_LEN)
3025 return res->tuples[tup_num][field_num].len;
3031 * returns the null status of a field value.
3034 PQgetisnull(const PGresult *res, int tup_num, int field_num)
3036 if (!check_tuple_field_number(res, tup_num, field_num))
3037 return 1; /* pretend it is null */
3038 if (res->tuples[tup_num][field_num].len == NULL_LEN)
3045 * returns the number of input parameters of a prepared statement.
3048 PQnparams(const PGresult *res)
3052 return res->numParameters;
3056 * returns type Oid of the specified statement parameter.
3059 PQparamtype(const PGresult *res, int param_num)
3061 if (!check_param_number(res, param_num))
3063 if (res->paramDescs)
3064 return res->paramDescs[param_num].typid;
3070 /* PQsetnonblocking:
3071 * sets the PGconn's database connection non-blocking if the arg is TRUE
3072 * or makes it blocking if the arg is FALSE, this will not protect
3073 * you from PQexec(), you'll only be safe when using the non-blocking API.
3074 * Needs to be called only on a connected database connection.
3077 PQsetnonblocking(PGconn *conn, int arg)
3081 if (!conn || conn->status == CONNECTION_BAD)
3084 barg = (arg ? TRUE : FALSE);
3086 /* early out if the socket is already in the state requested */
3087 if (barg == conn->nonblocking)
3091 * to guarantee constancy for flushing/query/result-polling behavior we
3092 * need to flush the send queue at this point in order to guarantee proper
3093 * behavior. this is ok because either they are making a transition _from_
3094 * or _to_ blocking mode, either way we can block them.
3096 /* if we are going from blocking to non-blocking flush here */
3100 conn->nonblocking = barg;
3106 * return the blocking status of the database connection
3107 * TRUE == nonblocking, FALSE == blocking
3110 PQisnonblocking(const PGconn *conn)
3112 return pqIsnonblocking(conn);
3115 /* libpq is thread-safe? */
3117 PQisthreadsafe(void)
3119 #ifdef ENABLE_THREAD_SAFETY
3127 /* try to force data out, really only useful for non-blocking users */
3129 PQflush(PGconn *conn)
3131 return pqFlush(conn);
3136 * PQfreemem - safely frees memory allocated
3138 * Needed mostly by Win32, unless multithreaded DLL (/MD in VC6)
3139 * Used for freeing memory from PQescapeByte()a/PQunescapeBytea()
3142 PQfreemem(void *ptr)
3148 * PQfreeNotify - free's the memory associated with a PGnotify
3150 * This function is here only for binary backward compatibility.
3151 * New code should use PQfreemem(). A macro will automatically map
3152 * calls to PQfreemem. It should be removed in the future. bjm 2003-03-24
3156 void PQfreeNotify(PGnotify *notify);
3159 PQfreeNotify(PGnotify *notify)
3166 * Escaping arbitrary strings to get valid SQL literal strings.
3168 * Replaces "'" with "''", and if not std_strings, replaces "\" with "\\".
3170 * length is the length of the source string. (Note: if a terminating NUL
3171 * is encountered sooner, PQescapeString stops short of "length"; the behavior
3172 * is thus rather like strncpy.)
3174 * For safety the buffer at "to" must be at least 2*length + 1 bytes long.
3175 * A terminating NUL character is added to the output string, whether the
3176 * input is NUL-terminated or not.
3178 * Returns the actual length of the output (not counting the terminating NUL).
3181 PQescapeStringInternal(PGconn *conn,
3182 char *to, const char *from, size_t length,
3184 int encoding, bool std_strings)
3186 const char *source = from;
3188 size_t remaining = length;
3193 while (remaining > 0 && *source != '\0')
3199 /* Fast path for plain ASCII */
3200 if (!IS_HIGHBIT_SET(c))
3202 /* Apply quoting if needed */
3203 if (SQL_STR_DOUBLE(c, !std_strings))
3205 /* Copy the character */
3212 /* Slow path for possible multibyte characters */
3213 len = pg_encoding_mblen(encoding, source);
3215 /* Copy the character */
3216 for (i = 0; i < len; i++)
3218 if (remaining == 0 || *source == '\0')
3220 *target++ = *source++;
3225 * If we hit premature end of string (ie, incomplete multibyte
3226 * character), try to pad out to the correct length with spaces. We
3227 * may not be able to pad completely, but we will always be able to
3228 * insert at least one pad space (since we'd not have quoted a
3229 * multibyte character). This should be enough to make a string that
3230 * the server will error out on.
3237 printfPQExpBuffer(&conn->errorMessage,
3238 libpq_gettext("incomplete multibyte character\n"));
3239 for (; i < len; i++)
3241 if (((size_t) (target - to)) / 2 >= length)
3249 /* Write the terminating NUL character. */
3256 PQescapeStringConn(PGconn *conn,
3257 char *to, const char *from, size_t length,
3262 /* force empty-string result */
3268 return PQescapeStringInternal(conn, to, from, length, error,
3269 conn->client_encoding,
3274 PQescapeString(char *to, const char *from, size_t length)
3276 return PQescapeStringInternal(NULL, to, from, length, NULL,
3277 static_client_encoding,
3278 static_std_strings);
3283 * Escape arbitrary strings. If as_ident is true, we escape the result
3284 * as an identifier; if false, as a literal. The result is returned in
3285 * a newly allocated buffer. If we fail due to an encoding violation or out
3286 * of memory condition, we return NULL, storing an error message into conn.
3289 PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
3294 int num_quotes = 0; /* single or double, depending on as_ident */
3295 int num_backslashes = 0;
3298 char quote_char = as_ident ? '"' : '\'';
3300 /* We must have a connection, else fail immediately. */
3304 /* Scan the string for characters that must be escaped. */
3305 for (s = str; (s - str) < len && *s != '\0'; ++s)
3307 if (*s == quote_char)
3309 else if (*s == '\\')
3311 else if (IS_HIGHBIT_SET(*s))
3315 /* Slow path for possible multibyte characters */
3316 charlen = pg_encoding_mblen(conn->client_encoding, s);
3318 /* Multibyte character overruns allowable length. */
3319 if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
3321 printfPQExpBuffer(&conn->errorMessage,
3322 libpq_gettext("incomplete multibyte character\n"));
3326 /* Adjust s, bearing in mind that for loop will increment it. */
3331 /* Allocate output buffer. */
3332 input_len = s - str;
3333 result_size = input_len + num_quotes + 3; /* two quotes, plus a NUL */
3334 if (!as_ident && num_backslashes > 0)
3335 result_size += num_backslashes + 2;
3336 result = rp = (char *) malloc(result_size);
3339 printfPQExpBuffer(&conn->errorMessage,
3340 libpq_gettext("out of memory\n"));
3345 * If we are escaping a literal that contains backslashes, we use the
3346 * escape string syntax so that the result is correct under either value
3347 * of standard_conforming_strings. We also emit a leading space in this
3348 * case, to guard against the possibility that the result might be
3349 * interpolated immediately following an identifier.
3351 if (!as_ident && num_backslashes > 0)
3357 /* Opening quote. */
3361 * Use fast path if possible.
3363 * We've already verified that the input string is well-formed in the
3364 * current encoding. If it contains no quotes and, in the case of
3365 * literal-escaping, no backslashes, then we can just copy it directly to
3366 * the output buffer, adding the necessary quotes.
3368 * If not, we must rescan the input and process each character
3371 if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
3373 memcpy(rp, str, input_len);
3378 for (s = str; s - str < input_len; ++s)
3380 if (*s == quote_char || (!as_ident && *s == '\\'))
3385 else if (!IS_HIGHBIT_SET(*s))
3389 int i = pg_encoding_mblen(conn->client_encoding, s);
3396 ++s; /* for loop will provide the final increment */
3402 /* Closing quote and terminating NUL. */
3410 PQescapeLiteral(PGconn *conn, const char *str, size_t len)
3412 return PQescapeInternal(conn, str, len, false);
3416 PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
3418 return PQescapeInternal(conn, str, len, true);
3421 /* HEX encoding support for bytea */
3422 static const char hextbl[] = "0123456789abcdef";
3424 static const int8 hexlookup[128] = {
3425 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3426 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3427 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3428 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
3429 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3430 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3431 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3432 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3440 if (c > 0 && c < 127)
3441 res = hexlookup[(unsigned char) c];
3448 * PQescapeBytea - converts from binary string to the
3449 * minimal encoding necessary to include the string in an SQL
3450 * INSERT statement with a bytea type column as the target.
3452 * We can use either hex or escape (traditional) encoding.
3453 * In escape mode, the following transformations are applied:
3454 * '\0' == ASCII 0 == \000
3455 * '\'' == ASCII 39 == ''
3456 * '\\' == ASCII 92 == \\
3457 * anything < 0x20, or > 0x7e ---> \ooo
3458 * (where ooo is an octal expression)
3460 * If not std_strings, all backslashes sent to the output are doubled.
3462 static unsigned char *
3463 PQescapeByteaInternal(PGconn *conn,
3464 const unsigned char *from, size_t from_length,
3465 size_t *to_length, bool std_strings, bool use_hex)
3467 const unsigned char *vp;
3469 unsigned char *result;
3472 size_t bslash_len = (std_strings ? 1 : 2);
3475 * empty string has 1 char ('\0')
3481 len += bslash_len + 1 + 2 * from_length;
3486 for (i = from_length; i > 0; i--, vp++)
3488 if (*vp < 0x20 || *vp > 0x7e)
3489 len += bslash_len + 3;
3490 else if (*vp == '\'')
3492 else if (*vp == '\\')
3493 len += bslash_len + bslash_len;
3500 rp = result = (unsigned char *) malloc(len);
3504 printfPQExpBuffer(&conn->errorMessage,
3505 libpq_gettext("out of memory\n"));
3518 for (i = from_length; i > 0; i--, vp++)
3520 unsigned char c = *vp;
3524 *rp++ = hextbl[(c >> 4) & 0xF];
3525 *rp++ = hextbl[c & 0xF];
3527 else if (c < 0x20 || c > 0x7e)
3532 *rp++ = (c >> 6) + '0';
3533 *rp++ = ((c >> 3) & 07) + '0';
3534 *rp++ = (c & 07) + '0';
3560 PQescapeByteaConn(PGconn *conn,
3561 const unsigned char *from, size_t from_length,
3566 return PQescapeByteaInternal(conn, from, from_length, to_length,
3568 (conn->sversion >= 90000));
3572 PQescapeBytea(const unsigned char *from, size_t from_length, size_t *to_length)
3574 return PQescapeByteaInternal(NULL, from, from_length, to_length,
3576 false /* can't use hex */ );
3580 #define ISFIRSTOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '3')
3581 #define ISOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '7')
3582 #define OCTVAL(CH) ((CH) - '0')
3585 * PQunescapeBytea - converts the null terminated string representation
3586 * of a bytea, strtext, into binary, filling a buffer. It returns a
3587 * pointer to the buffer (or NULL on error), and the size of the
3588 * buffer in retbuflen. The pointer may subsequently be used as an
3589 * argument to the function PQfreemem.
3591 * The following transformations are made:
3592 * \\ == ASCII 92 == \
3593 * \ooo == a byte whose value = ooo (ooo is an octal number)
3594 * \x == x (x is any character not matched by the above transformations)
3597 PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
3601 unsigned char *buffer,
3606 if (strtext == NULL)
3609 strtextlen = strlen((const char *) strtext);
3611 if (strtext[0] == '\\' && strtext[1] == 'x')
3613 const unsigned char *s;
3616 buflen = (strtextlen - 2) / 2;
3617 /* Avoid unportable malloc(0) */
3618 buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
3630 * Bad input is silently ignored. Note that this includes
3631 * whitespace between hex pairs, which is allowed by byteain.
3634 if (!*s || v1 == (char) -1)
3637 if (v2 != (char) -1)
3638 *p++ = (v1 << 4) | v2;
3641 buflen = p - buffer;
3646 * Length of input is max length of output, but add one to avoid
3647 * unportable malloc(0) if input is zero-length.
3649 buffer = (unsigned char *) malloc(strtextlen + 1);
3653 for (i = j = 0; i < strtextlen;)
3659 if (strtext[i] == '\\')
3660 buffer[j++] = strtext[i++];
3663 if ((ISFIRSTOCTDIGIT(strtext[i])) &&
3664 (ISOCTDIGIT(strtext[i + 1])) &&
3665 (ISOCTDIGIT(strtext[i + 2])))
3669 byte = OCTVAL(strtext[i++]);
3670 byte = (byte << 3) + OCTVAL(strtext[i++]);
3671 byte = (byte << 3) + OCTVAL(strtext[i++]);
3677 * Note: if we see '\' followed by something that isn't a
3678 * recognized escape sequence, we loop around having done
3679 * nothing except advance i. Therefore the something will
3680 * be emitted as ordinary data on the next cycle. Corner
3681 * case: '\' at end of string will just be discarded.
3686 buffer[j++] = strtext[i++];
3690 buflen = j; /* buflen is the length of the dequoted data */
3693 /* Shrink the buffer to be no larger than necessary */
3694 /* +1 avoids unportable behavior when buflen==0 */
3695 tmpbuf = realloc(buffer, buflen + 1);
3697 /* It would only be a very brain-dead realloc that could fail, but... */
3704 *retbuflen = buflen;