1 /*-------------------------------------------------------------------------
4 * functions related to sending a query down to the backend
6 * Portions Copyright (c) 1996-2010, 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",
45 * static state needed by PQescapeString and PQescapeBytea; initialize to
46 * values that result in backward-compatible behavior
48 static int static_client_encoding = PG_SQL_ASCII;
49 static bool static_std_strings = false;
52 static PGEvent *dupEvents(PGEvent *events, int count);
53 static bool PQsendQueryStart(PGconn *conn);
54 static int PQsendQueryGuts(PGconn *conn,
58 const Oid *paramTypes,
59 const char *const * paramValues,
60 const int *paramLengths,
61 const int *paramFormats,
63 static void parseInput(PGconn *conn);
64 static bool PQexecStart(PGconn *conn);
65 static PGresult *PQexecFinish(PGconn *conn);
66 static int PQsendDescribe(PGconn *conn, char desc_type,
67 const char *desc_target);
68 static int check_field_number(const PGresult *res, int field_num);
72 * Space management for PGresult.
74 * Formerly, libpq did a separate malloc() for each field of each tuple
75 * returned by a query. This was remarkably expensive --- malloc/free
76 * consumed a sizable part of the application's runtime. And there is
77 * no real need to keep track of the fields separately, since they will
78 * all be freed together when the PGresult is released. So now, we grab
79 * large blocks of storage from malloc and allocate space for query data
80 * within these blocks, using a trivially simple allocator. This reduces
81 * the number of malloc/free calls dramatically, and it also avoids
82 * fragmentation of the malloc storage arena.
83 * The PGresult structure itself is still malloc'd separately. We could
84 * combine it with the first allocation block, but that would waste space
85 * for the common case that no extra storage is actually needed (that is,
86 * the SQL command did not return tuples).
88 * We also malloc the top-level array of tuple pointers separately, because
89 * we need to be able to enlarge it via realloc, and our trivial space
90 * allocator doesn't handle that effectively. (Too bad the FE/BE protocol
91 * doesn't tell us up front how many tuples will be returned.)
92 * All other subsidiary storage for a PGresult is kept in PGresult_data blocks
93 * of size PGRESULT_DATA_BLOCKSIZE. The overhead at the start of each block
94 * is just a link to the next one, if any. Free-space management info is
95 * kept in the owning PGresult.
96 * A query returning a small amount of data will thus require three malloc
97 * calls: one for the PGresult, one for the tuples pointer array, and one
98 * PGresult_data block.
100 * Only the most recently allocated PGresult_data block is a candidate to
101 * have more stuff added to it --- any extra space left over in older blocks
102 * is wasted. We could be smarter and search the whole chain, but the point
103 * here is to be simple and fast. Typical applications do not keep a PGresult
104 * around very long anyway, so some wasted space within one is not a problem.
106 * Tuning constants for the space allocator are:
107 * PGRESULT_DATA_BLOCKSIZE: size of a standard allocation block, in bytes
108 * PGRESULT_ALIGN_BOUNDARY: assumed alignment requirement for binary data
109 * PGRESULT_SEP_ALLOC_THRESHOLD: objects bigger than this are given separate
110 * blocks, instead of being crammed into a regular allocation block.
111 * Requirements for correct function are:
112 * PGRESULT_ALIGN_BOUNDARY must be a multiple of the alignment requirements
113 * of all machine data types. (Currently this is set from configure
114 * tests, so it should be OK automatically.)
115 * PGRESULT_SEP_ALLOC_THRESHOLD + PGRESULT_BLOCK_OVERHEAD <=
116 * PGRESULT_DATA_BLOCKSIZE
117 * pqResultAlloc assumes an object smaller than the threshold will fit
119 * The amount of space wasted at the end of a block could be as much as
120 * PGRESULT_SEP_ALLOC_THRESHOLD, so it doesn't pay to make that too large.
124 #define PGRESULT_DATA_BLOCKSIZE 2048
125 #define PGRESULT_ALIGN_BOUNDARY MAXIMUM_ALIGNOF /* from configure */
126 #define PGRESULT_BLOCK_OVERHEAD Max(sizeof(PGresult_data), PGRESULT_ALIGN_BOUNDARY)
127 #define PGRESULT_SEP_ALLOC_THRESHOLD (PGRESULT_DATA_BLOCKSIZE / 2)
131 * PQmakeEmptyPGresult
132 * returns a newly allocated, initialized PGresult with given status.
133 * If conn is not NULL and status indicates an error, the conn's
134 * errorMessage is copied. Also, any PGEvents are copied from the conn.
137 PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
141 result = (PGresult *) malloc(sizeof(PGresult));
146 result->numAttributes = 0;
147 result->attDescs = NULL;
148 result->tuples = NULL;
149 result->tupArrSize = 0;
150 result->numParameters = 0;
151 result->paramDescs = NULL;
152 result->resultStatus = status;
153 result->cmdStatus[0] = '\0';
155 result->events = NULL;
157 result->errMsg = NULL;
158 result->errFields = NULL;
159 result->null_field[0] = '\0';
160 result->curBlock = NULL;
161 result->curOffset = 0;
162 result->spaceLeft = 0;
166 /* copy connection data we might need for operations on PGresult */
167 result->noticeHooks = conn->noticeHooks;
168 result->client_encoding = conn->client_encoding;
170 /* consider copying conn's errorMessage */
173 case PGRES_EMPTY_QUERY:
174 case PGRES_COMMAND_OK:
175 case PGRES_TUPLES_OK:
178 case PGRES_COPY_BOTH:
179 /* non-error cases */
182 pqSetResultError(result, conn->errorMessage.data);
186 /* copy events last; result must be valid if we need to PQclear */
187 if (conn->nEvents > 0)
189 result->events = dupEvents(conn->events, conn->nEvents);
195 result->nEvents = conn->nEvents;
201 result->noticeHooks.noticeRec = NULL;
202 result->noticeHooks.noticeRecArg = NULL;
203 result->noticeHooks.noticeProc = NULL;
204 result->noticeHooks.noticeProcArg = NULL;
205 result->client_encoding = PG_SQL_ASCII;
214 * Set the attributes for a given result. This function fails if there are
215 * already attributes contained in the provided result. The call is
216 * ignored if numAttributes is is zero or attDescs is NULL. If the
217 * function fails, it returns zero. If the function succeeds, it
218 * returns a non-zero value.
221 PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs)
225 /* If attrs already exist, they cannot be overwritten. */
226 if (!res || res->numAttributes > 0)
229 /* ignore no-op request */
230 if (numAttributes <= 0 || !attDescs)
233 res->attDescs = (PGresAttDesc *)
234 PQresultAlloc(res, numAttributes * sizeof(PGresAttDesc));
239 res->numAttributes = numAttributes;
240 memcpy(res->attDescs, attDescs, numAttributes * sizeof(PGresAttDesc));
242 /* deep-copy the attribute names, and determine format */
244 for (i = 0; i < res->numAttributes; i++)
246 if (res->attDescs[i].name)
247 res->attDescs[i].name = pqResultStrdup(res, res->attDescs[i].name);
249 res->attDescs[i].name = res->null_field;
251 if (!res->attDescs[i].name)
254 if (res->attDescs[i].format == 0)
264 * Returns a deep copy of the provided 'src' PGresult, which cannot be NULL.
265 * The 'flags' argument controls which portions of the result will or will
266 * NOT be copied. The created result is always put into the
267 * PGRES_TUPLES_OK status. The source result error message is not copied,
268 * although cmdStatus is.
270 * To set custom attributes, use PQsetResultAttrs. That function requires
271 * that there are no attrs contained in the result, so to use that
272 * function you cannot use the PG_COPYRES_ATTRS or PG_COPYRES_TUPLES
273 * options with this function.
276 * PG_COPYRES_ATTRS - Copy the source result's attributes
278 * PG_COPYRES_TUPLES - Copy the source result's tuples. This implies
279 * copying the attrs, seeeing how the attrs are needed by the tuples.
281 * PG_COPYRES_EVENTS - Copy the source result's events.
283 * PG_COPYRES_NOTICEHOOKS - Copy the source result's notice hooks.
286 PQcopyResult(const PGresult *src, int flags)
294 dest = PQmakeEmptyPGresult(NULL, PGRES_TUPLES_OK);
298 /* Always copy these over. Is cmdStatus really useful here? */
299 dest->client_encoding = src->client_encoding;
300 strcpy(dest->cmdStatus, src->cmdStatus);
303 if (flags & (PG_COPYRES_ATTRS | PG_COPYRES_TUPLES))
305 if (!PQsetResultAttrs(dest, src->numAttributes, src->attDescs))
312 /* Wants to copy tuples? */
313 if (flags & PG_COPYRES_TUPLES)
318 for (tup = 0; tup < src->ntups; tup++)
320 for (field = 0; field < src->numAttributes; field++)
322 if (!PQsetvalue(dest, tup, field,
323 src->tuples[tup][field].value,
324 src->tuples[tup][field].len))
333 /* Wants to copy notice hooks? */
334 if (flags & PG_COPYRES_NOTICEHOOKS)
335 dest->noticeHooks = src->noticeHooks;
337 /* Wants to copy PGEvents? */
338 if ((flags & PG_COPYRES_EVENTS) && src->nEvents > 0)
340 dest->events = dupEvents(src->events, src->nEvents);
346 dest->nEvents = src->nEvents;
349 /* Okay, trigger PGEVT_RESULTCOPY event */
350 for (i = 0; i < dest->nEvents; i++)
352 if (src->events[i].resultInitialized)
354 PGEventResultCopy evt;
358 if (!dest->events[i].proc(PGEVT_RESULTCOPY, &evt,
359 dest->events[i].passThrough))
364 dest->events[i].resultInitialized = TRUE;
372 * Copy an array of PGEvents (with no extra space for more).
373 * Does not duplicate the event instance data, sets this to NULL.
374 * Also, the resultInitialized flags are all cleared.
377 dupEvents(PGEvent *events, int count)
382 if (!events || count <= 0)
385 newEvents = (PGEvent *) malloc(count * sizeof(PGEvent));
389 for (i = 0; i < count; i++)
391 newEvents[i].proc = events[i].proc;
392 newEvents[i].passThrough = events[i].passThrough;
393 newEvents[i].data = NULL;
394 newEvents[i].resultInitialized = FALSE;
395 newEvents[i].name = strdup(events[i].name);
396 if (!newEvents[i].name)
399 free(newEvents[i].name);
410 * Sets the value for a tuple field. The tup_num must be less than or
411 * equal to PQntuples(res). If it is equal, a new tuple is created and
412 * added to the result.
413 * Returns a non-zero value for success and zero for failure.
416 PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len)
418 PGresAttValue *attval;
420 if (!check_field_number(res, field_num))
423 /* Invalid tup_num, must be <= ntups */
424 if (tup_num < 0 || tup_num > res->ntups)
427 /* need to grow the tuple table? */
428 if (res->ntups >= res->tupArrSize)
430 int n = res->tupArrSize ? res->tupArrSize * 2 : 128;
431 PGresAttValue **tups;
434 tups = (PGresAttValue **) realloc(res->tuples, n * sizeof(PGresAttValue *));
436 tups = (PGresAttValue **) malloc(n * sizeof(PGresAttValue *));
441 memset(tups + res->tupArrSize, 0,
442 (n - res->tupArrSize) * sizeof(PGresAttValue *));
447 /* need to allocate a new tuple? */
448 if (tup_num == res->ntups && !res->tuples[tup_num])
453 tup = (PGresAttValue *)
454 pqResultAlloc(res, res->numAttributes * sizeof(PGresAttValue),
460 /* initialize each column to NULL */
461 for (i = 0; i < res->numAttributes; i++)
463 tup[i].len = NULL_LEN;
464 tup[i].value = res->null_field;
467 res->tuples[tup_num] = tup;
471 attval = &res->tuples[tup_num][field_num];
473 /* treat either NULL_LEN or NULL value pointer as a NULL field */
474 if (len == NULL_LEN || value == NULL)
476 attval->len = NULL_LEN;
477 attval->value = res->null_field;
482 attval->value = res->null_field;
486 attval->value = (char *) pqResultAlloc(res, len + 1, TRUE);
490 memcpy(attval->value, value, len);
491 attval->value[len] = '\0';
498 * pqResultAlloc - exported routine to allocate local storage in a PGresult.
500 * We force all such allocations to be maxaligned, since we don't know
501 * whether the value might be binary.
504 PQresultAlloc(PGresult *res, size_t nBytes)
506 return pqResultAlloc(res, nBytes, TRUE);
511 * Allocate subsidiary storage for a PGresult.
513 * nBytes is the amount of space needed for the object.
514 * If isBinary is true, we assume that we need to align the object on
515 * a machine allocation boundary.
516 * If isBinary is false, we assume the object is a char string and can
517 * be allocated on any byte boundary.
520 pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
523 PGresult_data *block;
529 return res->null_field;
532 * If alignment is needed, round up the current position to an alignment
537 int offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
541 res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
542 res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
546 /* If there's enough space in the current block, no problem. */
547 if (nBytes <= (size_t) res->spaceLeft)
549 space = res->curBlock->space + res->curOffset;
550 res->curOffset += nBytes;
551 res->spaceLeft -= nBytes;
556 * If the requested object is very large, give it its own block; this
557 * avoids wasting what might be most of the current block to start a new
558 * block. (We'd have to special-case requests bigger than the block size
559 * anyway.) The object is always given binary alignment in this case.
561 if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
563 block = (PGresult_data *) malloc(nBytes + PGRESULT_BLOCK_OVERHEAD);
566 space = block->space + PGRESULT_BLOCK_OVERHEAD;
570 * Tuck special block below the active block, so that we don't
571 * have to waste the free space in the active block.
573 block->next = res->curBlock->next;
574 res->curBlock->next = block;
578 /* Must set up the new block as the first active block. */
580 res->curBlock = block;
581 res->spaceLeft = 0; /* be sure it's marked full */
586 /* Otherwise, start a new block. */
587 block = (PGresult_data *) malloc(PGRESULT_DATA_BLOCKSIZE);
590 block->next = res->curBlock;
591 res->curBlock = block;
594 /* object needs full alignment */
595 res->curOffset = PGRESULT_BLOCK_OVERHEAD;
596 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - PGRESULT_BLOCK_OVERHEAD;
600 /* we can cram it right after the overhead pointer */
601 res->curOffset = sizeof(PGresult_data);
602 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - sizeof(PGresult_data);
605 space = block->space + res->curOffset;
606 res->curOffset += nBytes;
607 res->spaceLeft -= nBytes;
613 * Like strdup, but the space is subsidiary PGresult space.
616 pqResultStrdup(PGresult *res, const char *str)
618 char *space = (char *) pqResultAlloc(res, strlen(str) + 1, FALSE);
627 * assign a new error message to a PGresult
630 pqSetResultError(PGresult *res, const char *msg)
635 res->errMsg = pqResultStrdup(res, msg);
641 * pqCatenateResultError -
642 * concatenate a new error message to the one already in a PGresult
645 pqCatenateResultError(PGresult *res, const char *msg)
647 PQExpBufferData errorBuf;
651 initPQExpBuffer(&errorBuf);
653 appendPQExpBufferStr(&errorBuf, res->errMsg);
654 appendPQExpBufferStr(&errorBuf, msg);
655 pqSetResultError(res, errorBuf.data);
656 termPQExpBuffer(&errorBuf);
661 * free's the memory associated with a PGresult
664 PQclear(PGresult *res)
666 PGresult_data *block;
672 for (i = 0; i < res->nEvents; i++)
674 /* only send DESTROY to successfully-initialized event procs */
675 if (res->events[i].resultInitialized)
677 PGEventResultDestroy evt;
680 (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
681 res->events[i].passThrough);
683 free(res->events[i].name);
689 /* Free all the subsidiary blocks */
690 while ((block = res->curBlock) != NULL)
692 res->curBlock = block->next;
696 /* Free the top-level tuple pointer array */
700 /* zero out the pointer fields to catch programming errors */
701 res->attDescs = NULL;
703 res->paramDescs = NULL;
704 res->errFields = NULL;
707 /* res->curBlock was zeroed out earlier */
709 /* Free the PGresult structure itself */
714 * Handy subroutine to deallocate any partially constructed async result.
718 pqClearAsyncResult(PGconn *conn)
721 PQclear(conn->result);
723 conn->curTuple = NULL;
727 * This subroutine deletes any existing async result, sets conn->result
728 * to a PGresult with status PGRES_FATAL_ERROR, and stores the current
729 * contents of conn->errorMessage into that result. It differs from a
730 * plain call on PQmakeEmptyPGresult() in that if there is already an
731 * async result with status PGRES_FATAL_ERROR, the current error message
732 * is APPENDED to the old error message instead of replacing it. This
733 * behavior lets us report multiple error conditions properly, if necessary.
734 * (An example where this is needed is when the backend sends an 'E' message
735 * and immediately closes the connection --- we want to report both the
736 * backend error and the connection closure error.)
739 pqSaveErrorResult(PGconn *conn)
742 * If no old async result, just let PQmakeEmptyPGresult make one. Likewise
743 * if old result is not an error message.
745 if (conn->result == NULL ||
746 conn->result->resultStatus != PGRES_FATAL_ERROR ||
747 conn->result->errMsg == NULL)
749 pqClearAsyncResult(conn);
750 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
754 /* Else, concatenate error message to existing async result. */
755 pqCatenateResultError(conn->result, conn->errorMessage.data);
760 * This subroutine prepares an async result object for return to the caller.
761 * If there is not already an async result object, build an error object
762 * using whatever is in conn->errorMessage. In any case, clear the async
763 * result storage and make sure PQerrorMessage will agree with the result's
767 pqPrepareAsyncResult(PGconn *conn)
772 * conn->result is the PGresult to return. If it is NULL (which probably
773 * shouldn't happen) we assume there is an appropriate error message in
774 * conn->errorMessage.
777 conn->result = NULL; /* handing over ownership to caller */
778 conn->curTuple = NULL; /* just in case */
780 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
784 * Make sure PQerrorMessage agrees with result; it could be different
785 * if we have concatenated messages.
787 resetPQExpBuffer(&conn->errorMessage);
788 appendPQExpBufferStr(&conn->errorMessage,
789 PQresultErrorMessage(res));
795 * pqInternalNotice - produce an internally-generated notice message
797 * A format string and optional arguments can be passed. Note that we do
798 * libpq_gettext() here, so callers need not.
800 * The supplied text is taken as primary message (ie., it should not include
801 * a trailing newline, and should not be more than one line).
804 pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
810 if (hooks->noticeRec == NULL)
811 return; /* nobody home to receive notice? */
813 /* Format the message */
815 vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
817 msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
819 /* Make a PGresult to pass to the notice receiver */
820 res = PQmakeEmptyPGresult(NULL, PGRES_NONFATAL_ERROR);
823 res->noticeHooks = *hooks;
826 * Set up fields of notice.
828 pqSaveMessageField(res, PG_DIAG_MESSAGE_PRIMARY, msgBuf);
829 pqSaveMessageField(res, PG_DIAG_SEVERITY, libpq_gettext("NOTICE"));
830 /* XXX should provide a SQLSTATE too? */
833 * Result text is always just the primary message + newline. If we can't
834 * allocate it, don't bother invoking the receiver.
836 res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, FALSE);
839 sprintf(res->errMsg, "%s\n", msgBuf);
842 * Pass to receiver, then free it.
844 (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
851 * add a row pointer to the PGresult structure, growing it if necessary
852 * Returns TRUE if OK, FALSE if not enough memory to add the row
855 pqAddTuple(PGresult *res, PGresAttValue *tup)
857 if (res->ntups >= res->tupArrSize)
860 * Try to grow the array.
862 * We can use realloc because shallow copying of the structure is
863 * okay. Note that the first time through, res->tuples is NULL. While
864 * ANSI says that realloc() should act like malloc() in that case,
865 * some old C libraries (like SunOS 4.1.x) coredump instead. On
866 * failure realloc is supposed to return NULL without damaging the
867 * existing allocation. Note that the positions beyond res->ntups are
868 * garbage, not necessarily NULL.
870 int newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
871 PGresAttValue **newTuples;
873 if (res->tuples == NULL)
874 newTuples = (PGresAttValue **)
875 malloc(newSize * sizeof(PGresAttValue *));
877 newTuples = (PGresAttValue **)
878 realloc(res->tuples, newSize * sizeof(PGresAttValue *));
880 return FALSE; /* malloc or realloc failed */
881 res->tupArrSize = newSize;
882 res->tuples = newTuples;
884 res->tuples[res->ntups] = tup;
890 * pqSaveMessageField - save one field of an error or notice message
893 pqSaveMessageField(PGresult *res, char code, const char *value)
895 PGMessageField *pfield;
897 pfield = (PGMessageField *)
899 sizeof(PGMessageField) + strlen(value),
902 return; /* out of memory? */
904 strcpy(pfield->contents, value);
905 pfield->next = res->errFields;
906 res->errFields = pfield;
910 * pqSaveParameterStatus - remember parameter status sent by backend
913 pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
915 pgParameterStatus *pstatus;
916 pgParameterStatus *prev;
919 fprintf(conn->Pfdebug, "pqSaveParameterStatus: '%s' = '%s'\n",
923 * Forget any old information about the parameter
925 for (pstatus = conn->pstatus, prev = NULL;
927 prev = pstatus, pstatus = pstatus->next)
929 if (strcmp(pstatus->name, name) == 0)
932 prev->next = pstatus->next;
934 conn->pstatus = pstatus->next;
935 free(pstatus); /* frees name and value strings too */
941 * Store new info as a single malloc block
943 pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
944 strlen(name) +strlen(value) + 2);
949 ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
952 ptr += strlen(name) + 1;
953 pstatus->value = ptr;
955 pstatus->next = conn->pstatus;
956 conn->pstatus = pstatus;
960 * Special hacks: remember client_encoding and
961 * standard_conforming_strings, and convert server version to a numeric
962 * form. We keep the first two of these in static variables as well, so
963 * that PQescapeString and PQescapeBytea can behave somewhat sanely (at
964 * least in single-connection-using programs).
966 if (strcmp(name, "client_encoding") == 0)
968 conn->client_encoding = pg_char_to_encoding(value);
969 /* if we don't recognize the encoding name, fall back to SQL_ASCII */
970 if (conn->client_encoding < 0)
971 conn->client_encoding = PG_SQL_ASCII;
972 static_client_encoding = conn->client_encoding;
974 else if (strcmp(name, "standard_conforming_strings") == 0)
976 conn->std_strings = (strcmp(value, "on") == 0);
977 static_std_strings = conn->std_strings;
979 else if (strcmp(name, "server_version") == 0)
986 cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
989 conn->sversion = 0; /* unknown */
994 conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
1002 * Submit a query, but don't wait for it to finish
1004 * Returns: 1 if successfully submitted
1005 * 0 if error (conn->errorMessage is set)
1008 PQsendQuery(PGconn *conn, const char *query)
1010 if (!PQsendQueryStart(conn))
1015 printfPQExpBuffer(&conn->errorMessage,
1016 libpq_gettext("command string is a null pointer\n"));
1020 /* construct the outgoing Query message */
1021 if (pqPutMsgStart('Q', false, conn) < 0 ||
1022 pqPuts(query, conn) < 0 ||
1023 pqPutMsgEnd(conn) < 0)
1025 pqHandleSendFailure(conn);
1029 /* remember we are using simple query protocol */
1030 conn->queryclass = PGQUERY_SIMPLE;
1032 /* and remember the query text too, if possible */
1033 /* if insufficient memory, last_query just winds up NULL */
1034 if (conn->last_query)
1035 free(conn->last_query);
1036 conn->last_query = strdup(query);
1039 * Give the data a push. In nonblock mode, don't complain if we're unable
1040 * to send it all; PQgetResult() will do any additional flushing needed.
1042 if (pqFlush(conn) < 0)
1044 pqHandleSendFailure(conn);
1048 /* OK, it's launched! */
1049 conn->asyncStatus = PGASYNC_BUSY;
1055 * Like PQsendQuery, but use protocol 3.0 so we can pass parameters
1058 PQsendQueryParams(PGconn *conn,
1059 const char *command,
1061 const Oid *paramTypes,
1062 const char *const * paramValues,
1063 const int *paramLengths,
1064 const int *paramFormats,
1067 if (!PQsendQueryStart(conn))
1072 printfPQExpBuffer(&conn->errorMessage,
1073 libpq_gettext("command string is a null pointer\n"));
1077 return PQsendQueryGuts(conn,
1079 "", /* use unnamed statement */
1090 * Submit a Parse message, but don't wait for it to finish
1092 * Returns: 1 if successfully submitted
1093 * 0 if error (conn->errorMessage is set)
1096 PQsendPrepare(PGconn *conn,
1097 const char *stmtName, const char *query,
1098 int nParams, const Oid *paramTypes)
1100 if (!PQsendQueryStart(conn))
1105 printfPQExpBuffer(&conn->errorMessage,
1106 libpq_gettext("statement name is a null pointer\n"));
1112 printfPQExpBuffer(&conn->errorMessage,
1113 libpq_gettext("command string is a null pointer\n"));
1117 /* This isn't gonna work on a 2.0 server */
1118 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1120 printfPQExpBuffer(&conn->errorMessage,
1121 libpq_gettext("function requires at least protocol version 3.0\n"));
1125 /* construct the Parse message */
1126 if (pqPutMsgStart('P', false, conn) < 0 ||
1127 pqPuts(stmtName, conn) < 0 ||
1128 pqPuts(query, conn) < 0)
1131 if (nParams > 0 && paramTypes)
1135 if (pqPutInt(nParams, 2, conn) < 0)
1137 for (i = 0; i < nParams; i++)
1139 if (pqPutInt(paramTypes[i], 4, conn) < 0)
1145 if (pqPutInt(0, 2, conn) < 0)
1148 if (pqPutMsgEnd(conn) < 0)
1151 /* construct the Sync message */
1152 if (pqPutMsgStart('S', false, conn) < 0 ||
1153 pqPutMsgEnd(conn) < 0)
1156 /* remember we are doing just a Parse */
1157 conn->queryclass = PGQUERY_PREPARE;
1159 /* and remember the query text too, if possible */
1160 /* if insufficient memory, last_query just winds up NULL */
1161 if (conn->last_query)
1162 free(conn->last_query);
1163 conn->last_query = strdup(query);
1166 * Give the data a push. In nonblock mode, don't complain if we're unable
1167 * to send it all; PQgetResult() will do any additional flushing needed.
1169 if (pqFlush(conn) < 0)
1172 /* OK, it's launched! */
1173 conn->asyncStatus = PGASYNC_BUSY;
1177 pqHandleSendFailure(conn);
1182 * PQsendQueryPrepared
1183 * Like PQsendQuery, but execute a previously prepared statement,
1184 * using protocol 3.0 so we can pass parameters
1187 PQsendQueryPrepared(PGconn *conn,
1188 const char *stmtName,
1190 const char *const * paramValues,
1191 const int *paramLengths,
1192 const int *paramFormats,
1195 if (!PQsendQueryStart(conn))
1200 printfPQExpBuffer(&conn->errorMessage,
1201 libpq_gettext("statement name is a null pointer\n"));
1205 return PQsendQueryGuts(conn,
1206 NULL, /* no command to parse */
1209 NULL, /* no param types */
1217 * Common startup code for PQsendQuery and sibling routines
1220 PQsendQueryStart(PGconn *conn)
1225 /* clear the error string */
1226 resetPQExpBuffer(&conn->errorMessage);
1228 /* Don't try to send if we know there's no live connection. */
1229 if (conn->status != CONNECTION_OK)
1231 printfPQExpBuffer(&conn->errorMessage,
1232 libpq_gettext("no connection to the server\n"));
1235 /* Can't send while already busy, either. */
1236 if (conn->asyncStatus != PGASYNC_IDLE)
1238 printfPQExpBuffer(&conn->errorMessage,
1239 libpq_gettext("another command is already in progress\n"));
1243 /* initialize async result-accumulation state */
1244 conn->result = NULL;
1245 conn->curTuple = NULL;
1247 /* ready to send command message */
1253 * Common code for protocol-3.0 query sending
1254 * PQsendQueryStart should be done already
1256 * command may be NULL to indicate we use an already-prepared statement
1259 PQsendQueryGuts(PGconn *conn,
1260 const char *command,
1261 const char *stmtName,
1263 const Oid *paramTypes,
1264 const char *const * paramValues,
1265 const int *paramLengths,
1266 const int *paramFormats,
1271 /* This isn't gonna work on a 2.0 server */
1272 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1274 printfPQExpBuffer(&conn->errorMessage,
1275 libpq_gettext("function requires at least protocol version 3.0\n"));
1280 * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync,
1281 * using specified statement name and the unnamed portal.
1286 /* construct the Parse message */
1287 if (pqPutMsgStart('P', false, conn) < 0 ||
1288 pqPuts(stmtName, conn) < 0 ||
1289 pqPuts(command, conn) < 0)
1291 if (nParams > 0 && paramTypes)
1293 if (pqPutInt(nParams, 2, conn) < 0)
1295 for (i = 0; i < nParams; i++)
1297 if (pqPutInt(paramTypes[i], 4, conn) < 0)
1303 if (pqPutInt(0, 2, conn) < 0)
1306 if (pqPutMsgEnd(conn) < 0)
1310 /* Construct the Bind message */
1311 if (pqPutMsgStart('B', false, conn) < 0 ||
1312 pqPuts("", conn) < 0 ||
1313 pqPuts(stmtName, conn) < 0)
1316 /* Send parameter formats */
1317 if (nParams > 0 && paramFormats)
1319 if (pqPutInt(nParams, 2, conn) < 0)
1321 for (i = 0; i < nParams; i++)
1323 if (pqPutInt(paramFormats[i], 2, conn) < 0)
1329 if (pqPutInt(0, 2, conn) < 0)
1333 if (pqPutInt(nParams, 2, conn) < 0)
1336 /* Send parameters */
1337 for (i = 0; i < nParams; i++)
1339 if (paramValues && paramValues[i])
1343 if (paramFormats && paramFormats[i] != 0)
1345 /* binary parameter */
1347 nbytes = paramLengths[i];
1350 printfPQExpBuffer(&conn->errorMessage,
1351 libpq_gettext("length must be given for binary parameter\n"));
1357 /* text parameter, do not use paramLengths */
1358 nbytes = strlen(paramValues[i]);
1360 if (pqPutInt(nbytes, 4, conn) < 0 ||
1361 pqPutnchar(paramValues[i], nbytes, conn) < 0)
1366 /* take the param as NULL */
1367 if (pqPutInt(-1, 4, conn) < 0)
1371 if (pqPutInt(1, 2, conn) < 0 ||
1372 pqPutInt(resultFormat, 2, conn))
1374 if (pqPutMsgEnd(conn) < 0)
1377 /* construct the Describe Portal message */
1378 if (pqPutMsgStart('D', false, conn) < 0 ||
1379 pqPutc('P', conn) < 0 ||
1380 pqPuts("", conn) < 0 ||
1381 pqPutMsgEnd(conn) < 0)
1384 /* construct the Execute message */
1385 if (pqPutMsgStart('E', false, conn) < 0 ||
1386 pqPuts("", conn) < 0 ||
1387 pqPutInt(0, 4, conn) < 0 ||
1388 pqPutMsgEnd(conn) < 0)
1391 /* construct the Sync message */
1392 if (pqPutMsgStart('S', false, conn) < 0 ||
1393 pqPutMsgEnd(conn) < 0)
1396 /* remember we are using extended query protocol */
1397 conn->queryclass = PGQUERY_EXTENDED;
1399 /* and remember the query text too, if possible */
1400 /* if insufficient memory, last_query just winds up NULL */
1401 if (conn->last_query)
1402 free(conn->last_query);
1404 conn->last_query = strdup(command);
1406 conn->last_query = NULL;
1409 * Give the data a push. In nonblock mode, don't complain if we're unable
1410 * to send it all; PQgetResult() will do any additional flushing needed.
1412 if (pqFlush(conn) < 0)
1415 /* OK, it's launched! */
1416 conn->asyncStatus = PGASYNC_BUSY;
1420 pqHandleSendFailure(conn);
1425 * pqHandleSendFailure: try to clean up after failure to send command.
1427 * Primarily, what we want to accomplish here is to process an async
1428 * NOTICE message that the backend might have sent just before it died.
1430 * NOTE: this routine should only be called in PGASYNC_IDLE state.
1433 pqHandleSendFailure(PGconn *conn)
1436 * Accept any available input data, ignoring errors. Note that if
1437 * pqReadData decides the backend has closed the channel, it will close
1438 * our side of the socket --- that's just what we want here.
1440 while (pqReadData(conn) > 0)
1441 /* loop until no more data readable */ ;
1444 * Parse any available input messages. Since we are in PGASYNC_IDLE
1445 * state, only NOTICE and NOTIFY messages will be eaten.
1451 * Consume any available input from the backend
1452 * 0 return: some kind of trouble
1453 * 1 return: no problem
1456 PQconsumeInput(PGconn *conn)
1462 * for non-blocking connections try to flush the send-queue, otherwise we
1463 * may never get a response for something that may not have already been
1464 * sent because it's in our write buffer!
1466 if (pqIsnonblocking(conn))
1468 if (pqFlush(conn) < 0)
1473 * Load more data, if available. We do this no matter what state we are
1474 * in, since we are probably getting called because the application wants
1475 * to get rid of a read-select condition. Note that we will NOT block
1476 * waiting for more input.
1478 if (pqReadData(conn) < 0)
1481 /* Parsing of the data waits till later. */
1487 * parseInput: if appropriate, parse input data from backend
1488 * until input is exhausted or a stopping state is reached.
1489 * Note that this function will NOT attempt to read more data from the backend.
1492 parseInput(PGconn *conn)
1494 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1495 pqParseInput3(conn);
1497 pqParseInput2(conn);
1502 * Return TRUE if PQgetResult would block waiting for input.
1506 PQisBusy(PGconn *conn)
1511 /* Parse any available data, if our state permits. */
1514 /* PQgetResult will return immediately in all states except BUSY. */
1515 return conn->asyncStatus == PGASYNC_BUSY;
1521 * Get the next PGresult produced by a query. Returns NULL if no
1522 * query work remains or an error has occurred (e.g. out of
1527 PQgetResult(PGconn *conn)
1534 /* Parse any available data, if our state permits. */
1537 /* If not ready to return something, block until we are. */
1538 while (conn->asyncStatus == PGASYNC_BUSY)
1543 * If data remains unsent, send it. Else we might be waiting for the
1544 * result of a command the backend hasn't even got yet.
1546 while ((flushResult = pqFlush(conn)) > 0)
1548 if (pqWait(FALSE, TRUE, conn))
1555 /* Wait for some more data, and load it. */
1557 pqWait(TRUE, FALSE, conn) ||
1558 pqReadData(conn) < 0)
1561 * conn->errorMessage has been set by pqWait or pqReadData. We
1562 * want to append it to any already-received error message.
1564 pqSaveErrorResult(conn);
1565 conn->asyncStatus = PGASYNC_IDLE;
1566 return pqPrepareAsyncResult(conn);
1573 /* Return the appropriate thing. */
1574 switch (conn->asyncStatus)
1577 res = NULL; /* query is complete */
1580 res = pqPrepareAsyncResult(conn);
1581 /* Set the state back to BUSY, allowing parsing to proceed. */
1582 conn->asyncStatus = PGASYNC_BUSY;
1584 case PGASYNC_COPY_IN:
1585 if (conn->result && conn->result->resultStatus == PGRES_COPY_IN)
1586 res = pqPrepareAsyncResult(conn);
1588 res = PQmakeEmptyPGresult(conn, PGRES_COPY_IN);
1590 case PGASYNC_COPY_OUT:
1591 if (conn->result && conn->result->resultStatus == PGRES_COPY_OUT)
1592 res = pqPrepareAsyncResult(conn);
1594 res = PQmakeEmptyPGresult(conn, PGRES_COPY_OUT);
1596 case PGASYNC_COPY_BOTH:
1597 if (conn->result && conn->result->resultStatus == PGRES_COPY_BOTH)
1598 res = pqPrepareAsyncResult(conn);
1600 res = PQmakeEmptyPGresult(conn, PGRES_COPY_BOTH);
1603 printfPQExpBuffer(&conn->errorMessage,
1604 libpq_gettext("unexpected asyncStatus: %d\n"),
1605 (int) conn->asyncStatus);
1606 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1614 for (i = 0; i < res->nEvents; i++)
1616 PGEventResultCreate evt;
1620 if (!res->events[i].proc(PGEVT_RESULTCREATE, &evt,
1621 res->events[i].passThrough))
1623 printfPQExpBuffer(&conn->errorMessage,
1624 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_RESULTCREATE event\n"),
1625 res->events[i].name);
1626 pqSetResultError(res, conn->errorMessage.data);
1627 res->resultStatus = PGRES_FATAL_ERROR;
1630 res->events[i].resultInitialized = TRUE;
1640 * send a query to the backend and package up the result in a PGresult
1642 * If the query was not even sent, return NULL; conn->errorMessage is set to
1643 * a relevant message.
1644 * If the query was sent, a new PGresult is returned (which could indicate
1645 * either success or failure).
1646 * The user is responsible for freeing the PGresult via PQclear()
1647 * when done with it.
1650 PQexec(PGconn *conn, const char *query)
1652 if (!PQexecStart(conn))
1654 if (!PQsendQuery(conn, query))
1656 return PQexecFinish(conn);
1661 * Like PQexec, but use protocol 3.0 so we can pass parameters
1664 PQexecParams(PGconn *conn,
1665 const char *command,
1667 const Oid *paramTypes,
1668 const char *const * paramValues,
1669 const int *paramLengths,
1670 const int *paramFormats,
1673 if (!PQexecStart(conn))
1675 if (!PQsendQueryParams(conn, command,
1676 nParams, paramTypes, paramValues, paramLengths,
1677 paramFormats, resultFormat))
1679 return PQexecFinish(conn);
1684 * Creates a prepared statement by issuing a v3.0 parse message.
1686 * If the query was not even sent, return NULL; conn->errorMessage is set to
1687 * a relevant message.
1688 * If the query was sent, a new PGresult is returned (which could indicate
1689 * either success or failure).
1690 * The user is responsible for freeing the PGresult via PQclear()
1691 * when done with it.
1694 PQprepare(PGconn *conn,
1695 const char *stmtName, const char *query,
1696 int nParams, const Oid *paramTypes)
1698 if (!PQexecStart(conn))
1700 if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
1702 return PQexecFinish(conn);
1707 * Like PQexec, but execute a previously prepared statement,
1708 * using protocol 3.0 so we can pass parameters
1711 PQexecPrepared(PGconn *conn,
1712 const char *stmtName,
1714 const char *const * paramValues,
1715 const int *paramLengths,
1716 const int *paramFormats,
1719 if (!PQexecStart(conn))
1721 if (!PQsendQueryPrepared(conn, stmtName,
1722 nParams, paramValues, paramLengths,
1723 paramFormats, resultFormat))
1725 return PQexecFinish(conn);
1729 * Common code for PQexec and sibling routines: prepare to send command
1732 PQexecStart(PGconn *conn)
1740 * Silently discard any prior query result that application didn't eat.
1741 * This is probably poor design, but it's here for backward compatibility.
1743 while ((result = PQgetResult(conn)) != NULL)
1745 ExecStatusType resultStatus = result->resultStatus;
1747 PQclear(result); /* only need its status */
1748 if (resultStatus == PGRES_COPY_IN)
1750 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1752 /* In protocol 3, we can get out of a COPY IN state */
1753 if (PQputCopyEnd(conn,
1754 libpq_gettext("COPY terminated by new PQexec")) < 0)
1756 /* keep waiting to swallow the copy's failure message */
1760 /* In older protocols we have to punt */
1761 printfPQExpBuffer(&conn->errorMessage,
1762 libpq_gettext("COPY IN state must be terminated first\n"));
1766 else if (resultStatus == PGRES_COPY_OUT)
1768 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1771 * In protocol 3, we can get out of a COPY OUT state: we just
1772 * switch back to BUSY and allow the remaining COPY data to be
1773 * dropped on the floor.
1775 conn->asyncStatus = PGASYNC_BUSY;
1776 /* keep waiting to swallow the copy's completion message */
1780 /* In older protocols we have to punt */
1781 printfPQExpBuffer(&conn->errorMessage,
1782 libpq_gettext("COPY OUT state must be terminated first\n"));
1786 else if (resultStatus == PGRES_COPY_BOTH)
1788 /* We don't allow PQexec during COPY BOTH */
1789 printfPQExpBuffer(&conn->errorMessage,
1790 libpq_gettext("PQexec not allowed during COPY BOTH\n"));
1793 /* check for loss of connection, too */
1794 if (conn->status == CONNECTION_BAD)
1798 /* OK to send a command */
1803 * Common code for PQexec and sibling routines: wait for command result
1806 PQexecFinish(PGconn *conn)
1809 PGresult *lastResult;
1812 * For backwards compatibility, return the last result if there are more
1813 * than one --- but merge error messages if we get more than one error
1816 * We have to stop if we see copy in/out/both, however. We will resume parsing
1817 * after application performs the data transfer.
1819 * Also stop if the connection is lost (else we'll loop infinitely).
1822 while ((result = PQgetResult(conn)) != NULL)
1826 if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
1827 result->resultStatus == PGRES_FATAL_ERROR)
1829 pqCatenateResultError(lastResult, result->errMsg);
1831 result = lastResult;
1834 * Make sure PQerrorMessage agrees with concatenated result
1836 resetPQExpBuffer(&conn->errorMessage);
1837 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
1840 PQclear(lastResult);
1842 lastResult = result;
1843 if (result->resultStatus == PGRES_COPY_IN ||
1844 result->resultStatus == PGRES_COPY_OUT ||
1845 result->resultStatus == PGRES_COPY_BOTH ||
1846 conn->status == CONNECTION_BAD)
1854 * PQdescribePrepared
1855 * Obtain information about a previously prepared statement
1857 * If the query was not even sent, return NULL; conn->errorMessage is set to
1858 * a relevant message.
1859 * If the query was sent, a new PGresult is returned (which could indicate
1860 * either success or failure). On success, the PGresult contains status
1861 * PGRES_COMMAND_OK, and its parameter and column-heading fields describe
1862 * the statement's inputs and outputs respectively.
1863 * The user is responsible for freeing the PGresult via PQclear()
1864 * when done with it.
1867 PQdescribePrepared(PGconn *conn, const char *stmt)
1869 if (!PQexecStart(conn))
1871 if (!PQsendDescribe(conn, 'S', stmt))
1873 return PQexecFinish(conn);
1878 * Obtain information about a previously created portal
1880 * This is much like PQdescribePrepared, except that no parameter info is
1881 * returned. Note that at the moment, libpq doesn't really expose portals
1882 * to the client; but this can be used with a portal created by a SQL
1883 * DECLARE CURSOR command.
1886 PQdescribePortal(PGconn *conn, const char *portal)
1888 if (!PQexecStart(conn))
1890 if (!PQsendDescribe(conn, 'P', portal))
1892 return PQexecFinish(conn);
1896 * PQsendDescribePrepared
1897 * Submit a Describe Statement command, but don't wait for it to finish
1899 * Returns: 1 if successfully submitted
1900 * 0 if error (conn->errorMessage is set)
1903 PQsendDescribePrepared(PGconn *conn, const char *stmt)
1905 return PQsendDescribe(conn, 'S', stmt);
1909 * PQsendDescribePortal
1910 * Submit a Describe Portal command, but don't wait for it to finish
1912 * Returns: 1 if successfully submitted
1913 * 0 if error (conn->errorMessage is set)
1916 PQsendDescribePortal(PGconn *conn, const char *portal)
1918 return PQsendDescribe(conn, 'P', portal);
1923 * Common code to send a Describe command
1925 * Available options for desc_type are
1926 * 'S' to describe a prepared statement; or
1927 * 'P' to describe a portal.
1928 * Returns 1 on success and 0 on failure.
1931 PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
1933 /* Treat null desc_target as empty string */
1937 if (!PQsendQueryStart(conn))
1940 /* This isn't gonna work on a 2.0 server */
1941 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1943 printfPQExpBuffer(&conn->errorMessage,
1944 libpq_gettext("function requires at least protocol version 3.0\n"));
1948 /* construct the Describe message */
1949 if (pqPutMsgStart('D', false, conn) < 0 ||
1950 pqPutc(desc_type, conn) < 0 ||
1951 pqPuts(desc_target, conn) < 0 ||
1952 pqPutMsgEnd(conn) < 0)
1955 /* construct the Sync message */
1956 if (pqPutMsgStart('S', false, conn) < 0 ||
1957 pqPutMsgEnd(conn) < 0)
1960 /* remember we are doing a Describe */
1961 conn->queryclass = PGQUERY_DESCRIBE;
1963 /* reset last-query string (not relevant now) */
1964 if (conn->last_query)
1966 free(conn->last_query);
1967 conn->last_query = NULL;
1971 * Give the data a push. In nonblock mode, don't complain if we're unable
1972 * to send it all; PQgetResult() will do any additional flushing needed.
1974 if (pqFlush(conn) < 0)
1977 /* OK, it's launched! */
1978 conn->asyncStatus = PGASYNC_BUSY;
1982 pqHandleSendFailure(conn);
1988 * returns a PGnotify* structure of the latest async notification
1989 * that has not yet been handled
1991 * returns NULL, if there is currently
1992 * no unhandled async notification from the backend
1994 * the CALLER is responsible for FREE'ing the structure returned
1997 PQnotifies(PGconn *conn)
2004 /* Parse any available data to see if we can extract NOTIFY messages. */
2007 event = conn->notifyHead;
2010 conn->notifyHead = event->next;
2011 if (!conn->notifyHead)
2012 conn->notifyTail = NULL;
2013 event->next = NULL; /* don't let app see the internal state */
2019 * PQputCopyData - send some data to the backend during COPY IN or COPY BOTH
2021 * Returns 1 if successful, 0 if data could not be sent (only possible
2022 * in nonblock mode), or -1 if an error occurs.
2025 PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
2029 if (conn->asyncStatus != PGASYNC_COPY_IN &&
2030 conn->asyncStatus != PGASYNC_COPY_BOTH)
2032 printfPQExpBuffer(&conn->errorMessage,
2033 libpq_gettext("no COPY in progress\n"));
2038 * Process any NOTICE or NOTIFY messages that might be pending in the
2039 * input buffer. Since the server might generate many notices during the
2040 * COPY, we want to clean those out reasonably promptly to prevent
2041 * indefinite expansion of the input buffer. (Note: the actual read of
2042 * input data into the input buffer happens down inside pqSendSome, but
2043 * it's not authorized to get rid of the data again.)
2050 * Try to flush any previously sent data in preference to growing the
2051 * output buffer. If we can't enlarge the buffer enough to hold the
2052 * data, return 0 in the nonblock case, else hard error. (For
2053 * simplicity, always assume 5 bytes of overhead even in protocol 2.0
2056 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2058 if (pqFlush(conn) < 0)
2060 if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2062 return pqIsnonblocking(conn) ? 0 : -1;
2064 /* Send the data (too simple to delegate to fe-protocol files) */
2065 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2067 if (pqPutMsgStart('d', false, conn) < 0 ||
2068 pqPutnchar(buffer, nbytes, conn) < 0 ||
2069 pqPutMsgEnd(conn) < 0)
2074 if (pqPutMsgStart(0, false, conn) < 0 ||
2075 pqPutnchar(buffer, nbytes, conn) < 0 ||
2076 pqPutMsgEnd(conn) < 0)
2084 * PQputCopyEnd - send EOF indication to the backend during COPY IN
2086 * After calling this, use PQgetResult() to check command completion status.
2088 * Returns 1 if successful, 0 if data could not be sent (only possible
2089 * in nonblock mode), or -1 if an error occurs.
2092 PQputCopyEnd(PGconn *conn, const char *errormsg)
2096 if (conn->asyncStatus != PGASYNC_COPY_IN)
2098 printfPQExpBuffer(&conn->errorMessage,
2099 libpq_gettext("no COPY in progress\n"));
2104 * Send the COPY END indicator. This is simple enough that we don't
2105 * bother delegating it to the fe-protocol files.
2107 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2111 /* Send COPY FAIL */
2112 if (pqPutMsgStart('f', false, conn) < 0 ||
2113 pqPuts(errormsg, conn) < 0 ||
2114 pqPutMsgEnd(conn) < 0)
2119 /* Send COPY DONE */
2120 if (pqPutMsgStart('c', false, conn) < 0 ||
2121 pqPutMsgEnd(conn) < 0)
2126 * If we sent the COPY command in extended-query mode, we must issue a
2129 if (conn->queryclass != PGQUERY_SIMPLE)
2131 if (pqPutMsgStart('S', false, conn) < 0 ||
2132 pqPutMsgEnd(conn) < 0)
2140 /* Ooops, no way to do this in 2.0 */
2141 printfPQExpBuffer(&conn->errorMessage,
2142 libpq_gettext("function requires at least protocol version 3.0\n"));
2147 /* Send old-style end-of-data marker */
2148 if (pqPutMsgStart(0, false, conn) < 0 ||
2149 pqPutnchar("\\.\n", 3, conn) < 0 ||
2150 pqPutMsgEnd(conn) < 0)
2155 /* Return to active duty */
2156 conn->asyncStatus = PGASYNC_BUSY;
2157 resetPQExpBuffer(&conn->errorMessage);
2159 /* Try to flush data */
2160 if (pqFlush(conn) < 0)
2167 * PQgetCopyData - read a row of data from the backend during COPY OUT
2170 * If successful, sets *buffer to point to a malloc'd row of data, and
2171 * returns row length (always > 0) as result.
2172 * Returns 0 if no row available yet (only possible if async is true),
2173 * -1 if end of copy (consult PQgetResult), or -2 if error (consult
2177 PQgetCopyData(PGconn *conn, char **buffer, int async)
2179 *buffer = NULL; /* for all failure cases */
2182 if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2183 conn->asyncStatus != PGASYNC_COPY_BOTH)
2185 printfPQExpBuffer(&conn->errorMessage,
2186 libpq_gettext("no COPY in progress\n"));
2189 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2190 return pqGetCopyData3(conn, buffer, async);
2192 return pqGetCopyData2(conn, buffer, async);
2196 * PQgetline - gets a newline-terminated string from the backend.
2198 * Chiefly here so that applications can use "COPY <rel> to stdout"
2199 * and read the output string. Returns a null-terminated string in s.
2201 * XXX this routine is now deprecated, because it can't handle binary data.
2202 * If called during a COPY BINARY we return EOF.
2204 * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
2205 * the terminating \n (like gets(3)).
2207 * CAUTION: the caller is responsible for detecting the end-of-copy signal
2208 * (a line containing just "\.") when using this routine.
2211 * EOF if error (eg, invalid arguments are given)
2212 * 0 if EOL is reached (i.e., \n has been read)
2213 * (this is required for backward-compatibility -- this
2214 * routine used to always return EOF or 0, assuming that
2215 * the line ended within maxlen bytes.)
2216 * 1 in other cases (i.e., the buffer was filled before \n is reached)
2219 PQgetline(PGconn *conn, char *s, int maxlen)
2221 if (!s || maxlen <= 0)
2224 /* maxlen must be at least 3 to hold the \. terminator! */
2231 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2232 return pqGetline3(conn, s, maxlen);
2234 return pqGetline2(conn, s, maxlen);
2238 * PQgetlineAsync - gets a COPY data row without blocking.
2240 * This routine is for applications that want to do "COPY <rel> to stdout"
2241 * asynchronously, that is without blocking. Having issued the COPY command
2242 * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
2243 * and this routine until the end-of-data signal is detected. Unlike
2244 * PQgetline, this routine takes responsibility for detecting end-of-data.
2246 * On each call, PQgetlineAsync will return data if a complete data row
2247 * is available in libpq's input buffer. Otherwise, no data is returned
2248 * until the rest of the row arrives.
2250 * If -1 is returned, the end-of-data signal has been recognized (and removed
2251 * from libpq's input buffer). The caller *must* next call PQendcopy and
2252 * then return to normal processing.
2255 * -1 if the end-of-copy-data marker has been recognized
2256 * 0 if no data is available
2257 * >0 the number of bytes returned.
2259 * The data returned will not extend beyond a data-row boundary. If possible
2260 * a whole row will be returned at one time. But if the buffer offered by
2261 * the caller is too small to hold a row sent by the backend, then a partial
2262 * data row will be returned. In text mode this can be detected by testing
2263 * whether the last returned byte is '\n' or not.
2265 * The returned data is *not* null-terminated.
2269 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
2274 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2275 return pqGetlineAsync3(conn, buffer, bufsize);
2277 return pqGetlineAsync2(conn, buffer, bufsize);
2281 * PQputline -- sends a string to the backend during COPY IN.
2282 * Returns 0 if OK, EOF if not.
2284 * This is deprecated primarily because the return convention doesn't allow
2285 * caller to tell the difference between a hard error and a nonblock-mode
2289 PQputline(PGconn *conn, const char *s)
2291 return PQputnbytes(conn, s, strlen(s));
2295 * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
2296 * Returns 0 if OK, EOF if not.
2299 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
2301 if (PQputCopyData(conn, buffer, nbytes) > 0)
2309 * After completing the data transfer portion of a copy in/out,
2310 * the application must call this routine to finish the command protocol.
2312 * When using protocol 3.0 this is deprecated; it's cleaner to use PQgetResult
2313 * to get the transfer status. Note however that when using 2.0 protocol,
2314 * recovering from a copy failure often requires a PQreset. PQendcopy will
2315 * take care of that, PQgetResult won't.
2322 PQendcopy(PGconn *conn)
2327 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2328 return pqEndcopy3(conn);
2330 return pqEndcopy2(conn);
2335 * PQfn - Send a function call to the POSTGRES backend.
2337 * conn : backend connection
2338 * fnid : function id
2339 * result_buf : pointer to result buffer (&int if integer)
2340 * result_len : length of return value.
2341 * actual_result_len: actual length returned. (differs from result_len
2342 * for varlena structures.)
2343 * result_type : If the result is an integer, this must be 1,
2344 * otherwise this should be 0
2345 * args : pointer to an array of function arguments.
2346 * (each has length, if integer, and value/pointer)
2347 * nargs : # of arguments in args array.
2350 * PGresult with status = PGRES_COMMAND_OK if successful.
2351 * *actual_result_len is > 0 if there is a return value, 0 if not.
2352 * PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
2353 * NULL on communications failure. conn->errorMessage will be set.
2361 int *actual_result_len,
2363 const PQArgBlock *args,
2366 *actual_result_len = 0;
2371 /* clear the error string */
2372 resetPQExpBuffer(&conn->errorMessage);
2374 if (conn->sock < 0 || conn->asyncStatus != PGASYNC_IDLE ||
2375 conn->result != NULL)
2377 printfPQExpBuffer(&conn->errorMessage,
2378 libpq_gettext("connection in wrong state\n"));
2382 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2383 return pqFunctionCall3(conn, fnid,
2384 result_buf, actual_result_len,
2388 return pqFunctionCall2(conn, fnid,
2389 result_buf, actual_result_len,
2395 /* ====== accessor funcs for PGresult ======== */
2398 PQresultStatus(const PGresult *res)
2401 return PGRES_FATAL_ERROR;
2402 return res->resultStatus;
2406 PQresStatus(ExecStatusType status)
2408 if (status < 0 || status >= sizeof pgresStatus / sizeof pgresStatus[0])
2409 return libpq_gettext("invalid ExecStatusType code");
2410 return pgresStatus[status];
2414 PQresultErrorMessage(const PGresult *res)
2416 if (!res || !res->errMsg)
2422 PQresultErrorField(const PGresult *res, int fieldcode)
2424 PGMessageField *pfield;
2428 for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
2430 if (pfield->code == fieldcode)
2431 return pfield->contents;
2437 PQntuples(const PGresult *res)
2445 PQnfields(const PGresult *res)
2449 return res->numAttributes;
2453 PQbinaryTuples(const PGresult *res)
2461 * Helper routines to range-check field numbers and tuple numbers.
2462 * Return TRUE if OK, FALSE if not
2466 check_field_number(const PGresult *res, int field_num)
2469 return FALSE; /* no way to display error message... */
2470 if (field_num < 0 || field_num >= res->numAttributes)
2472 pqInternalNotice(&res->noticeHooks,
2473 "column number %d is out of range 0..%d",
2474 field_num, res->numAttributes - 1);
2481 check_tuple_field_number(const PGresult *res,
2482 int tup_num, int field_num)
2485 return FALSE; /* no way to display error message... */
2486 if (tup_num < 0 || tup_num >= res->ntups)
2488 pqInternalNotice(&res->noticeHooks,
2489 "row number %d is out of range 0..%d",
2490 tup_num, res->ntups - 1);
2493 if (field_num < 0 || field_num >= res->numAttributes)
2495 pqInternalNotice(&res->noticeHooks,
2496 "column number %d is out of range 0..%d",
2497 field_num, res->numAttributes - 1);
2504 check_param_number(const PGresult *res, int param_num)
2507 return FALSE; /* no way to display error message... */
2508 if (param_num < 0 || param_num >= res->numParameters)
2510 pqInternalNotice(&res->noticeHooks,
2511 "parameter number %d is out of range 0..%d",
2512 param_num, res->numParameters - 1);
2520 * returns NULL if the field_num is invalid
2523 PQfname(const PGresult *res, int field_num)
2525 if (!check_field_number(res, field_num))
2528 return res->attDescs[field_num].name;
2534 * PQfnumber: find column number given column name
2536 * The column name is parsed as if it were in a SQL statement, including
2537 * case-folding and double-quote processing. But note a possible gotcha:
2538 * downcasing in the frontend might follow different locale rules than
2539 * downcasing in the backend...
2541 * Returns -1 if no match. In the present backend it is also possible
2542 * to have multiple matches, in which case the first one is found.
2545 PQfnumber(const PGresult *res, const char *field_name)
2557 * Note: it is correct to reject a zero-length input string; the proper
2558 * input to match a zero-length field name would be "".
2560 if (field_name == NULL ||
2561 field_name[0] == '\0' ||
2562 res->attDescs == NULL)
2566 * Note: this code will not reject partially quoted strings, eg
2567 * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
2570 field_case = strdup(field_name);
2571 if (field_case == NULL)
2572 return -1; /* grotty */
2576 for (iptr = field_case; *iptr; iptr++)
2586 /* doubled quotes become a single quote */
2600 c = pg_tolower((unsigned char) c);
2606 for (i = 0; i < res->numAttributes; i++)
2608 if (strcmp(field_case, res->attDescs[i].name) == 0)
2619 PQftable(const PGresult *res, int field_num)
2621 if (!check_field_number(res, field_num))
2624 return res->attDescs[field_num].tableid;
2630 PQftablecol(const PGresult *res, int field_num)
2632 if (!check_field_number(res, field_num))
2635 return res->attDescs[field_num].columnid;
2641 PQfformat(const PGresult *res, int field_num)
2643 if (!check_field_number(res, field_num))
2646 return res->attDescs[field_num].format;
2652 PQftype(const PGresult *res, int field_num)
2654 if (!check_field_number(res, field_num))
2657 return res->attDescs[field_num].typid;
2663 PQfsize(const PGresult *res, int field_num)
2665 if (!check_field_number(res, field_num))
2668 return res->attDescs[field_num].typlen;
2674 PQfmod(const PGresult *res, int field_num)
2676 if (!check_field_number(res, field_num))
2679 return res->attDescs[field_num].atttypmod;
2685 PQcmdStatus(PGresult *res)
2689 return res->cmdStatus;
2694 * if the last command was an INSERT, return the oid string
2698 PQoidStatus(const PGresult *res)
2701 * This must be enough to hold the result. Don't laugh, this is better
2702 * than what this function used to do.
2704 static char buf[24];
2708 if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2711 len = strspn(res->cmdStatus + 7, "0123456789");
2714 strncpy(buf, res->cmdStatus + 7, len);
2722 * a perhaps preferable form of the above which just returns
2726 PQoidValue(const PGresult *res)
2728 char *endptr = NULL;
2729 unsigned long result;
2733 strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
2734 res->cmdStatus[7] < '0' ||
2735 res->cmdStatus[7] > '9')
2738 result = strtoul(res->cmdStatus + 7, &endptr, 10);
2740 if (!endptr || (*endptr != ' ' && *endptr != '\0'))
2743 return (Oid) result;
2749 * If the last command was INSERT/UPDATE/DELETE/MOVE/FETCH/COPY, return
2750 * a string containing the number of inserted/affected tuples. If not,
2753 * XXX: this should probably return an int
2756 PQcmdTuples(PGresult *res)
2764 if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
2766 p = res->cmdStatus + 7;
2767 /* INSERT: skip oid and space */
2768 while (*p && *p != ' ')
2771 goto interpret_error; /* no space? */
2774 else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
2775 strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
2776 strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
2777 p = res->cmdStatus + 7;
2778 else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
2779 p = res->cmdStatus + 6;
2780 else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
2781 strncmp(res->cmdStatus, "COPY ", 5) == 0)
2782 p = res->cmdStatus + 5;
2786 /* check that we have an integer (at least one digit, nothing else) */
2787 for (c = p; *c; c++)
2789 if (!isdigit((unsigned char) *c))
2790 goto interpret_error;
2793 goto interpret_error;
2798 pqInternalNotice(&res->noticeHooks,
2799 "could not interpret result from server: %s",
2806 * return the value of field 'field_num' of row 'tup_num'
2809 PQgetvalue(const PGresult *res, int tup_num, int field_num)
2811 if (!check_tuple_field_number(res, tup_num, field_num))
2813 return res->tuples[tup_num][field_num].value;
2817 * returns the actual length of a field value in bytes.
2820 PQgetlength(const PGresult *res, int tup_num, int field_num)
2822 if (!check_tuple_field_number(res, tup_num, field_num))
2824 if (res->tuples[tup_num][field_num].len != NULL_LEN)
2825 return res->tuples[tup_num][field_num].len;
2831 * returns the null status of a field value.
2834 PQgetisnull(const PGresult *res, int tup_num, int field_num)
2836 if (!check_tuple_field_number(res, tup_num, field_num))
2837 return 1; /* pretend it is null */
2838 if (res->tuples[tup_num][field_num].len == NULL_LEN)
2845 * returns the number of input parameters of a prepared statement.
2848 PQnparams(const PGresult *res)
2852 return res->numParameters;
2856 * returns type Oid of the specified statement parameter.
2859 PQparamtype(const PGresult *res, int param_num)
2861 if (!check_param_number(res, param_num))
2863 if (res->paramDescs)
2864 return res->paramDescs[param_num].typid;
2870 /* PQsetnonblocking:
2871 * sets the PGconn's database connection non-blocking if the arg is TRUE
2872 * or makes it non-blocking if the arg is FALSE, this will not protect
2873 * you from PQexec(), you'll only be safe when using the non-blocking API.
2874 * Needs to be called only on a connected database connection.
2877 PQsetnonblocking(PGconn *conn, int arg)
2881 if (!conn || conn->status == CONNECTION_BAD)
2884 barg = (arg ? TRUE : FALSE);
2886 /* early out if the socket is already in the state requested */
2887 if (barg == conn->nonblocking)
2891 * to guarantee constancy for flushing/query/result-polling behavior we
2892 * need to flush the send queue at this point in order to guarantee proper
2893 * behavior. this is ok because either they are making a transition _from_
2894 * or _to_ blocking mode, either way we can block them.
2896 /* if we are going from blocking to non-blocking flush here */
2900 conn->nonblocking = barg;
2906 * return the blocking status of the database connection
2907 * TRUE == nonblocking, FALSE == blocking
2910 PQisnonblocking(const PGconn *conn)
2912 return pqIsnonblocking(conn);
2915 /* libpq is thread-safe? */
2917 PQisthreadsafe(void)
2919 #ifdef ENABLE_THREAD_SAFETY
2927 /* try to force data out, really only useful for non-blocking users */
2929 PQflush(PGconn *conn)
2931 return pqFlush(conn);
2936 * PQfreemem - safely frees memory allocated
2938 * Needed mostly by Win32, unless multithreaded DLL (/MD in VC6)
2939 * Used for freeing memory from PQescapeByte()a/PQunescapeBytea()
2942 PQfreemem(void *ptr)
2948 * PQfreeNotify - free's the memory associated with a PGnotify
2950 * This function is here only for binary backward compatibility.
2951 * New code should use PQfreemem(). A macro will automatically map
2952 * calls to PQfreemem. It should be removed in the future. bjm 2003-03-24
2956 void PQfreeNotify(PGnotify *notify);
2959 PQfreeNotify(PGnotify *notify)
2966 * Escaping arbitrary strings to get valid SQL literal strings.
2968 * Replaces "'" with "''", and if not std_strings, replaces "\" with "\\".
2970 * length is the length of the source string. (Note: if a terminating NUL
2971 * is encountered sooner, PQescapeString stops short of "length"; the behavior
2972 * is thus rather like strncpy.)
2974 * For safety the buffer at "to" must be at least 2*length + 1 bytes long.
2975 * A terminating NUL character is added to the output string, whether the
2976 * input is NUL-terminated or not.
2978 * Returns the actual length of the output (not counting the terminating NUL).
2981 PQescapeStringInternal(PGconn *conn,
2982 char *to, const char *from, size_t length,
2984 int encoding, bool std_strings)
2986 const char *source = from;
2988 size_t remaining = length;
2993 while (remaining > 0 && *source != '\0')
2999 /* Fast path for plain ASCII */
3000 if (!IS_HIGHBIT_SET(c))
3002 /* Apply quoting if needed */
3003 if (SQL_STR_DOUBLE(c, !std_strings))
3005 /* Copy the character */
3012 /* Slow path for possible multibyte characters */
3013 len = pg_encoding_mblen(encoding, source);
3015 /* Copy the character */
3016 for (i = 0; i < len; i++)
3018 if (remaining == 0 || *source == '\0')
3020 *target++ = *source++;
3025 * If we hit premature end of string (ie, incomplete multibyte
3026 * character), try to pad out to the correct length with spaces. We
3027 * may not be able to pad completely, but we will always be able to
3028 * insert at least one pad space (since we'd not have quoted a
3029 * multibyte character). This should be enough to make a string that
3030 * the server will error out on.
3037 printfPQExpBuffer(&conn->errorMessage,
3038 libpq_gettext("incomplete multibyte character\n"));
3039 for (; i < len; i++)
3041 if (((size_t) (target - to)) / 2 >= length)
3049 /* Write the terminating NUL character. */
3056 PQescapeStringConn(PGconn *conn,
3057 char *to, const char *from, size_t length,
3062 /* force empty-string result */
3068 return PQescapeStringInternal(conn, to, from, length, error,
3069 conn->client_encoding,
3074 PQescapeString(char *to, const char *from, size_t length)
3076 return PQescapeStringInternal(NULL, to, from, length, NULL,
3077 static_client_encoding,
3078 static_std_strings);
3083 * Escape arbitrary strings. If as_ident is true, we escape the result
3084 * as an identifier; if false, as a literal. The result is returned in
3085 * a newly allocated buffer. If we fail due to an encoding violation or out
3086 * of memory condition, we return NULL, storing an error message into conn.
3089 PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
3094 int num_quotes = 0; /* single or double, depending on as_ident */
3095 int num_backslashes = 0;
3098 char quote_char = as_ident ? '"' : '\'';
3100 /* We must have a connection, else fail immediately. */
3104 /* Scan the string for characters that must be escaped. */
3105 for (s = str; (s - str) < len && *s != '\0'; ++s)
3107 if (*s == quote_char)
3109 else if (*s == '\\')
3111 else if (IS_HIGHBIT_SET(*s))
3115 /* Slow path for possible multibyte characters */
3116 charlen = pg_encoding_mblen(conn->client_encoding, s);
3118 /* Multibyte character overruns allowable length. */
3119 if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
3121 printfPQExpBuffer(&conn->errorMessage,
3122 libpq_gettext("incomplete multibyte character\n"));
3126 /* Adjust s, bearing in mind that for loop will increment it. */
3131 /* Allocate output buffer. */
3132 input_len = s - str;
3133 result_size = input_len + num_quotes + 3; /* two quotes, plus a NUL */
3134 if (!as_ident && num_backslashes > 0)
3135 result_size += num_backslashes + 2;
3136 result = rp = (char *) malloc(result_size);
3139 printfPQExpBuffer(&conn->errorMessage,
3140 libpq_gettext("out of memory\n"));
3145 * If we are escaping a literal that contains backslashes, we use the
3146 * escape string syntax so that the result is correct under either value
3147 * of standard_conforming_strings. We also emit a leading space in this
3148 * case, to guard against the possibility that the result might be
3149 * interpolated immediately following an identifier.
3151 if (!as_ident && num_backslashes > 0)
3157 /* Opening quote. */
3161 * Use fast path if possible.
3163 * We've already verified that the input string is well-formed in the
3164 * current encoding. If it contains no quotes and, in the case of
3165 * literal-escaping, no backslashes, then we can just copy it directly to
3166 * the output buffer, adding the necessary quotes.
3168 * If not, we must rescan the input and process each character
3171 if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
3173 memcpy(rp, str, input_len);
3178 for (s = str; s - str < input_len; ++s)
3180 if (*s == quote_char || (!as_ident && *s == '\\'))
3185 else if (!IS_HIGHBIT_SET(*s))
3189 int i = pg_encoding_mblen(conn->client_encoding, s);
3196 ++s; /* for loop will provide the final increment */
3202 /* Closing quote and terminating NUL. */
3210 PQescapeLiteral(PGconn *conn, const char *str, size_t len)
3212 return PQescapeInternal(conn, str, len, false);
3216 PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
3218 return PQescapeInternal(conn, str, len, true);
3221 /* HEX encoding support for bytea */
3222 static const char hextbl[] = "0123456789abcdef";
3224 static const int8 hexlookup[128] = {
3225 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3226 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3227 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3228 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
3229 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3230 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3231 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3232 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3240 if (c > 0 && c < 127)
3241 res = hexlookup[(unsigned char) c];
3248 * PQescapeBytea - converts from binary string to the
3249 * minimal encoding necessary to include the string in an SQL
3250 * INSERT statement with a bytea type column as the target.
3252 * We can use either hex or escape (traditional) encoding.
3253 * In escape mode, the following transformations are applied:
3254 * '\0' == ASCII 0 == \000
3255 * '\'' == ASCII 39 == ''
3256 * '\\' == ASCII 92 == \\
3257 * anything < 0x20, or > 0x7e ---> \ooo
3258 * (where ooo is an octal expression)
3260 * If not std_strings, all backslashes sent to the output are doubled.
3262 static unsigned char *
3263 PQescapeByteaInternal(PGconn *conn,
3264 const unsigned char *from, size_t from_length,
3265 size_t *to_length, bool std_strings, bool use_hex)
3267 const unsigned char *vp;
3269 unsigned char *result;
3272 size_t bslash_len = (std_strings ? 1 : 2);
3275 * empty string has 1 char ('\0')
3281 len += bslash_len + 1 + 2 * from_length;
3286 for (i = from_length; i > 0; i--, vp++)
3288 if (*vp < 0x20 || *vp > 0x7e)
3289 len += bslash_len + 3;
3290 else if (*vp == '\'')
3292 else if (*vp == '\\')
3293 len += bslash_len + bslash_len;
3300 rp = result = (unsigned char *) malloc(len);
3304 printfPQExpBuffer(&conn->errorMessage,
3305 libpq_gettext("out of memory\n"));
3318 for (i = from_length; i > 0; i--, vp++)
3320 unsigned char c = *vp;
3324 *rp++ = hextbl[(c >> 4) & 0xF];
3325 *rp++ = hextbl[c & 0xF];
3327 else if (c < 0x20 || c > 0x7e)
3332 *rp++ = (c >> 6) + '0';
3333 *rp++ = ((c >> 3) & 07) + '0';
3334 *rp++ = (c & 07) + '0';
3360 PQescapeByteaConn(PGconn *conn,
3361 const unsigned char *from, size_t from_length,
3366 return PQescapeByteaInternal(conn, from, from_length, to_length,
3368 (conn->sversion >= 90000));
3372 PQescapeBytea(const unsigned char *from, size_t from_length, size_t *to_length)
3374 return PQescapeByteaInternal(NULL, from, from_length, to_length,
3376 false /* can't use hex */ );
3380 #define ISFIRSTOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '3')
3381 #define ISOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '7')
3382 #define OCTVAL(CH) ((CH) - '0')
3385 * PQunescapeBytea - converts the null terminated string representation
3386 * of a bytea, strtext, into binary, filling a buffer. It returns a
3387 * pointer to the buffer (or NULL on error), and the size of the
3388 * buffer in retbuflen. The pointer may subsequently be used as an
3389 * argument to the function PQfreemem.
3391 * The following transformations are made:
3392 * \\ == ASCII 92 == \
3393 * \ooo == a byte whose value = ooo (ooo is an octal number)
3394 * \x == x (x is any character not matched by the above transformations)
3397 PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
3401 unsigned char *buffer,
3406 if (strtext == NULL)
3409 strtextlen = strlen((const char *) strtext);
3411 if (strtext[0] == '\\' && strtext[1] == 'x')
3413 const unsigned char *s;
3416 buflen = (strtextlen - 2) / 2;
3417 /* Avoid unportable malloc(0) */
3418 buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
3430 * Bad input is silently ignored. Note that this includes
3431 * whitespace between hex pairs, which is allowed by byteain.
3434 if (!*s || v1 == (char) -1)
3437 if (v2 != (char) -1)
3438 *p++ = (v1 << 4) | v2;
3441 buflen = p - buffer;
3446 * Length of input is max length of output, but add one to avoid
3447 * unportable malloc(0) if input is zero-length.
3449 buffer = (unsigned char *) malloc(strtextlen + 1);
3453 for (i = j = 0; i < strtextlen;)
3459 if (strtext[i] == '\\')
3460 buffer[j++] = strtext[i++];
3463 if ((ISFIRSTOCTDIGIT(strtext[i])) &&
3464 (ISOCTDIGIT(strtext[i + 1])) &&
3465 (ISOCTDIGIT(strtext[i + 2])))
3469 byte = OCTVAL(strtext[i++]);
3470 byte = (byte <<3) +OCTVAL(strtext[i++]);
3471 byte = (byte <<3) +OCTVAL(strtext[i++]);
3477 * Note: if we see '\' followed by something that isn't a
3478 * recognized escape sequence, we loop around having done
3479 * nothing except advance i. Therefore the something will
3480 * be emitted as ordinary data on the next cycle. Corner
3481 * case: '\' at end of string will just be discarded.
3486 buffer[j++] = strtext[i++];
3490 buflen = j; /* buflen is the length of the dequoted data */
3493 /* Shrink the buffer to be no larger than necessary */
3494 /* +1 avoids unportable behavior when buflen==0 */
3495 tmpbuf = realloc(buffer, buflen + 1);
3497 /* It would only be a very brain-dead realloc that could fail, but... */
3504 *retbuflen = buflen;