1 /*-------------------------------------------------------------------------
4 * functions related to sending a query down to the backend
6 * Portions Copyright (c) 1996-2015, 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 offsetof(PGMessageField, contents) +
899 return; /* out of memory? */
901 strcpy(pfield->contents, value);
902 pfield->next = res->errFields;
903 res->errFields = pfield;
907 * pqSaveParameterStatus - remember parameter status sent by backend
910 pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
912 pgParameterStatus *pstatus;
913 pgParameterStatus *prev;
916 fprintf(conn->Pfdebug, "pqSaveParameterStatus: '%s' = '%s'\n",
920 * Forget any old information about the parameter
922 for (pstatus = conn->pstatus, prev = NULL;
924 prev = pstatus, pstatus = pstatus->next)
926 if (strcmp(pstatus->name, name) == 0)
929 prev->next = pstatus->next;
931 conn->pstatus = pstatus->next;
932 free(pstatus); /* frees name and value strings too */
938 * Store new info as a single malloc block
940 pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
941 strlen(name) +strlen(value) + 2);
946 ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
949 ptr += strlen(name) + 1;
950 pstatus->value = ptr;
952 pstatus->next = conn->pstatus;
953 conn->pstatus = pstatus;
957 * Special hacks: remember client_encoding and
958 * standard_conforming_strings, and convert server version to a numeric
959 * form. We keep the first two of these in static variables as well, so
960 * that PQescapeString and PQescapeBytea can behave somewhat sanely (at
961 * least in single-connection-using programs).
963 if (strcmp(name, "client_encoding") == 0)
965 conn->client_encoding = pg_char_to_encoding(value);
966 /* if we don't recognize the encoding name, fall back to SQL_ASCII */
967 if (conn->client_encoding < 0)
968 conn->client_encoding = PG_SQL_ASCII;
969 static_client_encoding = conn->client_encoding;
971 else if (strcmp(name, "standard_conforming_strings") == 0)
973 conn->std_strings = (strcmp(value, "on") == 0);
974 static_std_strings = conn->std_strings;
976 else if (strcmp(name, "server_version") == 0)
983 cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
986 conn->sversion = 0; /* unknown */
991 conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
999 * Add the received row to the current async result (conn->result).
1000 * Returns 1 if OK, 0 if error occurred.
1002 * On error, *errmsgp can be set to an error string to be returned.
1003 * If it is left NULL, the error is presumed to be "out of memory".
1005 * In single-row mode, we create a new result holding just the current row,
1006 * stashing the previous result in conn->next_result so that it becomes
1007 * active again after pqPrepareAsyncResult(). This allows the result metadata
1008 * (column descriptions) to be carried forward to each result row.
1011 pqRowProcessor(PGconn *conn, const char **errmsgp)
1013 PGresult *res = conn->result;
1014 int nfields = res->numAttributes;
1015 const PGdataValue *columns = conn->rowBuf;
1020 * In single-row mode, make a new PGresult that will hold just this one
1021 * row; the original conn->result is left unchanged so that it can be used
1022 * again as the template for future rows.
1024 if (conn->singleRowMode)
1026 /* Copy everything that should be in the result at this point */
1027 res = PQcopyResult(res,
1028 PG_COPYRES_ATTRS | PG_COPYRES_EVENTS |
1029 PG_COPYRES_NOTICEHOOKS);
1035 * Basically we just allocate space in the PGresult for each field and
1036 * copy the data over.
1038 * Note: on malloc failure, we return 0 leaving *errmsgp still NULL, which
1039 * caller will take to mean "out of memory". This is preferable to trying
1040 * to set up such a message here, because evidently there's not enough
1041 * memory for gettext() to do anything.
1043 tup = (PGresAttValue *)
1044 pqResultAlloc(res, nfields * sizeof(PGresAttValue), TRUE);
1048 for (i = 0; i < nfields; i++)
1050 int clen = columns[i].len;
1055 tup[i].len = NULL_LEN;
1056 tup[i].value = res->null_field;
1060 bool isbinary = (res->attDescs[i].format != 0);
1063 val = (char *) pqResultAlloc(res, clen + 1, isbinary);
1067 /* copy and zero-terminate the data (even if it's binary) */
1068 memcpy(val, columns[i].value, clen);
1076 /* And add the tuple to the PGresult's tuple array */
1077 if (!pqAddTuple(res, tup))
1081 * Success. In single-row mode, make the result available to the client
1084 if (conn->singleRowMode)
1086 /* Change result status to special single-row value */
1087 res->resultStatus = PGRES_SINGLE_TUPLE;
1088 /* Stash old result for re-use later */
1089 conn->next_result = conn->result;
1091 /* And mark the result ready to return */
1092 conn->asyncStatus = PGASYNC_READY;
1098 /* release locally allocated PGresult, if we made one */
1099 if (res != conn->result)
1107 * Submit a query, but don't wait for it to finish
1109 * Returns: 1 if successfully submitted
1110 * 0 if error (conn->errorMessage is set)
1113 PQsendQuery(PGconn *conn, const char *query)
1115 if (!PQsendQueryStart(conn))
1118 /* check the argument */
1121 printfPQExpBuffer(&conn->errorMessage,
1122 libpq_gettext("command string is a null pointer\n"));
1126 /* construct the outgoing Query message */
1127 if (pqPutMsgStart('Q', false, conn) < 0 ||
1128 pqPuts(query, conn) < 0 ||
1129 pqPutMsgEnd(conn) < 0)
1131 pqHandleSendFailure(conn);
1135 /* remember we are using simple query protocol */
1136 conn->queryclass = PGQUERY_SIMPLE;
1138 /* and remember the query text too, if possible */
1139 /* if insufficient memory, last_query just winds up NULL */
1140 if (conn->last_query)
1141 free(conn->last_query);
1142 conn->last_query = strdup(query);
1145 * Give the data a push. In nonblock mode, don't complain if we're unable
1146 * to send it all; PQgetResult() will do any additional flushing needed.
1148 if (pqFlush(conn) < 0)
1150 pqHandleSendFailure(conn);
1154 /* OK, it's launched! */
1155 conn->asyncStatus = PGASYNC_BUSY;
1161 * Like PQsendQuery, but use protocol 3.0 so we can pass parameters
1164 PQsendQueryParams(PGconn *conn,
1165 const char *command,
1167 const Oid *paramTypes,
1168 const char *const * paramValues,
1169 const int *paramLengths,
1170 const int *paramFormats,
1173 if (!PQsendQueryStart(conn))
1176 /* check the arguments */
1179 printfPQExpBuffer(&conn->errorMessage,
1180 libpq_gettext("command string is a null pointer\n"));
1183 if (nParams < 0 || nParams > 65535)
1185 printfPQExpBuffer(&conn->errorMessage,
1186 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1190 return PQsendQueryGuts(conn,
1192 "", /* use unnamed statement */
1203 * Submit a Parse message, but don't wait for it to finish
1205 * Returns: 1 if successfully submitted
1206 * 0 if error (conn->errorMessage is set)
1209 PQsendPrepare(PGconn *conn,
1210 const char *stmtName, const char *query,
1211 int nParams, const Oid *paramTypes)
1213 if (!PQsendQueryStart(conn))
1216 /* check the arguments */
1219 printfPQExpBuffer(&conn->errorMessage,
1220 libpq_gettext("statement name is a null pointer\n"));
1225 printfPQExpBuffer(&conn->errorMessage,
1226 libpq_gettext("command string is a null pointer\n"));
1229 if (nParams < 0 || nParams > 65535)
1231 printfPQExpBuffer(&conn->errorMessage,
1232 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1236 /* This isn't gonna work on a 2.0 server */
1237 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1239 printfPQExpBuffer(&conn->errorMessage,
1240 libpq_gettext("function requires at least protocol version 3.0\n"));
1244 /* construct the Parse message */
1245 if (pqPutMsgStart('P', false, conn) < 0 ||
1246 pqPuts(stmtName, conn) < 0 ||
1247 pqPuts(query, conn) < 0)
1250 if (nParams > 0 && paramTypes)
1254 if (pqPutInt(nParams, 2, conn) < 0)
1256 for (i = 0; i < nParams; i++)
1258 if (pqPutInt(paramTypes[i], 4, conn) < 0)
1264 if (pqPutInt(0, 2, conn) < 0)
1267 if (pqPutMsgEnd(conn) < 0)
1270 /* construct the Sync message */
1271 if (pqPutMsgStart('S', false, conn) < 0 ||
1272 pqPutMsgEnd(conn) < 0)
1275 /* remember we are doing just a Parse */
1276 conn->queryclass = PGQUERY_PREPARE;
1278 /* and remember the query text too, if possible */
1279 /* if insufficient memory, last_query just winds up NULL */
1280 if (conn->last_query)
1281 free(conn->last_query);
1282 conn->last_query = strdup(query);
1285 * Give the data a push. In nonblock mode, don't complain if we're unable
1286 * to send it all; PQgetResult() will do any additional flushing needed.
1288 if (pqFlush(conn) < 0)
1291 /* OK, it's launched! */
1292 conn->asyncStatus = PGASYNC_BUSY;
1296 pqHandleSendFailure(conn);
1301 * PQsendQueryPrepared
1302 * Like PQsendQuery, but execute a previously prepared statement,
1303 * using protocol 3.0 so we can pass parameters
1306 PQsendQueryPrepared(PGconn *conn,
1307 const char *stmtName,
1309 const char *const * paramValues,
1310 const int *paramLengths,
1311 const int *paramFormats,
1314 if (!PQsendQueryStart(conn))
1317 /* check the arguments */
1320 printfPQExpBuffer(&conn->errorMessage,
1321 libpq_gettext("statement name is a null pointer\n"));
1324 if (nParams < 0 || nParams > 65535)
1326 printfPQExpBuffer(&conn->errorMessage,
1327 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1331 return PQsendQueryGuts(conn,
1332 NULL, /* no command to parse */
1335 NULL, /* no param types */
1343 * Common startup code for PQsendQuery and sibling routines
1346 PQsendQueryStart(PGconn *conn)
1351 /* clear the error string */
1352 resetPQExpBuffer(&conn->errorMessage);
1354 /* Don't try to send if we know there's no live connection. */
1355 if (conn->status != CONNECTION_OK)
1357 printfPQExpBuffer(&conn->errorMessage,
1358 libpq_gettext("no connection to the server\n"));
1361 /* Can't send while already busy, either. */
1362 if (conn->asyncStatus != PGASYNC_IDLE)
1364 printfPQExpBuffer(&conn->errorMessage,
1365 libpq_gettext("another command is already in progress\n"));
1369 /* initialize async result-accumulation state */
1370 conn->result = NULL;
1371 conn->next_result = NULL;
1373 /* reset single-row processing mode */
1374 conn->singleRowMode = false;
1376 /* ready to send command message */
1382 * Common code for protocol-3.0 query sending
1383 * PQsendQueryStart should be done already
1385 * command may be NULL to indicate we use an already-prepared statement
1388 PQsendQueryGuts(PGconn *conn,
1389 const char *command,
1390 const char *stmtName,
1392 const Oid *paramTypes,
1393 const char *const * paramValues,
1394 const int *paramLengths,
1395 const int *paramFormats,
1400 /* This isn't gonna work on a 2.0 server */
1401 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1403 printfPQExpBuffer(&conn->errorMessage,
1404 libpq_gettext("function requires at least protocol version 3.0\n"));
1409 * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync,
1410 * using specified statement name and the unnamed portal.
1415 /* construct the Parse message */
1416 if (pqPutMsgStart('P', false, conn) < 0 ||
1417 pqPuts(stmtName, conn) < 0 ||
1418 pqPuts(command, conn) < 0)
1420 if (nParams > 0 && paramTypes)
1422 if (pqPutInt(nParams, 2, conn) < 0)
1424 for (i = 0; i < nParams; i++)
1426 if (pqPutInt(paramTypes[i], 4, conn) < 0)
1432 if (pqPutInt(0, 2, conn) < 0)
1435 if (pqPutMsgEnd(conn) < 0)
1439 /* Construct the Bind message */
1440 if (pqPutMsgStart('B', false, conn) < 0 ||
1441 pqPuts("", conn) < 0 ||
1442 pqPuts(stmtName, conn) < 0)
1445 /* Send parameter formats */
1446 if (nParams > 0 && paramFormats)
1448 if (pqPutInt(nParams, 2, conn) < 0)
1450 for (i = 0; i < nParams; i++)
1452 if (pqPutInt(paramFormats[i], 2, conn) < 0)
1458 if (pqPutInt(0, 2, conn) < 0)
1462 if (pqPutInt(nParams, 2, conn) < 0)
1465 /* Send parameters */
1466 for (i = 0; i < nParams; i++)
1468 if (paramValues && paramValues[i])
1472 if (paramFormats && paramFormats[i] != 0)
1474 /* binary parameter */
1476 nbytes = paramLengths[i];
1479 printfPQExpBuffer(&conn->errorMessage,
1480 libpq_gettext("length must be given for binary parameter\n"));
1486 /* text parameter, do not use paramLengths */
1487 nbytes = strlen(paramValues[i]);
1489 if (pqPutInt(nbytes, 4, conn) < 0 ||
1490 pqPutnchar(paramValues[i], nbytes, conn) < 0)
1495 /* take the param as NULL */
1496 if (pqPutInt(-1, 4, conn) < 0)
1500 if (pqPutInt(1, 2, conn) < 0 ||
1501 pqPutInt(resultFormat, 2, conn))
1503 if (pqPutMsgEnd(conn) < 0)
1506 /* construct the Describe Portal message */
1507 if (pqPutMsgStart('D', false, conn) < 0 ||
1508 pqPutc('P', conn) < 0 ||
1509 pqPuts("", conn) < 0 ||
1510 pqPutMsgEnd(conn) < 0)
1513 /* construct the Execute message */
1514 if (pqPutMsgStart('E', false, conn) < 0 ||
1515 pqPuts("", conn) < 0 ||
1516 pqPutInt(0, 4, conn) < 0 ||
1517 pqPutMsgEnd(conn) < 0)
1520 /* construct the Sync message */
1521 if (pqPutMsgStart('S', false, conn) < 0 ||
1522 pqPutMsgEnd(conn) < 0)
1525 /* remember we are using extended query protocol */
1526 conn->queryclass = PGQUERY_EXTENDED;
1528 /* and remember the query text too, if possible */
1529 /* if insufficient memory, last_query just winds up NULL */
1530 if (conn->last_query)
1531 free(conn->last_query);
1533 conn->last_query = strdup(command);
1535 conn->last_query = NULL;
1538 * Give the data a push. In nonblock mode, don't complain if we're unable
1539 * to send it all; PQgetResult() will do any additional flushing needed.
1541 if (pqFlush(conn) < 0)
1544 /* OK, it's launched! */
1545 conn->asyncStatus = PGASYNC_BUSY;
1549 pqHandleSendFailure(conn);
1554 * pqHandleSendFailure: try to clean up after failure to send command.
1556 * Primarily, what we want to accomplish here is to process an async
1557 * NOTICE message that the backend might have sent just before it died.
1559 * NOTE: this routine should only be called in PGASYNC_IDLE state.
1562 pqHandleSendFailure(PGconn *conn)
1565 * Accept any available input data, ignoring errors. Note that if
1566 * pqReadData decides the backend has closed the channel, it will close
1567 * our side of the socket --- that's just what we want here.
1569 while (pqReadData(conn) > 0)
1570 /* loop until no more data readable */ ;
1573 * Parse any available input messages. Since we are in PGASYNC_IDLE
1574 * state, only NOTICE and NOTIFY messages will be eaten.
1580 * Select row-by-row processing mode
1583 PQsetSingleRowMode(PGconn *conn)
1586 * Only allow setting the flag when we have launched a query and not yet
1587 * received any results.
1591 if (conn->asyncStatus != PGASYNC_BUSY)
1593 if (conn->queryclass != PGQUERY_SIMPLE &&
1594 conn->queryclass != PGQUERY_EXTENDED)
1600 conn->singleRowMode = true;
1605 * Consume any available input from the backend
1606 * 0 return: some kind of trouble
1607 * 1 return: no problem
1610 PQconsumeInput(PGconn *conn)
1616 * for non-blocking connections try to flush the send-queue, otherwise we
1617 * may never get a response for something that may not have already been
1618 * sent because it's in our write buffer!
1620 if (pqIsnonblocking(conn))
1622 if (pqFlush(conn) < 0)
1627 * Load more data, if available. We do this no matter what state we are
1628 * in, since we are probably getting called because the application wants
1629 * to get rid of a read-select condition. Note that we will NOT block
1630 * waiting for more input.
1632 if (pqReadData(conn) < 0)
1635 /* Parsing of the data waits till later. */
1641 * parseInput: if appropriate, parse input data from backend
1642 * until input is exhausted or a stopping state is reached.
1643 * Note that this function will NOT attempt to read more data from the backend.
1646 parseInput(PGconn *conn)
1648 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1649 pqParseInput3(conn);
1651 pqParseInput2(conn);
1656 * Return TRUE if PQgetResult would block waiting for input.
1660 PQisBusy(PGconn *conn)
1665 /* Parse any available data, if our state permits. */
1668 /* PQgetResult will return immediately in all states except BUSY. */
1669 return conn->asyncStatus == PGASYNC_BUSY;
1675 * Get the next PGresult produced by a query. Returns NULL if no
1676 * query work remains or an error has occurred (e.g. out of
1681 PQgetResult(PGconn *conn)
1688 /* Parse any available data, if our state permits. */
1691 /* If not ready to return something, block until we are. */
1692 while (conn->asyncStatus == PGASYNC_BUSY)
1697 * If data remains unsent, send it. Else we might be waiting for the
1698 * result of a command the backend hasn't even got yet.
1700 while ((flushResult = pqFlush(conn)) > 0)
1702 if (pqWait(FALSE, TRUE, conn))
1709 /* Wait for some more data, and load it. */
1711 pqWait(TRUE, FALSE, conn) ||
1712 pqReadData(conn) < 0)
1715 * conn->errorMessage has been set by pqWait or pqReadData. We
1716 * want to append it to any already-received error message.
1718 pqSaveErrorResult(conn);
1719 conn->asyncStatus = PGASYNC_IDLE;
1720 return pqPrepareAsyncResult(conn);
1727 /* Return the appropriate thing. */
1728 switch (conn->asyncStatus)
1731 res = NULL; /* query is complete */
1734 res = pqPrepareAsyncResult(conn);
1735 /* Set the state back to BUSY, allowing parsing to proceed. */
1736 conn->asyncStatus = PGASYNC_BUSY;
1738 case PGASYNC_COPY_IN:
1739 res = getCopyResult(conn, PGRES_COPY_IN);
1741 case PGASYNC_COPY_OUT:
1742 res = getCopyResult(conn, PGRES_COPY_OUT);
1744 case PGASYNC_COPY_BOTH:
1745 res = getCopyResult(conn, PGRES_COPY_BOTH);
1748 printfPQExpBuffer(&conn->errorMessage,
1749 libpq_gettext("unexpected asyncStatus: %d\n"),
1750 (int) conn->asyncStatus);
1751 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1759 for (i = 0; i < res->nEvents; i++)
1761 PGEventResultCreate evt;
1765 if (!res->events[i].proc(PGEVT_RESULTCREATE, &evt,
1766 res->events[i].passThrough))
1768 printfPQExpBuffer(&conn->errorMessage,
1769 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_RESULTCREATE event\n"),
1770 res->events[i].name);
1771 pqSetResultError(res, conn->errorMessage.data);
1772 res->resultStatus = PGRES_FATAL_ERROR;
1775 res->events[i].resultInitialized = TRUE;
1784 * Helper for PQgetResult: generate result for COPY-in-progress cases
1787 getCopyResult(PGconn *conn, ExecStatusType copytype)
1790 * If the server connection has been lost, don't pretend everything is
1791 * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
1792 * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
1793 * error in the earlier steps in PQgetResult). The text returned in the
1794 * result is whatever is in conn->errorMessage; we hope that was filled
1795 * with something relevant when the lost connection was detected.
1797 if (conn->status != CONNECTION_OK)
1799 pqSaveErrorResult(conn);
1800 conn->asyncStatus = PGASYNC_IDLE;
1801 return pqPrepareAsyncResult(conn);
1804 /* If we have an async result for the COPY, return that */
1805 if (conn->result && conn->result->resultStatus == copytype)
1806 return pqPrepareAsyncResult(conn);
1808 /* Otherwise, invent a suitable PGresult */
1809 return PQmakeEmptyPGresult(conn, copytype);
1815 * send a query to the backend and package up the result in a PGresult
1817 * If the query was not even sent, return NULL; conn->errorMessage is set to
1818 * a relevant message.
1819 * If the query was sent, a new PGresult is returned (which could indicate
1820 * either success or failure).
1821 * The user is responsible for freeing the PGresult via PQclear()
1822 * when done with it.
1825 PQexec(PGconn *conn, const char *query)
1827 if (!PQexecStart(conn))
1829 if (!PQsendQuery(conn, query))
1831 return PQexecFinish(conn);
1836 * Like PQexec, but use protocol 3.0 so we can pass parameters
1839 PQexecParams(PGconn *conn,
1840 const char *command,
1842 const Oid *paramTypes,
1843 const char *const * paramValues,
1844 const int *paramLengths,
1845 const int *paramFormats,
1848 if (!PQexecStart(conn))
1850 if (!PQsendQueryParams(conn, command,
1851 nParams, paramTypes, paramValues, paramLengths,
1852 paramFormats, resultFormat))
1854 return PQexecFinish(conn);
1859 * Creates a prepared statement by issuing a v3.0 parse message.
1861 * If the query was not even sent, return NULL; conn->errorMessage is set to
1862 * a relevant message.
1863 * If the query was sent, a new PGresult is returned (which could indicate
1864 * either success or failure).
1865 * The user is responsible for freeing the PGresult via PQclear()
1866 * when done with it.
1869 PQprepare(PGconn *conn,
1870 const char *stmtName, const char *query,
1871 int nParams, const Oid *paramTypes)
1873 if (!PQexecStart(conn))
1875 if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
1877 return PQexecFinish(conn);
1882 * Like PQexec, but execute a previously prepared statement,
1883 * using protocol 3.0 so we can pass parameters
1886 PQexecPrepared(PGconn *conn,
1887 const char *stmtName,
1889 const char *const * paramValues,
1890 const int *paramLengths,
1891 const int *paramFormats,
1894 if (!PQexecStart(conn))
1896 if (!PQsendQueryPrepared(conn, stmtName,
1897 nParams, paramValues, paramLengths,
1898 paramFormats, resultFormat))
1900 return PQexecFinish(conn);
1904 * Common code for PQexec and sibling routines: prepare to send command
1907 PQexecStart(PGconn *conn)
1915 * Silently discard any prior query result that application didn't eat.
1916 * This is probably poor design, but it's here for backward compatibility.
1918 while ((result = PQgetResult(conn)) != NULL)
1920 ExecStatusType resultStatus = result->resultStatus;
1922 PQclear(result); /* only need its status */
1923 if (resultStatus == PGRES_COPY_IN)
1925 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1927 /* In protocol 3, we can get out of a COPY IN state */
1928 if (PQputCopyEnd(conn,
1929 libpq_gettext("COPY terminated by new PQexec")) < 0)
1931 /* keep waiting to swallow the copy's failure message */
1935 /* In older protocols we have to punt */
1936 printfPQExpBuffer(&conn->errorMessage,
1937 libpq_gettext("COPY IN state must be terminated first\n"));
1941 else if (resultStatus == PGRES_COPY_OUT)
1943 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1946 * In protocol 3, we can get out of a COPY OUT state: we just
1947 * switch back to BUSY and allow the remaining COPY data to be
1948 * dropped on the floor.
1950 conn->asyncStatus = PGASYNC_BUSY;
1951 /* keep waiting to swallow the copy's completion message */
1955 /* In older protocols we have to punt */
1956 printfPQExpBuffer(&conn->errorMessage,
1957 libpq_gettext("COPY OUT state must be terminated first\n"));
1961 else if (resultStatus == PGRES_COPY_BOTH)
1963 /* We don't allow PQexec during COPY BOTH */
1964 printfPQExpBuffer(&conn->errorMessage,
1965 libpq_gettext("PQexec not allowed during COPY BOTH\n"));
1968 /* check for loss of connection, too */
1969 if (conn->status == CONNECTION_BAD)
1973 /* OK to send a command */
1978 * Common code for PQexec and sibling routines: wait for command result
1981 PQexecFinish(PGconn *conn)
1984 PGresult *lastResult;
1987 * For backwards compatibility, return the last result if there are more
1988 * than one --- but merge error messages if we get more than one error
1991 * We have to stop if we see copy in/out/both, however. We will resume
1992 * parsing after application performs the data transfer.
1994 * Also stop if the connection is lost (else we'll loop infinitely).
1997 while ((result = PQgetResult(conn)) != NULL)
2001 if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
2002 result->resultStatus == PGRES_FATAL_ERROR)
2004 pqCatenateResultError(lastResult, result->errMsg);
2006 result = lastResult;
2009 * Make sure PQerrorMessage agrees with concatenated result
2011 resetPQExpBuffer(&conn->errorMessage);
2012 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
2015 PQclear(lastResult);
2017 lastResult = result;
2018 if (result->resultStatus == PGRES_COPY_IN ||
2019 result->resultStatus == PGRES_COPY_OUT ||
2020 result->resultStatus == PGRES_COPY_BOTH ||
2021 conn->status == CONNECTION_BAD)
2029 * PQdescribePrepared
2030 * Obtain information about a previously prepared statement
2032 * If the query was not even sent, return NULL; conn->errorMessage is set to
2033 * a relevant message.
2034 * If the query was sent, a new PGresult is returned (which could indicate
2035 * either success or failure). On success, the PGresult contains status
2036 * PGRES_COMMAND_OK, and its parameter and column-heading fields describe
2037 * the statement's inputs and outputs respectively.
2038 * The user is responsible for freeing the PGresult via PQclear()
2039 * when done with it.
2042 PQdescribePrepared(PGconn *conn, const char *stmt)
2044 if (!PQexecStart(conn))
2046 if (!PQsendDescribe(conn, 'S', stmt))
2048 return PQexecFinish(conn);
2053 * Obtain information about a previously created portal
2055 * This is much like PQdescribePrepared, except that no parameter info is
2056 * returned. Note that at the moment, libpq doesn't really expose portals
2057 * to the client; but this can be used with a portal created by a SQL
2058 * DECLARE CURSOR command.
2061 PQdescribePortal(PGconn *conn, const char *portal)
2063 if (!PQexecStart(conn))
2065 if (!PQsendDescribe(conn, 'P', portal))
2067 return PQexecFinish(conn);
2071 * PQsendDescribePrepared
2072 * Submit a Describe Statement command, but don't wait for it to finish
2074 * Returns: 1 if successfully submitted
2075 * 0 if error (conn->errorMessage is set)
2078 PQsendDescribePrepared(PGconn *conn, const char *stmt)
2080 return PQsendDescribe(conn, 'S', stmt);
2084 * PQsendDescribePortal
2085 * Submit a Describe Portal command, but don't wait for it to finish
2087 * Returns: 1 if successfully submitted
2088 * 0 if error (conn->errorMessage is set)
2091 PQsendDescribePortal(PGconn *conn, const char *portal)
2093 return PQsendDescribe(conn, 'P', portal);
2098 * Common code to send a Describe command
2100 * Available options for desc_type are
2101 * 'S' to describe a prepared statement; or
2102 * 'P' to describe a portal.
2103 * Returns 1 on success and 0 on failure.
2106 PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
2108 /* Treat null desc_target as empty string */
2112 if (!PQsendQueryStart(conn))
2115 /* This isn't gonna work on a 2.0 server */
2116 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2118 printfPQExpBuffer(&conn->errorMessage,
2119 libpq_gettext("function requires at least protocol version 3.0\n"));
2123 /* construct the Describe message */
2124 if (pqPutMsgStart('D', false, conn) < 0 ||
2125 pqPutc(desc_type, conn) < 0 ||
2126 pqPuts(desc_target, conn) < 0 ||
2127 pqPutMsgEnd(conn) < 0)
2130 /* construct the Sync message */
2131 if (pqPutMsgStart('S', false, conn) < 0 ||
2132 pqPutMsgEnd(conn) < 0)
2135 /* remember we are doing a Describe */
2136 conn->queryclass = PGQUERY_DESCRIBE;
2138 /* reset last-query string (not relevant now) */
2139 if (conn->last_query)
2141 free(conn->last_query);
2142 conn->last_query = NULL;
2146 * Give the data a push. In nonblock mode, don't complain if we're unable
2147 * to send it all; PQgetResult() will do any additional flushing needed.
2149 if (pqFlush(conn) < 0)
2152 /* OK, it's launched! */
2153 conn->asyncStatus = PGASYNC_BUSY;
2157 pqHandleSendFailure(conn);
2163 * returns a PGnotify* structure of the latest async notification
2164 * that has not yet been handled
2166 * returns NULL, if there is currently
2167 * no unhandled async notification from the backend
2169 * the CALLER is responsible for FREE'ing the structure returned
2172 PQnotifies(PGconn *conn)
2179 /* Parse any available data to see if we can extract NOTIFY messages. */
2182 event = conn->notifyHead;
2185 conn->notifyHead = event->next;
2186 if (!conn->notifyHead)
2187 conn->notifyTail = NULL;
2188 event->next = NULL; /* don't let app see the internal state */
2194 * PQputCopyData - send some data to the backend during COPY IN or COPY BOTH
2196 * Returns 1 if successful, 0 if data could not be sent (only possible
2197 * in nonblock mode), or -1 if an error occurs.
2200 PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
2204 if (conn->asyncStatus != PGASYNC_COPY_IN &&
2205 conn->asyncStatus != PGASYNC_COPY_BOTH)
2207 printfPQExpBuffer(&conn->errorMessage,
2208 libpq_gettext("no COPY in progress\n"));
2213 * Process any NOTICE or NOTIFY messages that might be pending in the
2214 * input buffer. Since the server might generate many notices during the
2215 * COPY, we want to clean those out reasonably promptly to prevent
2216 * indefinite expansion of the input buffer. (Note: the actual read of
2217 * input data into the input buffer happens down inside pqSendSome, but
2218 * it's not authorized to get rid of the data again.)
2225 * Try to flush any previously sent data in preference to growing the
2226 * output buffer. If we can't enlarge the buffer enough to hold the
2227 * data, return 0 in the nonblock case, else hard error. (For
2228 * simplicity, always assume 5 bytes of overhead even in protocol 2.0
2231 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2233 if (pqFlush(conn) < 0)
2235 if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2237 return pqIsnonblocking(conn) ? 0 : -1;
2239 /* Send the data (too simple to delegate to fe-protocol files) */
2240 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2242 if (pqPutMsgStart('d', false, conn) < 0 ||
2243 pqPutnchar(buffer, nbytes, conn) < 0 ||
2244 pqPutMsgEnd(conn) < 0)
2249 if (pqPutMsgStart(0, false, conn) < 0 ||
2250 pqPutnchar(buffer, nbytes, conn) < 0 ||
2251 pqPutMsgEnd(conn) < 0)
2259 * PQputCopyEnd - send EOF indication to the backend during COPY IN
2261 * After calling this, use PQgetResult() to check command completion status.
2263 * Returns 1 if successful, 0 if data could not be sent (only possible
2264 * in nonblock mode), or -1 if an error occurs.
2267 PQputCopyEnd(PGconn *conn, const char *errormsg)
2271 if (conn->asyncStatus != PGASYNC_COPY_IN &&
2272 conn->asyncStatus != PGASYNC_COPY_BOTH)
2274 printfPQExpBuffer(&conn->errorMessage,
2275 libpq_gettext("no COPY in progress\n"));
2280 * Send the COPY END indicator. This is simple enough that we don't
2281 * bother delegating it to the fe-protocol files.
2283 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2287 /* Send COPY FAIL */
2288 if (pqPutMsgStart('f', false, conn) < 0 ||
2289 pqPuts(errormsg, conn) < 0 ||
2290 pqPutMsgEnd(conn) < 0)
2295 /* Send COPY DONE */
2296 if (pqPutMsgStart('c', false, conn) < 0 ||
2297 pqPutMsgEnd(conn) < 0)
2302 * If we sent the COPY command in extended-query mode, we must issue a
2305 if (conn->queryclass != PGQUERY_SIMPLE)
2307 if (pqPutMsgStart('S', false, conn) < 0 ||
2308 pqPutMsgEnd(conn) < 0)
2316 /* Ooops, no way to do this in 2.0 */
2317 printfPQExpBuffer(&conn->errorMessage,
2318 libpq_gettext("function requires at least protocol version 3.0\n"));
2323 /* Send old-style end-of-data marker */
2324 if (pqPutMsgStart(0, false, conn) < 0 ||
2325 pqPutnchar("\\.\n", 3, conn) < 0 ||
2326 pqPutMsgEnd(conn) < 0)
2331 /* Return to active duty */
2332 if (conn->asyncStatus == PGASYNC_COPY_BOTH)
2333 conn->asyncStatus = PGASYNC_COPY_OUT;
2335 conn->asyncStatus = PGASYNC_BUSY;
2336 resetPQExpBuffer(&conn->errorMessage);
2338 /* Try to flush data */
2339 if (pqFlush(conn) < 0)
2346 * PQgetCopyData - read a row of data from the backend during COPY OUT
2349 * If successful, sets *buffer to point to a malloc'd row of data, and
2350 * returns row length (always > 0) as result.
2351 * Returns 0 if no row available yet (only possible if async is true),
2352 * -1 if end of copy (consult PQgetResult), or -2 if error (consult
2356 PQgetCopyData(PGconn *conn, char **buffer, int async)
2358 *buffer = NULL; /* for all failure cases */
2361 if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2362 conn->asyncStatus != PGASYNC_COPY_BOTH)
2364 printfPQExpBuffer(&conn->errorMessage,
2365 libpq_gettext("no COPY in progress\n"));
2368 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2369 return pqGetCopyData3(conn, buffer, async);
2371 return pqGetCopyData2(conn, buffer, async);
2375 * PQgetline - gets a newline-terminated string from the backend.
2377 * Chiefly here so that applications can use "COPY <rel> to stdout"
2378 * and read the output string. Returns a null-terminated string in s.
2380 * XXX this routine is now deprecated, because it can't handle binary data.
2381 * If called during a COPY BINARY we return EOF.
2383 * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
2384 * the terminating \n (like gets(3)).
2386 * CAUTION: the caller is responsible for detecting the end-of-copy signal
2387 * (a line containing just "\.") when using this routine.
2390 * EOF if error (eg, invalid arguments are given)
2391 * 0 if EOL is reached (i.e., \n has been read)
2392 * (this is required for backward-compatibility -- this
2393 * routine used to always return EOF or 0, assuming that
2394 * the line ended within maxlen bytes.)
2395 * 1 in other cases (i.e., the buffer was filled before \n is reached)
2398 PQgetline(PGconn *conn, char *s, int maxlen)
2400 if (!s || maxlen <= 0)
2403 /* maxlen must be at least 3 to hold the \. terminator! */
2410 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2411 return pqGetline3(conn, s, maxlen);
2413 return pqGetline2(conn, s, maxlen);
2417 * PQgetlineAsync - gets a COPY data row without blocking.
2419 * This routine is for applications that want to do "COPY <rel> to stdout"
2420 * asynchronously, that is without blocking. Having issued the COPY command
2421 * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
2422 * and this routine until the end-of-data signal is detected. Unlike
2423 * PQgetline, this routine takes responsibility for detecting end-of-data.
2425 * On each call, PQgetlineAsync will return data if a complete data row
2426 * is available in libpq's input buffer. Otherwise, no data is returned
2427 * until the rest of the row arrives.
2429 * If -1 is returned, the end-of-data signal has been recognized (and removed
2430 * from libpq's input buffer). The caller *must* next call PQendcopy and
2431 * then return to normal processing.
2434 * -1 if the end-of-copy-data marker has been recognized
2435 * 0 if no data is available
2436 * >0 the number of bytes returned.
2438 * The data returned will not extend beyond a data-row boundary. If possible
2439 * a whole row will be returned at one time. But if the buffer offered by
2440 * the caller is too small to hold a row sent by the backend, then a partial
2441 * data row will be returned. In text mode this can be detected by testing
2442 * whether the last returned byte is '\n' or not.
2444 * The returned data is *not* null-terminated.
2448 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
2453 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2454 return pqGetlineAsync3(conn, buffer, bufsize);
2456 return pqGetlineAsync2(conn, buffer, bufsize);
2460 * PQputline -- sends a string to the backend during COPY IN.
2461 * Returns 0 if OK, EOF if not.
2463 * This is deprecated primarily because the return convention doesn't allow
2464 * caller to tell the difference between a hard error and a nonblock-mode
2468 PQputline(PGconn *conn, const char *s)
2470 return PQputnbytes(conn, s, strlen(s));
2474 * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
2475 * Returns 0 if OK, EOF if not.
2478 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
2480 if (PQputCopyData(conn, buffer, nbytes) > 0)
2488 * After completing the data transfer portion of a copy in/out,
2489 * the application must call this routine to finish the command protocol.
2491 * When using protocol 3.0 this is deprecated; it's cleaner to use PQgetResult
2492 * to get the transfer status. Note however that when using 2.0 protocol,
2493 * recovering from a copy failure often requires a PQreset. PQendcopy will
2494 * take care of that, PQgetResult won't.
2501 PQendcopy(PGconn *conn)
2506 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2507 return pqEndcopy3(conn);
2509 return pqEndcopy2(conn);
2514 * PQfn - Send a function call to the POSTGRES backend.
2516 * conn : backend connection
2517 * fnid : OID of function to be called
2518 * result_buf : pointer to result buffer
2519 * result_len : actual length of result is returned here
2520 * result_is_int : If the result is an integer, this must be 1,
2521 * otherwise this should be 0
2522 * args : pointer to an array of function arguments
2523 * (each has length, if integer, and value/pointer)
2524 * nargs : # of arguments in args array.
2527 * PGresult with status = PGRES_COMMAND_OK if successful.
2528 * *result_len is > 0 if there is a return value, 0 if not.
2529 * PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
2530 * NULL on communications failure. conn->errorMessage will be set.
2540 const PQArgBlock *args,
2548 /* clear the error string */
2549 resetPQExpBuffer(&conn->errorMessage);
2551 if (conn->sock == PGINVALID_SOCKET || conn->asyncStatus != PGASYNC_IDLE ||
2552 conn->result != NULL)
2554 printfPQExpBuffer(&conn->errorMessage,
2555 libpq_gettext("connection in wrong state\n"));
2559 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2560 return pqFunctionCall3(conn, fnid,
2561 result_buf, result_len,
2565 return pqFunctionCall2(conn, fnid,
2566 result_buf, result_len,
2572 /* ====== accessor funcs for PGresult ======== */
2575 PQresultStatus(const PGresult *res)
2578 return PGRES_FATAL_ERROR;
2579 return res->resultStatus;
2583 PQresStatus(ExecStatusType status)
2585 if ((unsigned int) status >= sizeof pgresStatus / sizeof pgresStatus[0])
2586 return libpq_gettext("invalid ExecStatusType code");
2587 return pgresStatus[status];
2591 PQresultErrorMessage(const PGresult *res)
2593 if (!res || !res->errMsg)
2599 PQresultErrorField(const PGresult *res, int fieldcode)
2601 PGMessageField *pfield;
2605 for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
2607 if (pfield->code == fieldcode)
2608 return pfield->contents;
2614 PQntuples(const PGresult *res)
2622 PQnfields(const PGresult *res)
2626 return res->numAttributes;
2630 PQbinaryTuples(const PGresult *res)
2638 * Helper routines to range-check field numbers and tuple numbers.
2639 * Return TRUE if OK, FALSE if not
2643 check_field_number(const PGresult *res, int field_num)
2646 return FALSE; /* no way to display error message... */
2647 if (field_num < 0 || field_num >= res->numAttributes)
2649 pqInternalNotice(&res->noticeHooks,
2650 "column number %d is out of range 0..%d",
2651 field_num, res->numAttributes - 1);
2658 check_tuple_field_number(const PGresult *res,
2659 int tup_num, int field_num)
2662 return FALSE; /* no way to display error message... */
2663 if (tup_num < 0 || tup_num >= res->ntups)
2665 pqInternalNotice(&res->noticeHooks,
2666 "row number %d is out of range 0..%d",
2667 tup_num, res->ntups - 1);
2670 if (field_num < 0 || field_num >= res->numAttributes)
2672 pqInternalNotice(&res->noticeHooks,
2673 "column number %d is out of range 0..%d",
2674 field_num, res->numAttributes - 1);
2681 check_param_number(const PGresult *res, int param_num)
2684 return FALSE; /* no way to display error message... */
2685 if (param_num < 0 || param_num >= res->numParameters)
2687 pqInternalNotice(&res->noticeHooks,
2688 "parameter number %d is out of range 0..%d",
2689 param_num, res->numParameters - 1);
2697 * returns NULL if the field_num is invalid
2700 PQfname(const PGresult *res, int field_num)
2702 if (!check_field_number(res, field_num))
2705 return res->attDescs[field_num].name;
2711 * PQfnumber: find column number given column name
2713 * The column name is parsed as if it were in a SQL statement, including
2714 * case-folding and double-quote processing. But note a possible gotcha:
2715 * downcasing in the frontend might follow different locale rules than
2716 * downcasing in the backend...
2718 * Returns -1 if no match. In the present backend it is also possible
2719 * to have multiple matches, in which case the first one is found.
2722 PQfnumber(const PGresult *res, const char *field_name)
2726 bool all_lower = true;
2735 * Note: it is correct to reject a zero-length input string; the proper
2736 * input to match a zero-length field name would be "".
2738 if (field_name == NULL ||
2739 field_name[0] == '\0' ||
2740 res->attDescs == NULL)
2744 * Check if we can avoid the strdup() and related work because the
2745 * passed-in string wouldn't be changed before we do the check anyway.
2747 for (iptr = field_name; *iptr; iptr++)
2751 if (c == '"' || c != pg_tolower((unsigned char) c))
2759 for (i = 0; i < res->numAttributes; i++)
2760 if (strcmp(field_name, res->attDescs[i].name) == 0)
2763 /* Fall through to the normal check if that didn't work out. */
2766 * Note: this code will not reject partially quoted strings, eg
2767 * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
2770 field_case = strdup(field_name);
2771 if (field_case == NULL)
2772 return -1; /* grotty */
2776 for (iptr = field_case; *iptr; iptr++)
2786 /* doubled quotes become a single quote */
2800 c = pg_tolower((unsigned char) c);
2806 for (i = 0; i < res->numAttributes; i++)
2808 if (strcmp(field_case, res->attDescs[i].name) == 0)
2819 PQftable(const PGresult *res, int field_num)
2821 if (!check_field_number(res, field_num))
2824 return res->attDescs[field_num].tableid;
2830 PQftablecol(const PGresult *res, int field_num)
2832 if (!check_field_number(res, field_num))
2835 return res->attDescs[field_num].columnid;
2841 PQfformat(const PGresult *res, int field_num)
2843 if (!check_field_number(res, field_num))
2846 return res->attDescs[field_num].format;
2852 PQftype(const PGresult *res, int field_num)
2854 if (!check_field_number(res, field_num))
2857 return res->attDescs[field_num].typid;
2863 PQfsize(const PGresult *res, int field_num)
2865 if (!check_field_number(res, field_num))
2868 return res->attDescs[field_num].typlen;
2874 PQfmod(const PGresult *res, int field_num)
2876 if (!check_field_number(res, field_num))
2879 return res->attDescs[field_num].atttypmod;
2885 PQcmdStatus(PGresult *res)
2889 return res->cmdStatus;
2894 * if the last command was an INSERT, return the oid string
2898 PQoidStatus(const PGresult *res)
2901 * This must be enough to hold the result. Don't laugh, this is better
2902 * than what this function used to do.
2904 static char buf[24];
2908 if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2911 len = strspn(res->cmdStatus + 7, "0123456789");
2912 if (len > sizeof(buf) - 1)
2913 len = sizeof(buf) - 1;
2914 memcpy(buf, res->cmdStatus + 7, len);
2922 * a perhaps preferable form of the above which just returns
2926 PQoidValue(const PGresult *res)
2928 char *endptr = NULL;
2929 unsigned long result;
2932 strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
2933 res->cmdStatus[7] < '0' ||
2934 res->cmdStatus[7] > '9')
2937 result = strtoul(res->cmdStatus + 7, &endptr, 10);
2939 if (!endptr || (*endptr != ' ' && *endptr != '\0'))
2942 return (Oid) result;
2948 * If the last command was INSERT/UPDATE/DELETE/MOVE/FETCH/COPY, return
2949 * a string containing the number of inserted/affected tuples. If not,
2952 * XXX: this should probably return an int
2955 PQcmdTuples(PGresult *res)
2963 if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
2965 p = res->cmdStatus + 7;
2966 /* INSERT: skip oid and space */
2967 while (*p && *p != ' ')
2970 goto interpret_error; /* no space? */
2973 else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
2974 strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
2975 strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
2976 p = res->cmdStatus + 7;
2977 else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
2978 p = res->cmdStatus + 6;
2979 else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
2980 strncmp(res->cmdStatus, "COPY ", 5) == 0)
2981 p = res->cmdStatus + 5;
2985 /* check that we have an integer (at least one digit, nothing else) */
2986 for (c = p; *c; c++)
2988 if (!isdigit((unsigned char) *c))
2989 goto interpret_error;
2992 goto interpret_error;
2997 pqInternalNotice(&res->noticeHooks,
2998 "could not interpret result from server: %s",
3005 * return the value of field 'field_num' of row 'tup_num'
3008 PQgetvalue(const PGresult *res, int tup_num, int field_num)
3010 if (!check_tuple_field_number(res, tup_num, field_num))
3012 return res->tuples[tup_num][field_num].value;
3016 * returns the actual length of a field value in bytes.
3019 PQgetlength(const PGresult *res, int tup_num, int field_num)
3021 if (!check_tuple_field_number(res, tup_num, field_num))
3023 if (res->tuples[tup_num][field_num].len != NULL_LEN)
3024 return res->tuples[tup_num][field_num].len;
3030 * returns the null status of a field value.
3033 PQgetisnull(const PGresult *res, int tup_num, int field_num)
3035 if (!check_tuple_field_number(res, tup_num, field_num))
3036 return 1; /* pretend it is null */
3037 if (res->tuples[tup_num][field_num].len == NULL_LEN)
3044 * returns the number of input parameters of a prepared statement.
3047 PQnparams(const PGresult *res)
3051 return res->numParameters;
3055 * returns type Oid of the specified statement parameter.
3058 PQparamtype(const PGresult *res, int param_num)
3060 if (!check_param_number(res, param_num))
3062 if (res->paramDescs)
3063 return res->paramDescs[param_num].typid;
3069 /* PQsetnonblocking:
3070 * sets the PGconn's database connection non-blocking if the arg is TRUE
3071 * or makes it blocking if the arg is FALSE, this will not protect
3072 * you from PQexec(), you'll only be safe when using the non-blocking API.
3073 * Needs to be called only on a connected database connection.
3076 PQsetnonblocking(PGconn *conn, int arg)
3080 if (!conn || conn->status == CONNECTION_BAD)
3083 barg = (arg ? TRUE : FALSE);
3085 /* early out if the socket is already in the state requested */
3086 if (barg == conn->nonblocking)
3090 * to guarantee constancy for flushing/query/result-polling behavior we
3091 * need to flush the send queue at this point in order to guarantee proper
3092 * behavior. this is ok because either they are making a transition _from_
3093 * or _to_ blocking mode, either way we can block them.
3095 /* if we are going from blocking to non-blocking flush here */
3099 conn->nonblocking = barg;
3105 * return the blocking status of the database connection
3106 * TRUE == nonblocking, FALSE == blocking
3109 PQisnonblocking(const PGconn *conn)
3111 return pqIsnonblocking(conn);
3114 /* libpq is thread-safe? */
3116 PQisthreadsafe(void)
3118 #ifdef ENABLE_THREAD_SAFETY
3126 /* try to force data out, really only useful for non-blocking users */
3128 PQflush(PGconn *conn)
3130 return pqFlush(conn);
3135 * PQfreemem - safely frees memory allocated
3137 * Needed mostly by Win32, unless multithreaded DLL (/MD in VC6)
3138 * Used for freeing memory from PQescapeByte()a/PQunescapeBytea()
3141 PQfreemem(void *ptr)
3147 * PQfreeNotify - free's the memory associated with a PGnotify
3149 * This function is here only for binary backward compatibility.
3150 * New code should use PQfreemem(). A macro will automatically map
3151 * calls to PQfreemem. It should be removed in the future. bjm 2003-03-24
3155 void PQfreeNotify(PGnotify *notify);
3158 PQfreeNotify(PGnotify *notify)
3165 * Escaping arbitrary strings to get valid SQL literal strings.
3167 * Replaces "'" with "''", and if not std_strings, replaces "\" with "\\".
3169 * length is the length of the source string. (Note: if a terminating NUL
3170 * is encountered sooner, PQescapeString stops short of "length"; the behavior
3171 * is thus rather like strncpy.)
3173 * For safety the buffer at "to" must be at least 2*length + 1 bytes long.
3174 * A terminating NUL character is added to the output string, whether the
3175 * input is NUL-terminated or not.
3177 * Returns the actual length of the output (not counting the terminating NUL).
3180 PQescapeStringInternal(PGconn *conn,
3181 char *to, const char *from, size_t length,
3183 int encoding, bool std_strings)
3185 const char *source = from;
3187 size_t remaining = length;
3192 while (remaining > 0 && *source != '\0')
3198 /* Fast path for plain ASCII */
3199 if (!IS_HIGHBIT_SET(c))
3201 /* Apply quoting if needed */
3202 if (SQL_STR_DOUBLE(c, !std_strings))
3204 /* Copy the character */
3211 /* Slow path for possible multibyte characters */
3212 len = pg_encoding_mblen(encoding, source);
3214 /* Copy the character */
3215 for (i = 0; i < len; i++)
3217 if (remaining == 0 || *source == '\0')
3219 *target++ = *source++;
3224 * If we hit premature end of string (ie, incomplete multibyte
3225 * character), try to pad out to the correct length with spaces. We
3226 * may not be able to pad completely, but we will always be able to
3227 * insert at least one pad space (since we'd not have quoted a
3228 * multibyte character). This should be enough to make a string that
3229 * the server will error out on.
3236 printfPQExpBuffer(&conn->errorMessage,
3237 libpq_gettext("incomplete multibyte character\n"));
3238 for (; i < len; i++)
3240 if (((size_t) (target - to)) / 2 >= length)
3248 /* Write the terminating NUL character. */
3255 PQescapeStringConn(PGconn *conn,
3256 char *to, const char *from, size_t length,
3261 /* force empty-string result */
3267 return PQescapeStringInternal(conn, to, from, length, error,
3268 conn->client_encoding,
3273 PQescapeString(char *to, const char *from, size_t length)
3275 return PQescapeStringInternal(NULL, to, from, length, NULL,
3276 static_client_encoding,
3277 static_std_strings);
3282 * Escape arbitrary strings. If as_ident is true, we escape the result
3283 * as an identifier; if false, as a literal. The result is returned in
3284 * a newly allocated buffer. If we fail due to an encoding violation or out
3285 * of memory condition, we return NULL, storing an error message into conn.
3288 PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
3293 int num_quotes = 0; /* single or double, depending on as_ident */
3294 int num_backslashes = 0;
3297 char quote_char = as_ident ? '"' : '\'';
3299 /* We must have a connection, else fail immediately. */
3303 /* Scan the string for characters that must be escaped. */
3304 for (s = str; (s - str) < len && *s != '\0'; ++s)
3306 if (*s == quote_char)
3308 else if (*s == '\\')
3310 else if (IS_HIGHBIT_SET(*s))
3314 /* Slow path for possible multibyte characters */
3315 charlen = pg_encoding_mblen(conn->client_encoding, s);
3317 /* Multibyte character overruns allowable length. */
3318 if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
3320 printfPQExpBuffer(&conn->errorMessage,
3321 libpq_gettext("incomplete multibyte character\n"));
3325 /* Adjust s, bearing in mind that for loop will increment it. */
3330 /* Allocate output buffer. */
3331 input_len = s - str;
3332 result_size = input_len + num_quotes + 3; /* two quotes, plus a NUL */
3333 if (!as_ident && num_backslashes > 0)
3334 result_size += num_backslashes + 2;
3335 result = rp = (char *) malloc(result_size);
3338 printfPQExpBuffer(&conn->errorMessage,
3339 libpq_gettext("out of memory\n"));
3344 * If we are escaping a literal that contains backslashes, we use the
3345 * escape string syntax so that the result is correct under either value
3346 * of standard_conforming_strings. We also emit a leading space in this
3347 * case, to guard against the possibility that the result might be
3348 * interpolated immediately following an identifier.
3350 if (!as_ident && num_backslashes > 0)
3356 /* Opening quote. */
3360 * Use fast path if possible.
3362 * We've already verified that the input string is well-formed in the
3363 * current encoding. If it contains no quotes and, in the case of
3364 * literal-escaping, no backslashes, then we can just copy it directly to
3365 * the output buffer, adding the necessary quotes.
3367 * If not, we must rescan the input and process each character
3370 if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
3372 memcpy(rp, str, input_len);
3377 for (s = str; s - str < input_len; ++s)
3379 if (*s == quote_char || (!as_ident && *s == '\\'))
3384 else if (!IS_HIGHBIT_SET(*s))
3388 int i = pg_encoding_mblen(conn->client_encoding, s);
3395 ++s; /* for loop will provide the final increment */
3401 /* Closing quote and terminating NUL. */
3409 PQescapeLiteral(PGconn *conn, const char *str, size_t len)
3411 return PQescapeInternal(conn, str, len, false);
3415 PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
3417 return PQescapeInternal(conn, str, len, true);
3420 /* HEX encoding support for bytea */
3421 static const char hextbl[] = "0123456789abcdef";
3423 static const int8 hexlookup[128] = {
3424 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
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 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
3428 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3429 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3430 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3431 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3439 if (c > 0 && c < 127)
3440 res = hexlookup[(unsigned char) c];
3447 * PQescapeBytea - converts from binary string to the
3448 * minimal encoding necessary to include the string in an SQL
3449 * INSERT statement with a bytea type column as the target.
3451 * We can use either hex or escape (traditional) encoding.
3452 * In escape mode, the following transformations are applied:
3453 * '\0' == ASCII 0 == \000
3454 * '\'' == ASCII 39 == ''
3455 * '\\' == ASCII 92 == \\
3456 * anything < 0x20, or > 0x7e ---> \ooo
3457 * (where ooo is an octal expression)
3459 * If not std_strings, all backslashes sent to the output are doubled.
3461 static unsigned char *
3462 PQescapeByteaInternal(PGconn *conn,
3463 const unsigned char *from, size_t from_length,
3464 size_t *to_length, bool std_strings, bool use_hex)
3466 const unsigned char *vp;
3468 unsigned char *result;
3471 size_t bslash_len = (std_strings ? 1 : 2);
3474 * empty string has 1 char ('\0')
3480 len += bslash_len + 1 + 2 * from_length;
3485 for (i = from_length; i > 0; i--, vp++)
3487 if (*vp < 0x20 || *vp > 0x7e)
3488 len += bslash_len + 3;
3489 else if (*vp == '\'')
3491 else if (*vp == '\\')
3492 len += bslash_len + bslash_len;
3499 rp = result = (unsigned char *) malloc(len);
3503 printfPQExpBuffer(&conn->errorMessage,
3504 libpq_gettext("out of memory\n"));
3517 for (i = from_length; i > 0; i--, vp++)
3519 unsigned char c = *vp;
3523 *rp++ = hextbl[(c >> 4) & 0xF];
3524 *rp++ = hextbl[c & 0xF];
3526 else if (c < 0x20 || c > 0x7e)
3531 *rp++ = (c >> 6) + '0';
3532 *rp++ = ((c >> 3) & 07) + '0';
3533 *rp++ = (c & 07) + '0';
3559 PQescapeByteaConn(PGconn *conn,
3560 const unsigned char *from, size_t from_length,
3565 return PQescapeByteaInternal(conn, from, from_length, to_length,
3567 (conn->sversion >= 90000));
3571 PQescapeBytea(const unsigned char *from, size_t from_length, size_t *to_length)
3573 return PQescapeByteaInternal(NULL, from, from_length, to_length,
3575 false /* can't use hex */ );
3579 #define ISFIRSTOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '3')
3580 #define ISOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '7')
3581 #define OCTVAL(CH) ((CH) - '0')
3584 * PQunescapeBytea - converts the null terminated string representation
3585 * of a bytea, strtext, into binary, filling a buffer. It returns a
3586 * pointer to the buffer (or NULL on error), and the size of the
3587 * buffer in retbuflen. The pointer may subsequently be used as an
3588 * argument to the function PQfreemem.
3590 * The following transformations are made:
3591 * \\ == ASCII 92 == \
3592 * \ooo == a byte whose value = ooo (ooo is an octal number)
3593 * \x == x (x is any character not matched by the above transformations)
3596 PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
3600 unsigned char *buffer,
3605 if (strtext == NULL)
3608 strtextlen = strlen((const char *) strtext);
3610 if (strtext[0] == '\\' && strtext[1] == 'x')
3612 const unsigned char *s;
3615 buflen = (strtextlen - 2) / 2;
3616 /* Avoid unportable malloc(0) */
3617 buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
3629 * Bad input is silently ignored. Note that this includes
3630 * whitespace between hex pairs, which is allowed by byteain.
3633 if (!*s || v1 == (char) -1)
3636 if (v2 != (char) -1)
3637 *p++ = (v1 << 4) | v2;
3640 buflen = p - buffer;
3645 * Length of input is max length of output, but add one to avoid
3646 * unportable malloc(0) if input is zero-length.
3648 buffer = (unsigned char *) malloc(strtextlen + 1);
3652 for (i = j = 0; i < strtextlen;)
3658 if (strtext[i] == '\\')
3659 buffer[j++] = strtext[i++];
3662 if ((ISFIRSTOCTDIGIT(strtext[i])) &&
3663 (ISOCTDIGIT(strtext[i + 1])) &&
3664 (ISOCTDIGIT(strtext[i + 2])))
3668 byte = OCTVAL(strtext[i++]);
3669 byte = (byte << 3) + OCTVAL(strtext[i++]);
3670 byte = (byte << 3) + OCTVAL(strtext[i++]);
3676 * Note: if we see '\' followed by something that isn't a
3677 * recognized escape sequence, we loop around having done
3678 * nothing except advance i. Therefore the something will
3679 * be emitted as ordinary data on the next cycle. Corner
3680 * case: '\' at end of string will just be discarded.
3685 buffer[j++] = strtext[i++];
3689 buflen = j; /* buflen is the length of the dequoted data */
3692 /* Shrink the buffer to be no larger than necessary */
3693 /* +1 avoids unportable behavior when buflen==0 */
3694 tmpbuf = realloc(buffer, buflen + 1);
3696 /* It would only be a very brain-dead realloc that could fail, but... */
3703 *retbuflen = buflen;