1 /*-------------------------------------------------------------------------
4 * functions related to sending a query down to the backend
6 * Portions Copyright (c) 1996-2013, 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 bool PQexecStart(PGconn *conn);
67 static PGresult *PQexecFinish(PGconn *conn);
68 static int PQsendDescribe(PGconn *conn, char desc_type,
69 const char *desc_target);
70 static int check_field_number(const PGresult *res, int field_num);
74 * Space management for PGresult.
76 * Formerly, libpq did a separate malloc() for each field of each tuple
77 * returned by a query. This was remarkably expensive --- malloc/free
78 * consumed a sizable part of the application's runtime. And there is
79 * no real need to keep track of the fields separately, since they will
80 * all be freed together when the PGresult is released. So now, we grab
81 * large blocks of storage from malloc and allocate space for query data
82 * within these blocks, using a trivially simple allocator. This reduces
83 * the number of malloc/free calls dramatically, and it also avoids
84 * fragmentation of the malloc storage arena.
85 * The PGresult structure itself is still malloc'd separately. We could
86 * combine it with the first allocation block, but that would waste space
87 * for the common case that no extra storage is actually needed (that is,
88 * the SQL command did not return tuples).
90 * We also malloc the top-level array of tuple pointers separately, because
91 * we need to be able to enlarge it via realloc, and our trivial space
92 * allocator doesn't handle that effectively. (Too bad the FE/BE protocol
93 * doesn't tell us up front how many tuples will be returned.)
94 * All other subsidiary storage for a PGresult is kept in PGresult_data blocks
95 * of size PGRESULT_DATA_BLOCKSIZE. The overhead at the start of each block
96 * is just a link to the next one, if any. Free-space management info is
97 * kept in the owning PGresult.
98 * A query returning a small amount of data will thus require three malloc
99 * calls: one for the PGresult, one for the tuples pointer array, and one
100 * PGresult_data block.
102 * Only the most recently allocated PGresult_data block is a candidate to
103 * have more stuff added to it --- any extra space left over in older blocks
104 * is wasted. We could be smarter and search the whole chain, but the point
105 * here is to be simple and fast. Typical applications do not keep a PGresult
106 * around very long anyway, so some wasted space within one is not a problem.
108 * Tuning constants for the space allocator are:
109 * PGRESULT_DATA_BLOCKSIZE: size of a standard allocation block, in bytes
110 * PGRESULT_ALIGN_BOUNDARY: assumed alignment requirement for binary data
111 * PGRESULT_SEP_ALLOC_THRESHOLD: objects bigger than this are given separate
112 * blocks, instead of being crammed into a regular allocation block.
113 * Requirements for correct function are:
114 * PGRESULT_ALIGN_BOUNDARY must be a multiple of the alignment requirements
115 * of all machine data types. (Currently this is set from configure
116 * tests, so it should be OK automatically.)
117 * PGRESULT_SEP_ALLOC_THRESHOLD + PGRESULT_BLOCK_OVERHEAD <=
118 * PGRESULT_DATA_BLOCKSIZE
119 * pqResultAlloc assumes an object smaller than the threshold will fit
121 * The amount of space wasted at the end of a block could be as much as
122 * PGRESULT_SEP_ALLOC_THRESHOLD, so it doesn't pay to make that too large.
126 #define PGRESULT_DATA_BLOCKSIZE 2048
127 #define PGRESULT_ALIGN_BOUNDARY MAXIMUM_ALIGNOF /* from configure */
128 #define PGRESULT_BLOCK_OVERHEAD Max(sizeof(PGresult_data), PGRESULT_ALIGN_BOUNDARY)
129 #define PGRESULT_SEP_ALLOC_THRESHOLD (PGRESULT_DATA_BLOCKSIZE / 2)
133 * PQmakeEmptyPGresult
134 * returns a newly allocated, initialized PGresult with given status.
135 * If conn is not NULL and status indicates an error, the conn's
136 * errorMessage is copied. Also, any PGEvents are copied from the conn.
139 PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
143 result = (PGresult *) malloc(sizeof(PGresult));
148 result->numAttributes = 0;
149 result->attDescs = NULL;
150 result->tuples = NULL;
151 result->tupArrSize = 0;
152 result->numParameters = 0;
153 result->paramDescs = NULL;
154 result->resultStatus = status;
155 result->cmdStatus[0] = '\0';
157 result->events = NULL;
159 result->errMsg = NULL;
160 result->errFields = NULL;
161 result->null_field[0] = '\0';
162 result->curBlock = NULL;
163 result->curOffset = 0;
164 result->spaceLeft = 0;
168 /* copy connection data we might need for operations on PGresult */
169 result->noticeHooks = conn->noticeHooks;
170 result->client_encoding = conn->client_encoding;
172 /* consider copying conn's errorMessage */
175 case PGRES_EMPTY_QUERY:
176 case PGRES_COMMAND_OK:
177 case PGRES_TUPLES_OK:
180 case PGRES_COPY_BOTH:
181 case PGRES_SINGLE_TUPLE:
182 /* non-error cases */
185 pqSetResultError(result, conn->errorMessage.data);
189 /* copy events last; result must be valid if we need to PQclear */
190 if (conn->nEvents > 0)
192 result->events = dupEvents(conn->events, conn->nEvents);
198 result->nEvents = conn->nEvents;
204 result->noticeHooks.noticeRec = NULL;
205 result->noticeHooks.noticeRecArg = NULL;
206 result->noticeHooks.noticeProc = NULL;
207 result->noticeHooks.noticeProcArg = NULL;
208 result->client_encoding = PG_SQL_ASCII;
217 * Set the attributes for a given result. This function fails if there are
218 * already attributes contained in the provided result. The call is
219 * ignored if numAttributes is zero or attDescs is NULL. If the
220 * function fails, it returns zero. If the function succeeds, it
221 * returns a non-zero value.
224 PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs)
228 /* If attrs already exist, they cannot be overwritten. */
229 if (!res || res->numAttributes > 0)
232 /* ignore no-op request */
233 if (numAttributes <= 0 || !attDescs)
236 res->attDescs = (PGresAttDesc *)
237 PQresultAlloc(res, numAttributes * sizeof(PGresAttDesc));
242 res->numAttributes = numAttributes;
243 memcpy(res->attDescs, attDescs, numAttributes * sizeof(PGresAttDesc));
245 /* deep-copy the attribute names, and determine format */
247 for (i = 0; i < res->numAttributes; i++)
249 if (res->attDescs[i].name)
250 res->attDescs[i].name = pqResultStrdup(res, res->attDescs[i].name);
252 res->attDescs[i].name = res->null_field;
254 if (!res->attDescs[i].name)
257 if (res->attDescs[i].format == 0)
267 * Returns a deep copy of the provided 'src' PGresult, which cannot be NULL.
268 * The 'flags' argument controls which portions of the result will or will
269 * NOT be copied. The created result is always put into the
270 * PGRES_TUPLES_OK status. The source result error message is not copied,
271 * although cmdStatus is.
273 * To set custom attributes, use PQsetResultAttrs. That function requires
274 * that there are no attrs contained in the result, so to use that
275 * function you cannot use the PG_COPYRES_ATTRS or PG_COPYRES_TUPLES
276 * options with this function.
279 * PG_COPYRES_ATTRS - Copy the source result's attributes
281 * PG_COPYRES_TUPLES - Copy the source result's tuples. This implies
282 * copying the attrs, seeing how the attrs are needed by the tuples.
284 * PG_COPYRES_EVENTS - Copy the source result's events.
286 * PG_COPYRES_NOTICEHOOKS - Copy the source result's notice hooks.
289 PQcopyResult(const PGresult *src, int flags)
297 dest = PQmakeEmptyPGresult(NULL, PGRES_TUPLES_OK);
301 /* Always copy these over. Is cmdStatus really useful here? */
302 dest->client_encoding = src->client_encoding;
303 strcpy(dest->cmdStatus, src->cmdStatus);
306 if (flags & (PG_COPYRES_ATTRS | PG_COPYRES_TUPLES))
308 if (!PQsetResultAttrs(dest, src->numAttributes, src->attDescs))
315 /* Wants to copy tuples? */
316 if (flags & PG_COPYRES_TUPLES)
321 for (tup = 0; tup < src->ntups; tup++)
323 for (field = 0; field < src->numAttributes; field++)
325 if (!PQsetvalue(dest, tup, field,
326 src->tuples[tup][field].value,
327 src->tuples[tup][field].len))
336 /* Wants to copy notice hooks? */
337 if (flags & PG_COPYRES_NOTICEHOOKS)
338 dest->noticeHooks = src->noticeHooks;
340 /* Wants to copy PGEvents? */
341 if ((flags & PG_COPYRES_EVENTS) && src->nEvents > 0)
343 dest->events = dupEvents(src->events, src->nEvents);
349 dest->nEvents = src->nEvents;
352 /* Okay, trigger PGEVT_RESULTCOPY event */
353 for (i = 0; i < dest->nEvents; i++)
355 if (src->events[i].resultInitialized)
357 PGEventResultCopy evt;
361 if (!dest->events[i].proc(PGEVT_RESULTCOPY, &evt,
362 dest->events[i].passThrough))
367 dest->events[i].resultInitialized = TRUE;
375 * Copy an array of PGEvents (with no extra space for more).
376 * Does not duplicate the event instance data, sets this to NULL.
377 * Also, the resultInitialized flags are all cleared.
380 dupEvents(PGEvent *events, int count)
385 if (!events || count <= 0)
388 newEvents = (PGEvent *) malloc(count * sizeof(PGEvent));
392 for (i = 0; i < count; i++)
394 newEvents[i].proc = events[i].proc;
395 newEvents[i].passThrough = events[i].passThrough;
396 newEvents[i].data = NULL;
397 newEvents[i].resultInitialized = FALSE;
398 newEvents[i].name = strdup(events[i].name);
399 if (!newEvents[i].name)
402 free(newEvents[i].name);
413 * Sets the value for a tuple field. The tup_num must be less than or
414 * equal to PQntuples(res). If it is equal, a new tuple is created and
415 * added to the result.
416 * Returns a non-zero value for success and zero for failure.
419 PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len)
421 PGresAttValue *attval;
423 if (!check_field_number(res, field_num))
426 /* Invalid tup_num, must be <= ntups */
427 if (tup_num < 0 || tup_num > res->ntups)
430 /* need to allocate a new tuple? */
431 if (tup_num == res->ntups)
436 tup = (PGresAttValue *)
437 pqResultAlloc(res, res->numAttributes * sizeof(PGresAttValue),
443 /* initialize each column to NULL */
444 for (i = 0; i < res->numAttributes; i++)
446 tup[i].len = NULL_LEN;
447 tup[i].value = res->null_field;
450 /* add it to the array */
451 if (!pqAddTuple(res, tup))
455 attval = &res->tuples[tup_num][field_num];
457 /* treat either NULL_LEN or NULL value pointer as a NULL field */
458 if (len == NULL_LEN || value == NULL)
460 attval->len = NULL_LEN;
461 attval->value = res->null_field;
466 attval->value = res->null_field;
470 attval->value = (char *) pqResultAlloc(res, len + 1, TRUE);
474 memcpy(attval->value, value, len);
475 attval->value[len] = '\0';
482 * pqResultAlloc - exported routine to allocate local storage in a PGresult.
484 * We force all such allocations to be maxaligned, since we don't know
485 * whether the value might be binary.
488 PQresultAlloc(PGresult *res, size_t nBytes)
490 return pqResultAlloc(res, nBytes, TRUE);
495 * Allocate subsidiary storage for a PGresult.
497 * nBytes is the amount of space needed for the object.
498 * If isBinary is true, we assume that we need to align the object on
499 * a machine allocation boundary.
500 * If isBinary is false, we assume the object is a char string and can
501 * be allocated on any byte boundary.
504 pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
507 PGresult_data *block;
513 return res->null_field;
516 * If alignment is needed, round up the current position to an alignment
521 int offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
525 res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
526 res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
530 /* If there's enough space in the current block, no problem. */
531 if (nBytes <= (size_t) res->spaceLeft)
533 space = res->curBlock->space + res->curOffset;
534 res->curOffset += nBytes;
535 res->spaceLeft -= nBytes;
540 * If the requested object is very large, give it its own block; this
541 * avoids wasting what might be most of the current block to start a new
542 * block. (We'd have to special-case requests bigger than the block size
543 * anyway.) The object is always given binary alignment in this case.
545 if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
547 block = (PGresult_data *) malloc(nBytes + PGRESULT_BLOCK_OVERHEAD);
550 space = block->space + PGRESULT_BLOCK_OVERHEAD;
554 * Tuck special block below the active block, so that we don't
555 * have to waste the free space in the active block.
557 block->next = res->curBlock->next;
558 res->curBlock->next = block;
562 /* Must set up the new block as the first active block. */
564 res->curBlock = block;
565 res->spaceLeft = 0; /* be sure it's marked full */
570 /* Otherwise, start a new block. */
571 block = (PGresult_data *) malloc(PGRESULT_DATA_BLOCKSIZE);
574 block->next = res->curBlock;
575 res->curBlock = block;
578 /* object needs full alignment */
579 res->curOffset = PGRESULT_BLOCK_OVERHEAD;
580 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - PGRESULT_BLOCK_OVERHEAD;
584 /* we can cram it right after the overhead pointer */
585 res->curOffset = sizeof(PGresult_data);
586 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - sizeof(PGresult_data);
589 space = block->space + res->curOffset;
590 res->curOffset += nBytes;
591 res->spaceLeft -= nBytes;
597 * Like strdup, but the space is subsidiary PGresult space.
600 pqResultStrdup(PGresult *res, const char *str)
602 char *space = (char *) pqResultAlloc(res, strlen(str) + 1, FALSE);
611 * assign a new error message to a PGresult
614 pqSetResultError(PGresult *res, const char *msg)
619 res->errMsg = pqResultStrdup(res, msg);
625 * pqCatenateResultError -
626 * concatenate a new error message to the one already in a PGresult
629 pqCatenateResultError(PGresult *res, const char *msg)
631 PQExpBufferData errorBuf;
635 initPQExpBuffer(&errorBuf);
637 appendPQExpBufferStr(&errorBuf, res->errMsg);
638 appendPQExpBufferStr(&errorBuf, msg);
639 pqSetResultError(res, errorBuf.data);
640 termPQExpBuffer(&errorBuf);
645 * free's the memory associated with a PGresult
648 PQclear(PGresult *res)
650 PGresult_data *block;
656 for (i = 0; i < res->nEvents; i++)
658 /* only send DESTROY to successfully-initialized event procs */
659 if (res->events[i].resultInitialized)
661 PGEventResultDestroy evt;
664 (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
665 res->events[i].passThrough);
667 free(res->events[i].name);
673 /* Free all the subsidiary blocks */
674 while ((block = res->curBlock) != NULL)
676 res->curBlock = block->next;
680 /* Free the top-level tuple pointer array */
684 /* zero out the pointer fields to catch programming errors */
685 res->attDescs = NULL;
687 res->paramDescs = NULL;
688 res->errFields = NULL;
691 /* res->curBlock was zeroed out earlier */
693 /* Free the PGresult structure itself */
698 * Handy subroutine to deallocate any partially constructed async result.
700 * Any "next" result gets cleared too.
703 pqClearAsyncResult(PGconn *conn)
706 PQclear(conn->result);
708 if (conn->next_result)
709 PQclear(conn->next_result);
710 conn->next_result = NULL;
714 * This subroutine deletes any existing async result, sets conn->result
715 * to a PGresult with status PGRES_FATAL_ERROR, and stores the current
716 * contents of conn->errorMessage into that result. It differs from a
717 * plain call on PQmakeEmptyPGresult() in that if there is already an
718 * async result with status PGRES_FATAL_ERROR, the current error message
719 * is APPENDED to the old error message instead of replacing it. This
720 * behavior lets us report multiple error conditions properly, if necessary.
721 * (An example where this is needed is when the backend sends an 'E' message
722 * and immediately closes the connection --- we want to report both the
723 * backend error and the connection closure error.)
726 pqSaveErrorResult(PGconn *conn)
729 * If no old async result, just let PQmakeEmptyPGresult make one. Likewise
730 * if old result is not an error message.
732 if (conn->result == NULL ||
733 conn->result->resultStatus != PGRES_FATAL_ERROR ||
734 conn->result->errMsg == NULL)
736 pqClearAsyncResult(conn);
737 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
741 /* Else, concatenate error message to existing async result. */
742 pqCatenateResultError(conn->result, conn->errorMessage.data);
747 * This subroutine prepares an async result object for return to the caller.
748 * If there is not already an async result object, build an error object
749 * using whatever is in conn->errorMessage. In any case, clear the async
750 * result storage and make sure PQerrorMessage will agree with the result's
754 pqPrepareAsyncResult(PGconn *conn)
759 * conn->result is the PGresult to return. If it is NULL (which probably
760 * shouldn't happen) we assume there is an appropriate error message in
761 * conn->errorMessage.
765 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
769 * Make sure PQerrorMessage agrees with result; it could be different
770 * if we have concatenated messages.
772 resetPQExpBuffer(&conn->errorMessage);
773 appendPQExpBufferStr(&conn->errorMessage,
774 PQresultErrorMessage(res));
778 * Replace conn->result with next_result, if any. In the normal case
779 * there isn't a next result and we're just dropping ownership of the
780 * current result. In single-row mode this restores the situation to what
781 * it was before we created the current single-row result.
783 conn->result = conn->next_result;
784 conn->next_result = NULL;
790 * pqInternalNotice - produce an internally-generated notice message
792 * A format string and optional arguments can be passed. Note that we do
793 * libpq_gettext() here, so callers need not.
795 * The supplied text is taken as primary message (ie., it should not include
796 * a trailing newline, and should not be more than one line).
799 pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
805 if (hooks->noticeRec == NULL)
806 return; /* nobody home to receive notice? */
808 /* Format the message */
810 vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
812 msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
814 /* Make a PGresult to pass to the notice receiver */
815 res = PQmakeEmptyPGresult(NULL, PGRES_NONFATAL_ERROR);
818 res->noticeHooks = *hooks;
821 * Set up fields of notice.
823 pqSaveMessageField(res, PG_DIAG_MESSAGE_PRIMARY, msgBuf);
824 pqSaveMessageField(res, PG_DIAG_SEVERITY, libpq_gettext("NOTICE"));
825 /* XXX should provide a SQLSTATE too? */
828 * Result text is always just the primary message + newline. If we can't
829 * allocate it, don't bother invoking the receiver.
831 res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, FALSE);
834 sprintf(res->errMsg, "%s\n", msgBuf);
837 * Pass to receiver, then free it.
839 (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
846 * add a row pointer to the PGresult structure, growing it if necessary
847 * Returns TRUE if OK, FALSE if not enough memory to add the row
850 pqAddTuple(PGresult *res, PGresAttValue *tup)
852 if (res->ntups >= res->tupArrSize)
855 * Try to grow the array.
857 * We can use realloc because shallow copying of the structure is
858 * okay. Note that the first time through, res->tuples is NULL. While
859 * ANSI says that realloc() should act like malloc() in that case,
860 * some old C libraries (like SunOS 4.1.x) coredump instead. On
861 * failure realloc is supposed to return NULL without damaging the
862 * existing allocation. Note that the positions beyond res->ntups are
863 * garbage, not necessarily NULL.
865 int newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
866 PGresAttValue **newTuples;
868 if (res->tuples == NULL)
869 newTuples = (PGresAttValue **)
870 malloc(newSize * sizeof(PGresAttValue *));
872 newTuples = (PGresAttValue **)
873 realloc(res->tuples, newSize * sizeof(PGresAttValue *));
875 return FALSE; /* malloc or realloc failed */
876 res->tupArrSize = newSize;
877 res->tuples = newTuples;
879 res->tuples[res->ntups] = tup;
885 * pqSaveMessageField - save one field of an error or notice message
888 pqSaveMessageField(PGresult *res, char code, const char *value)
890 PGMessageField *pfield;
892 pfield = (PGMessageField *)
894 sizeof(PGMessageField) + strlen(value),
897 return; /* out of memory? */
899 strcpy(pfield->contents, value);
900 pfield->next = res->errFields;
901 res->errFields = pfield;
905 * pqSaveParameterStatus - remember parameter status sent by backend
908 pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
910 pgParameterStatus *pstatus;
911 pgParameterStatus *prev;
914 fprintf(conn->Pfdebug, "pqSaveParameterStatus: '%s' = '%s'\n",
918 * Forget any old information about the parameter
920 for (pstatus = conn->pstatus, prev = NULL;
922 prev = pstatus, pstatus = pstatus->next)
924 if (strcmp(pstatus->name, name) == 0)
927 prev->next = pstatus->next;
929 conn->pstatus = pstatus->next;
930 free(pstatus); /* frees name and value strings too */
936 * Store new info as a single malloc block
938 pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
939 strlen(name) +strlen(value) + 2);
944 ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
947 ptr += strlen(name) + 1;
948 pstatus->value = ptr;
950 pstatus->next = conn->pstatus;
951 conn->pstatus = pstatus;
955 * Special hacks: remember client_encoding and
956 * standard_conforming_strings, and convert server version to a numeric
957 * form. We keep the first two of these in static variables as well, so
958 * that PQescapeString and PQescapeBytea can behave somewhat sanely (at
959 * least in single-connection-using programs).
961 if (strcmp(name, "client_encoding") == 0)
963 conn->client_encoding = pg_char_to_encoding(value);
964 /* if we don't recognize the encoding name, fall back to SQL_ASCII */
965 if (conn->client_encoding < 0)
966 conn->client_encoding = PG_SQL_ASCII;
967 static_client_encoding = conn->client_encoding;
969 else if (strcmp(name, "standard_conforming_strings") == 0)
971 conn->std_strings = (strcmp(value, "on") == 0);
972 static_std_strings = conn->std_strings;
974 else if (strcmp(name, "server_version") == 0)
981 cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
984 conn->sversion = 0; /* unknown */
989 conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
997 * Add the received row to the current async result (conn->result).
998 * Returns 1 if OK, 0 if error occurred.
1000 * On error, *errmsgp can be set to an error string to be returned.
1001 * If it is left NULL, the error is presumed to be "out of memory".
1003 * In single-row mode, we create a new result holding just the current row,
1004 * stashing the previous result in conn->next_result so that it becomes
1005 * active again after pqPrepareAsyncResult(). This allows the result metadata
1006 * (column descriptions) to be carried forward to each result row.
1009 pqRowProcessor(PGconn *conn, const char **errmsgp)
1011 PGresult *res = conn->result;
1012 int nfields = res->numAttributes;
1013 const PGdataValue *columns = conn->rowBuf;
1018 * In single-row mode, make a new PGresult that will hold just this one
1019 * row; the original conn->result is left unchanged so that it can be used
1020 * again as the template for future rows.
1022 if (conn->singleRowMode)
1024 /* Copy everything that should be in the result at this point */
1025 res = PQcopyResult(res,
1026 PG_COPYRES_ATTRS | PG_COPYRES_EVENTS |
1027 PG_COPYRES_NOTICEHOOKS);
1033 * Basically we just allocate space in the PGresult for each field and
1034 * copy the data over.
1036 * Note: on malloc failure, we return 0 leaving *errmsgp still NULL, which
1037 * caller will take to mean "out of memory". This is preferable to trying
1038 * to set up such a message here, because evidently there's not enough
1039 * memory for gettext() to do anything.
1041 tup = (PGresAttValue *)
1042 pqResultAlloc(res, nfields * sizeof(PGresAttValue), TRUE);
1046 for (i = 0; i < nfields; i++)
1048 int clen = columns[i].len;
1053 tup[i].len = NULL_LEN;
1054 tup[i].value = res->null_field;
1058 bool isbinary = (res->attDescs[i].format != 0);
1061 val = (char *) pqResultAlloc(res, clen + 1, isbinary);
1065 /* copy and zero-terminate the data (even if it's binary) */
1066 memcpy(val, columns[i].value, clen);
1074 /* And add the tuple to the PGresult's tuple array */
1075 if (!pqAddTuple(res, tup))
1079 * Success. In single-row mode, make the result available to the client
1082 if (conn->singleRowMode)
1084 /* Change result status to special single-row value */
1085 res->resultStatus = PGRES_SINGLE_TUPLE;
1086 /* Stash old result for re-use later */
1087 conn->next_result = conn->result;
1089 /* And mark the result ready to return */
1090 conn->asyncStatus = PGASYNC_READY;
1096 /* release locally allocated PGresult, if we made one */
1097 if (res != conn->result)
1105 * Submit a query, but don't wait for it to finish
1107 * Returns: 1 if successfully submitted
1108 * 0 if error (conn->errorMessage is set)
1111 PQsendQuery(PGconn *conn, const char *query)
1113 if (!PQsendQueryStart(conn))
1116 /* check the argument */
1119 printfPQExpBuffer(&conn->errorMessage,
1120 libpq_gettext("command string is a null pointer\n"));
1124 /* construct the outgoing Query message */
1125 if (pqPutMsgStart('Q', false, conn) < 0 ||
1126 pqPuts(query, conn) < 0 ||
1127 pqPutMsgEnd(conn) < 0)
1129 pqHandleSendFailure(conn);
1133 /* remember we are using simple query protocol */
1134 conn->queryclass = PGQUERY_SIMPLE;
1136 /* and remember the query text too, if possible */
1137 /* if insufficient memory, last_query just winds up NULL */
1138 if (conn->last_query)
1139 free(conn->last_query);
1140 conn->last_query = strdup(query);
1143 * Give the data a push. In nonblock mode, don't complain if we're unable
1144 * to send it all; PQgetResult() will do any additional flushing needed.
1146 if (pqFlush(conn) < 0)
1148 pqHandleSendFailure(conn);
1152 /* OK, it's launched! */
1153 conn->asyncStatus = PGASYNC_BUSY;
1159 * Like PQsendQuery, but use protocol 3.0 so we can pass parameters
1162 PQsendQueryParams(PGconn *conn,
1163 const char *command,
1165 const Oid *paramTypes,
1166 const char *const * paramValues,
1167 const int *paramLengths,
1168 const int *paramFormats,
1171 if (!PQsendQueryStart(conn))
1174 /* check the arguments */
1177 printfPQExpBuffer(&conn->errorMessage,
1178 libpq_gettext("command string is a null pointer\n"));
1181 if (nParams < 0 || nParams > 65535)
1183 printfPQExpBuffer(&conn->errorMessage,
1184 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1188 return PQsendQueryGuts(conn,
1190 "", /* use unnamed statement */
1201 * Submit a Parse message, but don't wait for it to finish
1203 * Returns: 1 if successfully submitted
1204 * 0 if error (conn->errorMessage is set)
1207 PQsendPrepare(PGconn *conn,
1208 const char *stmtName, const char *query,
1209 int nParams, const Oid *paramTypes)
1211 if (!PQsendQueryStart(conn))
1214 /* check the arguments */
1217 printfPQExpBuffer(&conn->errorMessage,
1218 libpq_gettext("statement name is a null pointer\n"));
1223 printfPQExpBuffer(&conn->errorMessage,
1224 libpq_gettext("command string is a null pointer\n"));
1227 if (nParams < 0 || nParams > 65535)
1229 printfPQExpBuffer(&conn->errorMessage,
1230 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1234 /* This isn't gonna work on a 2.0 server */
1235 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1237 printfPQExpBuffer(&conn->errorMessage,
1238 libpq_gettext("function requires at least protocol version 3.0\n"));
1242 /* construct the Parse message */
1243 if (pqPutMsgStart('P', false, conn) < 0 ||
1244 pqPuts(stmtName, conn) < 0 ||
1245 pqPuts(query, conn) < 0)
1248 if (nParams > 0 && paramTypes)
1252 if (pqPutInt(nParams, 2, conn) < 0)
1254 for (i = 0; i < nParams; i++)
1256 if (pqPutInt(paramTypes[i], 4, conn) < 0)
1262 if (pqPutInt(0, 2, conn) < 0)
1265 if (pqPutMsgEnd(conn) < 0)
1268 /* construct the Sync message */
1269 if (pqPutMsgStart('S', false, conn) < 0 ||
1270 pqPutMsgEnd(conn) < 0)
1273 /* remember we are doing just a Parse */
1274 conn->queryclass = PGQUERY_PREPARE;
1276 /* and remember the query text too, if possible */
1277 /* if insufficient memory, last_query just winds up NULL */
1278 if (conn->last_query)
1279 free(conn->last_query);
1280 conn->last_query = strdup(query);
1283 * Give the data a push. In nonblock mode, don't complain if we're unable
1284 * to send it all; PQgetResult() will do any additional flushing needed.
1286 if (pqFlush(conn) < 0)
1289 /* OK, it's launched! */
1290 conn->asyncStatus = PGASYNC_BUSY;
1294 pqHandleSendFailure(conn);
1299 * PQsendQueryPrepared
1300 * Like PQsendQuery, but execute a previously prepared statement,
1301 * using protocol 3.0 so we can pass parameters
1304 PQsendQueryPrepared(PGconn *conn,
1305 const char *stmtName,
1307 const char *const * paramValues,
1308 const int *paramLengths,
1309 const int *paramFormats,
1312 if (!PQsendQueryStart(conn))
1315 /* check the arguments */
1318 printfPQExpBuffer(&conn->errorMessage,
1319 libpq_gettext("statement name is a null pointer\n"));
1322 if (nParams < 0 || nParams > 65535)
1324 printfPQExpBuffer(&conn->errorMessage,
1325 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1329 return PQsendQueryGuts(conn,
1330 NULL, /* no command to parse */
1333 NULL, /* no param types */
1341 * Common startup code for PQsendQuery and sibling routines
1344 PQsendQueryStart(PGconn *conn)
1349 /* clear the error string */
1350 resetPQExpBuffer(&conn->errorMessage);
1352 /* Don't try to send if we know there's no live connection. */
1353 if (conn->status != CONNECTION_OK)
1355 printfPQExpBuffer(&conn->errorMessage,
1356 libpq_gettext("no connection to the server\n"));
1359 /* Can't send while already busy, either. */
1360 if (conn->asyncStatus != PGASYNC_IDLE)
1362 printfPQExpBuffer(&conn->errorMessage,
1363 libpq_gettext("another command is already in progress\n"));
1367 /* initialize async result-accumulation state */
1368 conn->result = NULL;
1369 conn->next_result = NULL;
1371 /* reset single-row processing mode */
1372 conn->singleRowMode = false;
1374 /* ready to send command message */
1380 * Common code for protocol-3.0 query sending
1381 * PQsendQueryStart should be done already
1383 * command may be NULL to indicate we use an already-prepared statement
1386 PQsendQueryGuts(PGconn *conn,
1387 const char *command,
1388 const char *stmtName,
1390 const Oid *paramTypes,
1391 const char *const * paramValues,
1392 const int *paramLengths,
1393 const int *paramFormats,
1398 /* This isn't gonna work on a 2.0 server */
1399 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1401 printfPQExpBuffer(&conn->errorMessage,
1402 libpq_gettext("function requires at least protocol version 3.0\n"));
1407 * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync,
1408 * using specified statement name and the unnamed portal.
1413 /* construct the Parse message */
1414 if (pqPutMsgStart('P', false, conn) < 0 ||
1415 pqPuts(stmtName, conn) < 0 ||
1416 pqPuts(command, conn) < 0)
1418 if (nParams > 0 && paramTypes)
1420 if (pqPutInt(nParams, 2, conn) < 0)
1422 for (i = 0; i < nParams; i++)
1424 if (pqPutInt(paramTypes[i], 4, conn) < 0)
1430 if (pqPutInt(0, 2, conn) < 0)
1433 if (pqPutMsgEnd(conn) < 0)
1437 /* Construct the Bind message */
1438 if (pqPutMsgStart('B', false, conn) < 0 ||
1439 pqPuts("", conn) < 0 ||
1440 pqPuts(stmtName, conn) < 0)
1443 /* Send parameter formats */
1444 if (nParams > 0 && paramFormats)
1446 if (pqPutInt(nParams, 2, conn) < 0)
1448 for (i = 0; i < nParams; i++)
1450 if (pqPutInt(paramFormats[i], 2, conn) < 0)
1456 if (pqPutInt(0, 2, conn) < 0)
1460 if (pqPutInt(nParams, 2, conn) < 0)
1463 /* Send parameters */
1464 for (i = 0; i < nParams; i++)
1466 if (paramValues && paramValues[i])
1470 if (paramFormats && paramFormats[i] != 0)
1472 /* binary parameter */
1474 nbytes = paramLengths[i];
1477 printfPQExpBuffer(&conn->errorMessage,
1478 libpq_gettext("length must be given for binary parameter\n"));
1484 /* text parameter, do not use paramLengths */
1485 nbytes = strlen(paramValues[i]);
1487 if (pqPutInt(nbytes, 4, conn) < 0 ||
1488 pqPutnchar(paramValues[i], nbytes, conn) < 0)
1493 /* take the param as NULL */
1494 if (pqPutInt(-1, 4, conn) < 0)
1498 if (pqPutInt(1, 2, conn) < 0 ||
1499 pqPutInt(resultFormat, 2, conn))
1501 if (pqPutMsgEnd(conn) < 0)
1504 /* construct the Describe Portal message */
1505 if (pqPutMsgStart('D', false, conn) < 0 ||
1506 pqPutc('P', conn) < 0 ||
1507 pqPuts("", conn) < 0 ||
1508 pqPutMsgEnd(conn) < 0)
1511 /* construct the Execute message */
1512 if (pqPutMsgStart('E', false, conn) < 0 ||
1513 pqPuts("", conn) < 0 ||
1514 pqPutInt(0, 4, conn) < 0 ||
1515 pqPutMsgEnd(conn) < 0)
1518 /* construct the Sync message */
1519 if (pqPutMsgStart('S', false, conn) < 0 ||
1520 pqPutMsgEnd(conn) < 0)
1523 /* remember we are using extended query protocol */
1524 conn->queryclass = PGQUERY_EXTENDED;
1526 /* and remember the query text too, if possible */
1527 /* if insufficient memory, last_query just winds up NULL */
1528 if (conn->last_query)
1529 free(conn->last_query);
1531 conn->last_query = strdup(command);
1533 conn->last_query = NULL;
1536 * Give the data a push. In nonblock mode, don't complain if we're unable
1537 * to send it all; PQgetResult() will do any additional flushing needed.
1539 if (pqFlush(conn) < 0)
1542 /* OK, it's launched! */
1543 conn->asyncStatus = PGASYNC_BUSY;
1547 pqHandleSendFailure(conn);
1552 * pqHandleSendFailure: try to clean up after failure to send command.
1554 * Primarily, what we want to accomplish here is to process an async
1555 * NOTICE message that the backend might have sent just before it died.
1557 * NOTE: this routine should only be called in PGASYNC_IDLE state.
1560 pqHandleSendFailure(PGconn *conn)
1563 * Accept any available input data, ignoring errors. Note that if
1564 * pqReadData decides the backend has closed the channel, it will close
1565 * our side of the socket --- that's just what we want here.
1567 while (pqReadData(conn) > 0)
1568 /* loop until no more data readable */ ;
1571 * Parse any available input messages. Since we are in PGASYNC_IDLE
1572 * state, only NOTICE and NOTIFY messages will be eaten.
1578 * Select row-by-row processing mode
1581 PQsetSingleRowMode(PGconn *conn)
1584 * Only allow setting the flag when we have launched a query and not yet
1585 * received any results.
1589 if (conn->asyncStatus != PGASYNC_BUSY)
1591 if (conn->queryclass != PGQUERY_SIMPLE &&
1592 conn->queryclass != PGQUERY_EXTENDED)
1598 conn->singleRowMode = true;
1603 * Consume any available input from the backend
1604 * 0 return: some kind of trouble
1605 * 1 return: no problem
1608 PQconsumeInput(PGconn *conn)
1614 * for non-blocking connections try to flush the send-queue, otherwise we
1615 * may never get a response for something that may not have already been
1616 * sent because it's in our write buffer!
1618 if (pqIsnonblocking(conn))
1620 if (pqFlush(conn) < 0)
1625 * Load more data, if available. We do this no matter what state we are
1626 * in, since we are probably getting called because the application wants
1627 * to get rid of a read-select condition. Note that we will NOT block
1628 * waiting for more input.
1630 if (pqReadData(conn) < 0)
1633 /* Parsing of the data waits till later. */
1639 * parseInput: if appropriate, parse input data from backend
1640 * until input is exhausted or a stopping state is reached.
1641 * Note that this function will NOT attempt to read more data from the backend.
1644 parseInput(PGconn *conn)
1646 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1647 pqParseInput3(conn);
1649 pqParseInput2(conn);
1654 * Return TRUE if PQgetResult would block waiting for input.
1658 PQisBusy(PGconn *conn)
1663 /* Parse any available data, if our state permits. */
1666 /* PQgetResult will return immediately in all states except BUSY. */
1667 return conn->asyncStatus == PGASYNC_BUSY;
1673 * Get the next PGresult produced by a query. Returns NULL if no
1674 * query work remains or an error has occurred (e.g. out of
1679 PQgetResult(PGconn *conn)
1686 /* Parse any available data, if our state permits. */
1689 /* If not ready to return something, block until we are. */
1690 while (conn->asyncStatus == PGASYNC_BUSY)
1695 * If data remains unsent, send it. Else we might be waiting for the
1696 * result of a command the backend hasn't even got yet.
1698 while ((flushResult = pqFlush(conn)) > 0)
1700 if (pqWait(FALSE, TRUE, conn))
1707 /* Wait for some more data, and load it. */
1709 pqWait(TRUE, FALSE, conn) ||
1710 pqReadData(conn) < 0)
1713 * conn->errorMessage has been set by pqWait or pqReadData. We
1714 * want to append it to any already-received error message.
1716 pqSaveErrorResult(conn);
1717 conn->asyncStatus = PGASYNC_IDLE;
1718 return pqPrepareAsyncResult(conn);
1725 /* Return the appropriate thing. */
1726 switch (conn->asyncStatus)
1729 res = NULL; /* query is complete */
1732 res = pqPrepareAsyncResult(conn);
1733 /* Set the state back to BUSY, allowing parsing to proceed. */
1734 conn->asyncStatus = PGASYNC_BUSY;
1736 case PGASYNC_COPY_IN:
1737 if (conn->result && conn->result->resultStatus == PGRES_COPY_IN)
1738 res = pqPrepareAsyncResult(conn);
1740 res = PQmakeEmptyPGresult(conn, PGRES_COPY_IN);
1742 case PGASYNC_COPY_OUT:
1743 if (conn->result && conn->result->resultStatus == PGRES_COPY_OUT)
1744 res = pqPrepareAsyncResult(conn);
1746 res = PQmakeEmptyPGresult(conn, PGRES_COPY_OUT);
1748 case PGASYNC_COPY_BOTH:
1749 if (conn->result && conn->result->resultStatus == PGRES_COPY_BOTH)
1750 res = pqPrepareAsyncResult(conn);
1752 res = PQmakeEmptyPGresult(conn, PGRES_COPY_BOTH);
1755 printfPQExpBuffer(&conn->errorMessage,
1756 libpq_gettext("unexpected asyncStatus: %d\n"),
1757 (int) conn->asyncStatus);
1758 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1766 for (i = 0; i < res->nEvents; i++)
1768 PGEventResultCreate evt;
1772 if (!res->events[i].proc(PGEVT_RESULTCREATE, &evt,
1773 res->events[i].passThrough))
1775 printfPQExpBuffer(&conn->errorMessage,
1776 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_RESULTCREATE event\n"),
1777 res->events[i].name);
1778 pqSetResultError(res, conn->errorMessage.data);
1779 res->resultStatus = PGRES_FATAL_ERROR;
1782 res->events[i].resultInitialized = TRUE;
1792 * send a query to the backend and package up the result in a PGresult
1794 * If the query was not even sent, return NULL; conn->errorMessage is set to
1795 * a relevant message.
1796 * If the query was sent, a new PGresult is returned (which could indicate
1797 * either success or failure).
1798 * The user is responsible for freeing the PGresult via PQclear()
1799 * when done with it.
1802 PQexec(PGconn *conn, const char *query)
1804 if (!PQexecStart(conn))
1806 if (!PQsendQuery(conn, query))
1808 return PQexecFinish(conn);
1813 * Like PQexec, but use protocol 3.0 so we can pass parameters
1816 PQexecParams(PGconn *conn,
1817 const char *command,
1819 const Oid *paramTypes,
1820 const char *const * paramValues,
1821 const int *paramLengths,
1822 const int *paramFormats,
1825 if (!PQexecStart(conn))
1827 if (!PQsendQueryParams(conn, command,
1828 nParams, paramTypes, paramValues, paramLengths,
1829 paramFormats, resultFormat))
1831 return PQexecFinish(conn);
1836 * Creates a prepared statement by issuing a v3.0 parse message.
1838 * If the query was not even sent, return NULL; conn->errorMessage is set to
1839 * a relevant message.
1840 * If the query was sent, a new PGresult is returned (which could indicate
1841 * either success or failure).
1842 * The user is responsible for freeing the PGresult via PQclear()
1843 * when done with it.
1846 PQprepare(PGconn *conn,
1847 const char *stmtName, const char *query,
1848 int nParams, const Oid *paramTypes)
1850 if (!PQexecStart(conn))
1852 if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
1854 return PQexecFinish(conn);
1859 * Like PQexec, but execute a previously prepared statement,
1860 * using protocol 3.0 so we can pass parameters
1863 PQexecPrepared(PGconn *conn,
1864 const char *stmtName,
1866 const char *const * paramValues,
1867 const int *paramLengths,
1868 const int *paramFormats,
1871 if (!PQexecStart(conn))
1873 if (!PQsendQueryPrepared(conn, stmtName,
1874 nParams, paramValues, paramLengths,
1875 paramFormats, resultFormat))
1877 return PQexecFinish(conn);
1881 * Common code for PQexec and sibling routines: prepare to send command
1884 PQexecStart(PGconn *conn)
1892 * Silently discard any prior query result that application didn't eat.
1893 * This is probably poor design, but it's here for backward compatibility.
1895 while ((result = PQgetResult(conn)) != NULL)
1897 ExecStatusType resultStatus = result->resultStatus;
1899 PQclear(result); /* only need its status */
1900 if (resultStatus == PGRES_COPY_IN)
1902 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1904 /* In protocol 3, we can get out of a COPY IN state */
1905 if (PQputCopyEnd(conn,
1906 libpq_gettext("COPY terminated by new PQexec")) < 0)
1908 /* keep waiting to swallow the copy's failure message */
1912 /* In older protocols we have to punt */
1913 printfPQExpBuffer(&conn->errorMessage,
1914 libpq_gettext("COPY IN state must be terminated first\n"));
1918 else if (resultStatus == PGRES_COPY_OUT)
1920 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1923 * In protocol 3, we can get out of a COPY OUT state: we just
1924 * switch back to BUSY and allow the remaining COPY data to be
1925 * dropped on the floor.
1927 conn->asyncStatus = PGASYNC_BUSY;
1928 /* keep waiting to swallow the copy's completion message */
1932 /* In older protocols we have to punt */
1933 printfPQExpBuffer(&conn->errorMessage,
1934 libpq_gettext("COPY OUT state must be terminated first\n"));
1938 else if (resultStatus == PGRES_COPY_BOTH)
1940 /* We don't allow PQexec during COPY BOTH */
1941 printfPQExpBuffer(&conn->errorMessage,
1942 libpq_gettext("PQexec not allowed during COPY BOTH\n"));
1945 /* check for loss of connection, too */
1946 if (conn->status == CONNECTION_BAD)
1950 /* OK to send a command */
1955 * Common code for PQexec and sibling routines: wait for command result
1958 PQexecFinish(PGconn *conn)
1961 PGresult *lastResult;
1964 * For backwards compatibility, return the last result if there are more
1965 * than one --- but merge error messages if we get more than one error
1968 * We have to stop if we see copy in/out/both, however. We will resume
1969 * parsing after application performs the data transfer.
1971 * Also stop if the connection is lost (else we'll loop infinitely).
1974 while ((result = PQgetResult(conn)) != NULL)
1978 if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
1979 result->resultStatus == PGRES_FATAL_ERROR)
1981 pqCatenateResultError(lastResult, result->errMsg);
1983 result = lastResult;
1986 * Make sure PQerrorMessage agrees with concatenated result
1988 resetPQExpBuffer(&conn->errorMessage);
1989 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
1992 PQclear(lastResult);
1994 lastResult = result;
1995 if (result->resultStatus == PGRES_COPY_IN ||
1996 result->resultStatus == PGRES_COPY_OUT ||
1997 result->resultStatus == PGRES_COPY_BOTH ||
1998 conn->status == CONNECTION_BAD)
2006 * PQdescribePrepared
2007 * Obtain information about a previously prepared statement
2009 * If the query was not even sent, return NULL; conn->errorMessage is set to
2010 * a relevant message.
2011 * If the query was sent, a new PGresult is returned (which could indicate
2012 * either success or failure). On success, the PGresult contains status
2013 * PGRES_COMMAND_OK, and its parameter and column-heading fields describe
2014 * the statement's inputs and outputs respectively.
2015 * The user is responsible for freeing the PGresult via PQclear()
2016 * when done with it.
2019 PQdescribePrepared(PGconn *conn, const char *stmt)
2021 if (!PQexecStart(conn))
2023 if (!PQsendDescribe(conn, 'S', stmt))
2025 return PQexecFinish(conn);
2030 * Obtain information about a previously created portal
2032 * This is much like PQdescribePrepared, except that no parameter info is
2033 * returned. Note that at the moment, libpq doesn't really expose portals
2034 * to the client; but this can be used with a portal created by a SQL
2035 * DECLARE CURSOR command.
2038 PQdescribePortal(PGconn *conn, const char *portal)
2040 if (!PQexecStart(conn))
2042 if (!PQsendDescribe(conn, 'P', portal))
2044 return PQexecFinish(conn);
2048 * PQsendDescribePrepared
2049 * Submit a Describe Statement command, but don't wait for it to finish
2051 * Returns: 1 if successfully submitted
2052 * 0 if error (conn->errorMessage is set)
2055 PQsendDescribePrepared(PGconn *conn, const char *stmt)
2057 return PQsendDescribe(conn, 'S', stmt);
2061 * PQsendDescribePortal
2062 * Submit a Describe Portal command, but don't wait for it to finish
2064 * Returns: 1 if successfully submitted
2065 * 0 if error (conn->errorMessage is set)
2068 PQsendDescribePortal(PGconn *conn, const char *portal)
2070 return PQsendDescribe(conn, 'P', portal);
2075 * Common code to send a Describe command
2077 * Available options for desc_type are
2078 * 'S' to describe a prepared statement; or
2079 * 'P' to describe a portal.
2080 * Returns 1 on success and 0 on failure.
2083 PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
2085 /* Treat null desc_target as empty string */
2089 if (!PQsendQueryStart(conn))
2092 /* This isn't gonna work on a 2.0 server */
2093 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2095 printfPQExpBuffer(&conn->errorMessage,
2096 libpq_gettext("function requires at least protocol version 3.0\n"));
2100 /* construct the Describe message */
2101 if (pqPutMsgStart('D', false, conn) < 0 ||
2102 pqPutc(desc_type, conn) < 0 ||
2103 pqPuts(desc_target, conn) < 0 ||
2104 pqPutMsgEnd(conn) < 0)
2107 /* construct the Sync message */
2108 if (pqPutMsgStart('S', false, conn) < 0 ||
2109 pqPutMsgEnd(conn) < 0)
2112 /* remember we are doing a Describe */
2113 conn->queryclass = PGQUERY_DESCRIBE;
2115 /* reset last-query string (not relevant now) */
2116 if (conn->last_query)
2118 free(conn->last_query);
2119 conn->last_query = NULL;
2123 * Give the data a push. In nonblock mode, don't complain if we're unable
2124 * to send it all; PQgetResult() will do any additional flushing needed.
2126 if (pqFlush(conn) < 0)
2129 /* OK, it's launched! */
2130 conn->asyncStatus = PGASYNC_BUSY;
2134 pqHandleSendFailure(conn);
2140 * returns a PGnotify* structure of the latest async notification
2141 * that has not yet been handled
2143 * returns NULL, if there is currently
2144 * no unhandled async notification from the backend
2146 * the CALLER is responsible for FREE'ing the structure returned
2149 PQnotifies(PGconn *conn)
2156 /* Parse any available data to see if we can extract NOTIFY messages. */
2159 event = conn->notifyHead;
2162 conn->notifyHead = event->next;
2163 if (!conn->notifyHead)
2164 conn->notifyTail = NULL;
2165 event->next = NULL; /* don't let app see the internal state */
2171 * PQputCopyData - send some data to the backend during COPY IN or COPY BOTH
2173 * Returns 1 if successful, 0 if data could not be sent (only possible
2174 * in nonblock mode), or -1 if an error occurs.
2177 PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
2181 if (conn->asyncStatus != PGASYNC_COPY_IN &&
2182 conn->asyncStatus != PGASYNC_COPY_BOTH)
2184 printfPQExpBuffer(&conn->errorMessage,
2185 libpq_gettext("no COPY in progress\n"));
2190 * Process any NOTICE or NOTIFY messages that might be pending in the
2191 * input buffer. Since the server might generate many notices during the
2192 * COPY, we want to clean those out reasonably promptly to prevent
2193 * indefinite expansion of the input buffer. (Note: the actual read of
2194 * input data into the input buffer happens down inside pqSendSome, but
2195 * it's not authorized to get rid of the data again.)
2202 * Try to flush any previously sent data in preference to growing the
2203 * output buffer. If we can't enlarge the buffer enough to hold the
2204 * data, return 0 in the nonblock case, else hard error. (For
2205 * simplicity, always assume 5 bytes of overhead even in protocol 2.0
2208 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2210 if (pqFlush(conn) < 0)
2212 if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2214 return pqIsnonblocking(conn) ? 0 : -1;
2216 /* Send the data (too simple to delegate to fe-protocol files) */
2217 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2219 if (pqPutMsgStart('d', false, conn) < 0 ||
2220 pqPutnchar(buffer, nbytes, conn) < 0 ||
2221 pqPutMsgEnd(conn) < 0)
2226 if (pqPutMsgStart(0, false, conn) < 0 ||
2227 pqPutnchar(buffer, nbytes, conn) < 0 ||
2228 pqPutMsgEnd(conn) < 0)
2236 * PQputCopyEnd - send EOF indication to the backend during COPY IN
2238 * After calling this, use PQgetResult() to check command completion status.
2240 * Returns 1 if successful, 0 if data could not be sent (only possible
2241 * in nonblock mode), or -1 if an error occurs.
2244 PQputCopyEnd(PGconn *conn, const char *errormsg)
2248 if (conn->asyncStatus != PGASYNC_COPY_IN &&
2249 conn->asyncStatus != PGASYNC_COPY_BOTH)
2251 printfPQExpBuffer(&conn->errorMessage,
2252 libpq_gettext("no COPY in progress\n"));
2257 * Send the COPY END indicator. This is simple enough that we don't
2258 * bother delegating it to the fe-protocol files.
2260 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2264 /* Send COPY FAIL */
2265 if (pqPutMsgStart('f', false, conn) < 0 ||
2266 pqPuts(errormsg, conn) < 0 ||
2267 pqPutMsgEnd(conn) < 0)
2272 /* Send COPY DONE */
2273 if (pqPutMsgStart('c', false, conn) < 0 ||
2274 pqPutMsgEnd(conn) < 0)
2279 * If we sent the COPY command in extended-query mode, we must issue a
2282 if (conn->queryclass != PGQUERY_SIMPLE)
2284 if (pqPutMsgStart('S', false, conn) < 0 ||
2285 pqPutMsgEnd(conn) < 0)
2293 /* Ooops, no way to do this in 2.0 */
2294 printfPQExpBuffer(&conn->errorMessage,
2295 libpq_gettext("function requires at least protocol version 3.0\n"));
2300 /* Send old-style end-of-data marker */
2301 if (pqPutMsgStart(0, false, conn) < 0 ||
2302 pqPutnchar("\\.\n", 3, conn) < 0 ||
2303 pqPutMsgEnd(conn) < 0)
2308 /* Return to active duty */
2309 if (conn->asyncStatus == PGASYNC_COPY_BOTH)
2310 conn->asyncStatus = PGASYNC_COPY_OUT;
2312 conn->asyncStatus = PGASYNC_BUSY;
2313 resetPQExpBuffer(&conn->errorMessage);
2315 /* Try to flush data */
2316 if (pqFlush(conn) < 0)
2323 * PQgetCopyData - read a row of data from the backend during COPY OUT
2326 * If successful, sets *buffer to point to a malloc'd row of data, and
2327 * returns row length (always > 0) as result.
2328 * Returns 0 if no row available yet (only possible if async is true),
2329 * -1 if end of copy (consult PQgetResult), or -2 if error (consult
2333 PQgetCopyData(PGconn *conn, char **buffer, int async)
2335 *buffer = NULL; /* for all failure cases */
2338 if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2339 conn->asyncStatus != PGASYNC_COPY_BOTH)
2341 printfPQExpBuffer(&conn->errorMessage,
2342 libpq_gettext("no COPY in progress\n"));
2345 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2346 return pqGetCopyData3(conn, buffer, async);
2348 return pqGetCopyData2(conn, buffer, async);
2352 * PQgetline - gets a newline-terminated string from the backend.
2354 * Chiefly here so that applications can use "COPY <rel> to stdout"
2355 * and read the output string. Returns a null-terminated string in s.
2357 * XXX this routine is now deprecated, because it can't handle binary data.
2358 * If called during a COPY BINARY we return EOF.
2360 * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
2361 * the terminating \n (like gets(3)).
2363 * CAUTION: the caller is responsible for detecting the end-of-copy signal
2364 * (a line containing just "\.") when using this routine.
2367 * EOF if error (eg, invalid arguments are given)
2368 * 0 if EOL is reached (i.e., \n has been read)
2369 * (this is required for backward-compatibility -- this
2370 * routine used to always return EOF or 0, assuming that
2371 * the line ended within maxlen bytes.)
2372 * 1 in other cases (i.e., the buffer was filled before \n is reached)
2375 PQgetline(PGconn *conn, char *s, int maxlen)
2377 if (!s || maxlen <= 0)
2380 /* maxlen must be at least 3 to hold the \. terminator! */
2387 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2388 return pqGetline3(conn, s, maxlen);
2390 return pqGetline2(conn, s, maxlen);
2394 * PQgetlineAsync - gets a COPY data row without blocking.
2396 * This routine is for applications that want to do "COPY <rel> to stdout"
2397 * asynchronously, that is without blocking. Having issued the COPY command
2398 * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
2399 * and this routine until the end-of-data signal is detected. Unlike
2400 * PQgetline, this routine takes responsibility for detecting end-of-data.
2402 * On each call, PQgetlineAsync will return data if a complete data row
2403 * is available in libpq's input buffer. Otherwise, no data is returned
2404 * until the rest of the row arrives.
2406 * If -1 is returned, the end-of-data signal has been recognized (and removed
2407 * from libpq's input buffer). The caller *must* next call PQendcopy and
2408 * then return to normal processing.
2411 * -1 if the end-of-copy-data marker has been recognized
2412 * 0 if no data is available
2413 * >0 the number of bytes returned.
2415 * The data returned will not extend beyond a data-row boundary. If possible
2416 * a whole row will be returned at one time. But if the buffer offered by
2417 * the caller is too small to hold a row sent by the backend, then a partial
2418 * data row will be returned. In text mode this can be detected by testing
2419 * whether the last returned byte is '\n' or not.
2421 * The returned data is *not* null-terminated.
2425 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
2430 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2431 return pqGetlineAsync3(conn, buffer, bufsize);
2433 return pqGetlineAsync2(conn, buffer, bufsize);
2437 * PQputline -- sends a string to the backend during COPY IN.
2438 * Returns 0 if OK, EOF if not.
2440 * This is deprecated primarily because the return convention doesn't allow
2441 * caller to tell the difference between a hard error and a nonblock-mode
2445 PQputline(PGconn *conn, const char *s)
2447 return PQputnbytes(conn, s, strlen(s));
2451 * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
2452 * Returns 0 if OK, EOF if not.
2455 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
2457 if (PQputCopyData(conn, buffer, nbytes) > 0)
2465 * After completing the data transfer portion of a copy in/out,
2466 * the application must call this routine to finish the command protocol.
2468 * When using protocol 3.0 this is deprecated; it's cleaner to use PQgetResult
2469 * to get the transfer status. Note however that when using 2.0 protocol,
2470 * recovering from a copy failure often requires a PQreset. PQendcopy will
2471 * take care of that, PQgetResult won't.
2478 PQendcopy(PGconn *conn)
2483 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2484 return pqEndcopy3(conn);
2486 return pqEndcopy2(conn);
2491 * PQfn - Send a function call to the POSTGRES backend.
2493 * conn : backend connection
2494 * fnid : function id
2495 * result_buf : pointer to result buffer (&int if integer)
2496 * result_len : length of return value.
2497 * actual_result_len: actual length returned. (differs from result_len
2498 * for varlena structures.)
2499 * result_type : If the result is an integer, this must be 1,
2500 * otherwise this should be 0
2501 * args : pointer to an array of function arguments.
2502 * (each has length, if integer, and value/pointer)
2503 * nargs : # of arguments in args array.
2506 * PGresult with status = PGRES_COMMAND_OK if successful.
2507 * *actual_result_len is > 0 if there is a return value, 0 if not.
2508 * PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
2509 * NULL on communications failure. conn->errorMessage will be set.
2517 int *actual_result_len,
2519 const PQArgBlock *args,
2522 *actual_result_len = 0;
2527 /* clear the error string */
2528 resetPQExpBuffer(&conn->errorMessage);
2530 if (conn->sock < 0 || conn->asyncStatus != PGASYNC_IDLE ||
2531 conn->result != NULL)
2533 printfPQExpBuffer(&conn->errorMessage,
2534 libpq_gettext("connection in wrong state\n"));
2538 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2539 return pqFunctionCall3(conn, fnid,
2540 result_buf, actual_result_len,
2544 return pqFunctionCall2(conn, fnid,
2545 result_buf, actual_result_len,
2551 /* ====== accessor funcs for PGresult ======== */
2554 PQresultStatus(const PGresult *res)
2557 return PGRES_FATAL_ERROR;
2558 return res->resultStatus;
2562 PQresStatus(ExecStatusType status)
2564 if ((unsigned int) status >= sizeof pgresStatus / sizeof pgresStatus[0])
2565 return libpq_gettext("invalid ExecStatusType code");
2566 return pgresStatus[status];
2570 PQresultErrorMessage(const PGresult *res)
2572 if (!res || !res->errMsg)
2578 PQresultErrorField(const PGresult *res, int fieldcode)
2580 PGMessageField *pfield;
2584 for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
2586 if (pfield->code == fieldcode)
2587 return pfield->contents;
2593 PQntuples(const PGresult *res)
2601 PQnfields(const PGresult *res)
2605 return res->numAttributes;
2609 PQbinaryTuples(const PGresult *res)
2617 * Helper routines to range-check field numbers and tuple numbers.
2618 * Return TRUE if OK, FALSE if not
2622 check_field_number(const PGresult *res, int field_num)
2625 return FALSE; /* no way to display error message... */
2626 if (field_num < 0 || field_num >= res->numAttributes)
2628 pqInternalNotice(&res->noticeHooks,
2629 "column number %d is out of range 0..%d",
2630 field_num, res->numAttributes - 1);
2637 check_tuple_field_number(const PGresult *res,
2638 int tup_num, int field_num)
2641 return FALSE; /* no way to display error message... */
2642 if (tup_num < 0 || tup_num >= res->ntups)
2644 pqInternalNotice(&res->noticeHooks,
2645 "row number %d is out of range 0..%d",
2646 tup_num, res->ntups - 1);
2649 if (field_num < 0 || field_num >= res->numAttributes)
2651 pqInternalNotice(&res->noticeHooks,
2652 "column number %d is out of range 0..%d",
2653 field_num, res->numAttributes - 1);
2660 check_param_number(const PGresult *res, int param_num)
2663 return FALSE; /* no way to display error message... */
2664 if (param_num < 0 || param_num >= res->numParameters)
2666 pqInternalNotice(&res->noticeHooks,
2667 "parameter number %d is out of range 0..%d",
2668 param_num, res->numParameters - 1);
2676 * returns NULL if the field_num is invalid
2679 PQfname(const PGresult *res, int field_num)
2681 if (!check_field_number(res, field_num))
2684 return res->attDescs[field_num].name;
2690 * PQfnumber: find column number given column name
2692 * The column name is parsed as if it were in a SQL statement, including
2693 * case-folding and double-quote processing. But note a possible gotcha:
2694 * downcasing in the frontend might follow different locale rules than
2695 * downcasing in the backend...
2697 * Returns -1 if no match. In the present backend it is also possible
2698 * to have multiple matches, in which case the first one is found.
2701 PQfnumber(const PGresult *res, const char *field_name)
2713 * Note: it is correct to reject a zero-length input string; the proper
2714 * input to match a zero-length field name would be "".
2716 if (field_name == NULL ||
2717 field_name[0] == '\0' ||
2718 res->attDescs == NULL)
2722 * Note: this code will not reject partially quoted strings, eg
2723 * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
2726 field_case = strdup(field_name);
2727 if (field_case == NULL)
2728 return -1; /* grotty */
2732 for (iptr = field_case; *iptr; iptr++)
2742 /* doubled quotes become a single quote */
2756 c = pg_tolower((unsigned char) c);
2762 for (i = 0; i < res->numAttributes; i++)
2764 if (strcmp(field_case, res->attDescs[i].name) == 0)
2775 PQftable(const PGresult *res, int field_num)
2777 if (!check_field_number(res, field_num))
2780 return res->attDescs[field_num].tableid;
2786 PQftablecol(const PGresult *res, int field_num)
2788 if (!check_field_number(res, field_num))
2791 return res->attDescs[field_num].columnid;
2797 PQfformat(const PGresult *res, int field_num)
2799 if (!check_field_number(res, field_num))
2802 return res->attDescs[field_num].format;
2808 PQftype(const PGresult *res, int field_num)
2810 if (!check_field_number(res, field_num))
2813 return res->attDescs[field_num].typid;
2819 PQfsize(const PGresult *res, int field_num)
2821 if (!check_field_number(res, field_num))
2824 return res->attDescs[field_num].typlen;
2830 PQfmod(const PGresult *res, int field_num)
2832 if (!check_field_number(res, field_num))
2835 return res->attDescs[field_num].atttypmod;
2841 PQcmdStatus(PGresult *res)
2845 return res->cmdStatus;
2850 * if the last command was an INSERT, return the oid string
2854 PQoidStatus(const PGresult *res)
2857 * This must be enough to hold the result. Don't laugh, this is better
2858 * than what this function used to do.
2860 static char buf[24];
2864 if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2867 len = strspn(res->cmdStatus + 7, "0123456789");
2870 strncpy(buf, res->cmdStatus + 7, len);
2878 * a perhaps preferable form of the above which just returns
2882 PQoidValue(const PGresult *res)
2884 char *endptr = NULL;
2885 unsigned long result;
2889 strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
2890 res->cmdStatus[7] < '0' ||
2891 res->cmdStatus[7] > '9')
2894 result = strtoul(res->cmdStatus + 7, &endptr, 10);
2896 if (!endptr || (*endptr != ' ' && *endptr != '\0'))
2899 return (Oid) result;
2905 * If the last command was INSERT/UPDATE/DELETE/MOVE/FETCH/COPY, return
2906 * a string containing the number of inserted/affected tuples. If not,
2909 * XXX: this should probably return an int
2912 PQcmdTuples(PGresult *res)
2920 if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
2922 p = res->cmdStatus + 7;
2923 /* INSERT: skip oid and space */
2924 while (*p && *p != ' ')
2927 goto interpret_error; /* no space? */
2930 else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
2931 strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
2932 strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
2933 p = res->cmdStatus + 7;
2934 else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
2935 p = res->cmdStatus + 6;
2936 else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
2937 strncmp(res->cmdStatus, "COPY ", 5) == 0)
2938 p = res->cmdStatus + 5;
2942 /* check that we have an integer (at least one digit, nothing else) */
2943 for (c = p; *c; c++)
2945 if (!isdigit((unsigned char) *c))
2946 goto interpret_error;
2949 goto interpret_error;
2954 pqInternalNotice(&res->noticeHooks,
2955 "could not interpret result from server: %s",
2962 * return the value of field 'field_num' of row 'tup_num'
2965 PQgetvalue(const PGresult *res, int tup_num, int field_num)
2967 if (!check_tuple_field_number(res, tup_num, field_num))
2969 return res->tuples[tup_num][field_num].value;
2973 * returns the actual length of a field value in bytes.
2976 PQgetlength(const PGresult *res, int tup_num, int field_num)
2978 if (!check_tuple_field_number(res, tup_num, field_num))
2980 if (res->tuples[tup_num][field_num].len != NULL_LEN)
2981 return res->tuples[tup_num][field_num].len;
2987 * returns the null status of a field value.
2990 PQgetisnull(const PGresult *res, int tup_num, int field_num)
2992 if (!check_tuple_field_number(res, tup_num, field_num))
2993 return 1; /* pretend it is null */
2994 if (res->tuples[tup_num][field_num].len == NULL_LEN)
3001 * returns the number of input parameters of a prepared statement.
3004 PQnparams(const PGresult *res)
3008 return res->numParameters;
3012 * returns type Oid of the specified statement parameter.
3015 PQparamtype(const PGresult *res, int param_num)
3017 if (!check_param_number(res, param_num))
3019 if (res->paramDescs)
3020 return res->paramDescs[param_num].typid;
3026 /* PQsetnonblocking:
3027 * sets the PGconn's database connection non-blocking if the arg is TRUE
3028 * or makes it blocking if the arg is FALSE, this will not protect
3029 * you from PQexec(), you'll only be safe when using the non-blocking API.
3030 * Needs to be called only on a connected database connection.
3033 PQsetnonblocking(PGconn *conn, int arg)
3037 if (!conn || conn->status == CONNECTION_BAD)
3040 barg = (arg ? TRUE : FALSE);
3042 /* early out if the socket is already in the state requested */
3043 if (barg == conn->nonblocking)
3047 * to guarantee constancy for flushing/query/result-polling behavior we
3048 * need to flush the send queue at this point in order to guarantee proper
3049 * behavior. this is ok because either they are making a transition _from_
3050 * or _to_ blocking mode, either way we can block them.
3052 /* if we are going from blocking to non-blocking flush here */
3056 conn->nonblocking = barg;
3062 * return the blocking status of the database connection
3063 * TRUE == nonblocking, FALSE == blocking
3066 PQisnonblocking(const PGconn *conn)
3068 return pqIsnonblocking(conn);
3071 /* libpq is thread-safe? */
3073 PQisthreadsafe(void)
3075 #ifdef ENABLE_THREAD_SAFETY
3083 /* try to force data out, really only useful for non-blocking users */
3085 PQflush(PGconn *conn)
3087 return pqFlush(conn);
3092 * PQfreemem - safely frees memory allocated
3094 * Needed mostly by Win32, unless multithreaded DLL (/MD in VC6)
3095 * Used for freeing memory from PQescapeByte()a/PQunescapeBytea()
3098 PQfreemem(void *ptr)
3104 * PQfreeNotify - free's the memory associated with a PGnotify
3106 * This function is here only for binary backward compatibility.
3107 * New code should use PQfreemem(). A macro will automatically map
3108 * calls to PQfreemem. It should be removed in the future. bjm 2003-03-24
3112 void PQfreeNotify(PGnotify *notify);
3115 PQfreeNotify(PGnotify *notify)
3122 * Escaping arbitrary strings to get valid SQL literal strings.
3124 * Replaces "'" with "''", and if not std_strings, replaces "\" with "\\".
3126 * length is the length of the source string. (Note: if a terminating NUL
3127 * is encountered sooner, PQescapeString stops short of "length"; the behavior
3128 * is thus rather like strncpy.)
3130 * For safety the buffer at "to" must be at least 2*length + 1 bytes long.
3131 * A terminating NUL character is added to the output string, whether the
3132 * input is NUL-terminated or not.
3134 * Returns the actual length of the output (not counting the terminating NUL).
3137 PQescapeStringInternal(PGconn *conn,
3138 char *to, const char *from, size_t length,
3140 int encoding, bool std_strings)
3142 const char *source = from;
3144 size_t remaining = length;
3149 while (remaining > 0 && *source != '\0')
3155 /* Fast path for plain ASCII */
3156 if (!IS_HIGHBIT_SET(c))
3158 /* Apply quoting if needed */
3159 if (SQL_STR_DOUBLE(c, !std_strings))
3161 /* Copy the character */
3168 /* Slow path for possible multibyte characters */
3169 len = pg_encoding_mblen(encoding, source);
3171 /* Copy the character */
3172 for (i = 0; i < len; i++)
3174 if (remaining == 0 || *source == '\0')
3176 *target++ = *source++;
3181 * If we hit premature end of string (ie, incomplete multibyte
3182 * character), try to pad out to the correct length with spaces. We
3183 * may not be able to pad completely, but we will always be able to
3184 * insert at least one pad space (since we'd not have quoted a
3185 * multibyte character). This should be enough to make a string that
3186 * the server will error out on.
3193 printfPQExpBuffer(&conn->errorMessage,
3194 libpq_gettext("incomplete multibyte character\n"));
3195 for (; i < len; i++)
3197 if (((size_t) (target - to)) / 2 >= length)
3205 /* Write the terminating NUL character. */
3212 PQescapeStringConn(PGconn *conn,
3213 char *to, const char *from, size_t length,
3218 /* force empty-string result */
3224 return PQescapeStringInternal(conn, to, from, length, error,
3225 conn->client_encoding,
3230 PQescapeString(char *to, const char *from, size_t length)
3232 return PQescapeStringInternal(NULL, to, from, length, NULL,
3233 static_client_encoding,
3234 static_std_strings);
3239 * Escape arbitrary strings. If as_ident is true, we escape the result
3240 * as an identifier; if false, as a literal. The result is returned in
3241 * a newly allocated buffer. If we fail due to an encoding violation or out
3242 * of memory condition, we return NULL, storing an error message into conn.
3245 PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
3250 int num_quotes = 0; /* single or double, depending on as_ident */
3251 int num_backslashes = 0;
3254 char quote_char = as_ident ? '"' : '\'';
3256 /* We must have a connection, else fail immediately. */
3260 /* Scan the string for characters that must be escaped. */
3261 for (s = str; (s - str) < len && *s != '\0'; ++s)
3263 if (*s == quote_char)
3265 else if (*s == '\\')
3267 else if (IS_HIGHBIT_SET(*s))
3271 /* Slow path for possible multibyte characters */
3272 charlen = pg_encoding_mblen(conn->client_encoding, s);
3274 /* Multibyte character overruns allowable length. */
3275 if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
3277 printfPQExpBuffer(&conn->errorMessage,
3278 libpq_gettext("incomplete multibyte character\n"));
3282 /* Adjust s, bearing in mind that for loop will increment it. */
3287 /* Allocate output buffer. */
3288 input_len = s - str;
3289 result_size = input_len + num_quotes + 3; /* two quotes, plus a NUL */
3290 if (!as_ident && num_backslashes > 0)
3291 result_size += num_backslashes + 2;
3292 result = rp = (char *) malloc(result_size);
3295 printfPQExpBuffer(&conn->errorMessage,
3296 libpq_gettext("out of memory\n"));
3301 * If we are escaping a literal that contains backslashes, we use the
3302 * escape string syntax so that the result is correct under either value
3303 * of standard_conforming_strings. We also emit a leading space in this
3304 * case, to guard against the possibility that the result might be
3305 * interpolated immediately following an identifier.
3307 if (!as_ident && num_backslashes > 0)
3313 /* Opening quote. */
3317 * Use fast path if possible.
3319 * We've already verified that the input string is well-formed in the
3320 * current encoding. If it contains no quotes and, in the case of
3321 * literal-escaping, no backslashes, then we can just copy it directly to
3322 * the output buffer, adding the necessary quotes.
3324 * If not, we must rescan the input and process each character
3327 if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
3329 memcpy(rp, str, input_len);
3334 for (s = str; s - str < input_len; ++s)
3336 if (*s == quote_char || (!as_ident && *s == '\\'))
3341 else if (!IS_HIGHBIT_SET(*s))
3345 int i = pg_encoding_mblen(conn->client_encoding, s);
3352 ++s; /* for loop will provide the final increment */
3358 /* Closing quote and terminating NUL. */
3366 PQescapeLiteral(PGconn *conn, const char *str, size_t len)
3368 return PQescapeInternal(conn, str, len, false);
3372 PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
3374 return PQescapeInternal(conn, str, len, true);
3377 /* HEX encoding support for bytea */
3378 static const char hextbl[] = "0123456789abcdef";
3380 static const int8 hexlookup[128] = {
3381 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3382 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3383 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3384 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
3385 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3386 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3387 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3388 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3396 if (c > 0 && c < 127)
3397 res = hexlookup[(unsigned char) c];
3404 * PQescapeBytea - converts from binary string to the
3405 * minimal encoding necessary to include the string in an SQL
3406 * INSERT statement with a bytea type column as the target.
3408 * We can use either hex or escape (traditional) encoding.
3409 * In escape mode, the following transformations are applied:
3410 * '\0' == ASCII 0 == \000
3411 * '\'' == ASCII 39 == ''
3412 * '\\' == ASCII 92 == \\
3413 * anything < 0x20, or > 0x7e ---> \ooo
3414 * (where ooo is an octal expression)
3416 * If not std_strings, all backslashes sent to the output are doubled.
3418 static unsigned char *
3419 PQescapeByteaInternal(PGconn *conn,
3420 const unsigned char *from, size_t from_length,
3421 size_t *to_length, bool std_strings, bool use_hex)
3423 const unsigned char *vp;
3425 unsigned char *result;
3428 size_t bslash_len = (std_strings ? 1 : 2);
3431 * empty string has 1 char ('\0')
3437 len += bslash_len + 1 + 2 * from_length;
3442 for (i = from_length; i > 0; i--, vp++)
3444 if (*vp < 0x20 || *vp > 0x7e)
3445 len += bslash_len + 3;
3446 else if (*vp == '\'')
3448 else if (*vp == '\\')
3449 len += bslash_len + bslash_len;
3456 rp = result = (unsigned char *) malloc(len);
3460 printfPQExpBuffer(&conn->errorMessage,
3461 libpq_gettext("out of memory\n"));
3474 for (i = from_length; i > 0; i--, vp++)
3476 unsigned char c = *vp;
3480 *rp++ = hextbl[(c >> 4) & 0xF];
3481 *rp++ = hextbl[c & 0xF];
3483 else if (c < 0x20 || c > 0x7e)
3488 *rp++ = (c >> 6) + '0';
3489 *rp++ = ((c >> 3) & 07) + '0';
3490 *rp++ = (c & 07) + '0';
3516 PQescapeByteaConn(PGconn *conn,
3517 const unsigned char *from, size_t from_length,
3522 return PQescapeByteaInternal(conn, from, from_length, to_length,
3524 (conn->sversion >= 90000));
3528 PQescapeBytea(const unsigned char *from, size_t from_length, size_t *to_length)
3530 return PQescapeByteaInternal(NULL, from, from_length, to_length,
3532 false /* can't use hex */ );
3536 #define ISFIRSTOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '3')
3537 #define ISOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '7')
3538 #define OCTVAL(CH) ((CH) - '0')
3541 * PQunescapeBytea - converts the null terminated string representation
3542 * of a bytea, strtext, into binary, filling a buffer. It returns a
3543 * pointer to the buffer (or NULL on error), and the size of the
3544 * buffer in retbuflen. The pointer may subsequently be used as an
3545 * argument to the function PQfreemem.
3547 * The following transformations are made:
3548 * \\ == ASCII 92 == \
3549 * \ooo == a byte whose value = ooo (ooo is an octal number)
3550 * \x == x (x is any character not matched by the above transformations)
3553 PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
3557 unsigned char *buffer,
3562 if (strtext == NULL)
3565 strtextlen = strlen((const char *) strtext);
3567 if (strtext[0] == '\\' && strtext[1] == 'x')
3569 const unsigned char *s;
3572 buflen = (strtextlen - 2) / 2;
3573 /* Avoid unportable malloc(0) */
3574 buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
3586 * Bad input is silently ignored. Note that this includes
3587 * whitespace between hex pairs, which is allowed by byteain.
3590 if (!*s || v1 == (char) -1)
3593 if (v2 != (char) -1)
3594 *p++ = (v1 << 4) | v2;
3597 buflen = p - buffer;
3602 * Length of input is max length of output, but add one to avoid
3603 * unportable malloc(0) if input is zero-length.
3605 buffer = (unsigned char *) malloc(strtextlen + 1);
3609 for (i = j = 0; i < strtextlen;)
3615 if (strtext[i] == '\\')
3616 buffer[j++] = strtext[i++];
3619 if ((ISFIRSTOCTDIGIT(strtext[i])) &&
3620 (ISOCTDIGIT(strtext[i + 1])) &&
3621 (ISOCTDIGIT(strtext[i + 2])))
3625 byte = OCTVAL(strtext[i++]);
3626 byte = (byte << 3) + OCTVAL(strtext[i++]);
3627 byte = (byte << 3) + OCTVAL(strtext[i++]);
3633 * Note: if we see '\' followed by something that isn't a
3634 * recognized escape sequence, we loop around having done
3635 * nothing except advance i. Therefore the something will
3636 * be emitted as ordinary data on the next cycle. Corner
3637 * case: '\' at end of string will just be discarded.
3642 buffer[j++] = strtext[i++];
3646 buflen = j; /* buflen is the length of the dequoted data */
3649 /* Shrink the buffer to be no larger than necessary */
3650 /* +1 avoids unportable behavior when buflen==0 */
3651 tmpbuf = realloc(buffer, buflen + 1);
3653 /* It would only be a very brain-dead realloc that could fail, but... */
3660 *retbuflen = buflen;