1 /*-------------------------------------------------------------------------
4 * functions related to sending a query down to the backend
6 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/interfaces/libpq/fe-exec.c,v 1.190 2006/08/18 19:52:39 tgl Exp $
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",
44 * static state needed by PQescapeString and PQescapeBytea; initialize to
45 * values that result in backward-compatible behavior
47 static int static_client_encoding = PG_SQL_ASCII;
48 static bool static_std_strings = false;
51 static bool PQsendQueryStart(PGconn *conn);
52 static int PQsendQueryGuts(PGconn *conn,
56 const Oid *paramTypes,
57 const char *const * paramValues,
58 const int *paramLengths,
59 const int *paramFormats,
61 static void parseInput(PGconn *conn);
62 static bool PQexecStart(PGconn *conn);
63 static PGresult *PQexecFinish(PGconn *conn);
64 static int PQsendDescribe(PGconn *conn, char desc_type,
65 const char *desc_target);
69 * Space management for PGresult.
71 * Formerly, libpq did a separate malloc() for each field of each tuple
72 * returned by a query. This was remarkably expensive --- malloc/free
73 * consumed a sizable part of the application's runtime. And there is
74 * no real need to keep track of the fields separately, since they will
75 * all be freed together when the PGresult is released. So now, we grab
76 * large blocks of storage from malloc and allocate space for query data
77 * within these blocks, using a trivially simple allocator. This reduces
78 * the number of malloc/free calls dramatically, and it also avoids
79 * fragmentation of the malloc storage arena.
80 * The PGresult structure itself is still malloc'd separately. We could
81 * combine it with the first allocation block, but that would waste space
82 * for the common case that no extra storage is actually needed (that is,
83 * the SQL command did not return tuples).
85 * We also malloc the top-level array of tuple pointers separately, because
86 * we need to be able to enlarge it via realloc, and our trivial space
87 * allocator doesn't handle that effectively. (Too bad the FE/BE protocol
88 * doesn't tell us up front how many tuples will be returned.)
89 * All other subsidiary storage for a PGresult is kept in PGresult_data blocks
90 * of size PGRESULT_DATA_BLOCKSIZE. The overhead at the start of each block
91 * is just a link to the next one, if any. Free-space management info is
92 * kept in the owning PGresult.
93 * A query returning a small amount of data will thus require three malloc
94 * calls: one for the PGresult, one for the tuples pointer array, and one
95 * PGresult_data block.
97 * Only the most recently allocated PGresult_data block is a candidate to
98 * have more stuff added to it --- any extra space left over in older blocks
99 * is wasted. We could be smarter and search the whole chain, but the point
100 * here is to be simple and fast. Typical applications do not keep a PGresult
101 * around very long anyway, so some wasted space within one is not a problem.
103 * Tuning constants for the space allocator are:
104 * PGRESULT_DATA_BLOCKSIZE: size of a standard allocation block, in bytes
105 * PGRESULT_ALIGN_BOUNDARY: assumed alignment requirement for binary data
106 * PGRESULT_SEP_ALLOC_THRESHOLD: objects bigger than this are given separate
107 * blocks, instead of being crammed into a regular allocation block.
108 * Requirements for correct function are:
109 * PGRESULT_ALIGN_BOUNDARY must be a multiple of the alignment requirements
110 * of all machine data types. (Currently this is set from configure
111 * tests, so it should be OK automatically.)
112 * PGRESULT_SEP_ALLOC_THRESHOLD + PGRESULT_BLOCK_OVERHEAD <=
113 * PGRESULT_DATA_BLOCKSIZE
114 * pqResultAlloc assumes an object smaller than the threshold will fit
116 * The amount of space wasted at the end of a block could be as much as
117 * PGRESULT_SEP_ALLOC_THRESHOLD, so it doesn't pay to make that too large.
121 #define PGRESULT_DATA_BLOCKSIZE 2048
122 #define PGRESULT_ALIGN_BOUNDARY MAXIMUM_ALIGNOF /* from configure */
123 #define PGRESULT_BLOCK_OVERHEAD Max(sizeof(PGresult_data), PGRESULT_ALIGN_BOUNDARY)
124 #define PGRESULT_SEP_ALLOC_THRESHOLD (PGRESULT_DATA_BLOCKSIZE / 2)
128 * PQmakeEmptyPGresult
129 * returns a newly allocated, initialized PGresult with given status.
130 * If conn is not NULL and status indicates an error, the conn's
131 * errorMessage is copied.
133 * Note this is exported --- you wouldn't think an application would need
134 * to build its own PGresults, but this has proven useful in both libpgtcl
135 * and the Perl5 interface, so maybe it's not so unreasonable.
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->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 /* non-error cases */
181 pqSetResultError(result, conn->errorMessage.data);
188 result->noticeHooks.noticeRec = NULL;
189 result->noticeHooks.noticeRecArg = NULL;
190 result->noticeHooks.noticeProc = NULL;
191 result->noticeHooks.noticeProcArg = NULL;
192 result->client_encoding = PG_SQL_ASCII;
200 * Allocate subsidiary storage for a PGresult.
202 * nBytes is the amount of space needed for the object.
203 * If isBinary is true, we assume that we need to align the object on
204 * a machine allocation boundary.
205 * If isBinary is false, we assume the object is a char string and can
206 * be allocated on any byte boundary.
209 pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
212 PGresult_data *block;
218 return res->null_field;
221 * If alignment is needed, round up the current position to an alignment
226 int offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
230 res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
231 res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
235 /* If there's enough space in the current block, no problem. */
236 if (nBytes <= (size_t) res->spaceLeft)
238 space = res->curBlock->space + res->curOffset;
239 res->curOffset += nBytes;
240 res->spaceLeft -= nBytes;
245 * If the requested object is very large, give it its own block; this
246 * avoids wasting what might be most of the current block to start a new
247 * block. (We'd have to special-case requests bigger than the block size
248 * anyway.) The object is always given binary alignment in this case.
250 if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
252 block = (PGresult_data *) malloc(nBytes + PGRESULT_BLOCK_OVERHEAD);
255 space = block->space + PGRESULT_BLOCK_OVERHEAD;
259 * Tuck special block below the active block, so that we don't
260 * have to waste the free space in the active block.
262 block->next = res->curBlock->next;
263 res->curBlock->next = block;
267 /* Must set up the new block as the first active block. */
269 res->curBlock = block;
270 res->spaceLeft = 0; /* be sure it's marked full */
275 /* Otherwise, start a new block. */
276 block = (PGresult_data *) malloc(PGRESULT_DATA_BLOCKSIZE);
279 block->next = res->curBlock;
280 res->curBlock = block;
283 /* object needs full alignment */
284 res->curOffset = PGRESULT_BLOCK_OVERHEAD;
285 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - PGRESULT_BLOCK_OVERHEAD;
289 /* we can cram it right after the overhead pointer */
290 res->curOffset = sizeof(PGresult_data);
291 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - sizeof(PGresult_data);
294 space = block->space + res->curOffset;
295 res->curOffset += nBytes;
296 res->spaceLeft -= nBytes;
302 * Like strdup, but the space is subsidiary PGresult space.
305 pqResultStrdup(PGresult *res, const char *str)
307 char *space = (char *) pqResultAlloc(res, strlen(str) + 1, FALSE);
316 * assign a new error message to a PGresult
319 pqSetResultError(PGresult *res, const char *msg)
324 res->errMsg = pqResultStrdup(res, msg);
330 * pqCatenateResultError -
331 * concatenate a new error message to the one already in a PGresult
334 pqCatenateResultError(PGresult *res, const char *msg)
336 PQExpBufferData errorBuf;
340 initPQExpBuffer(&errorBuf);
342 appendPQExpBufferStr(&errorBuf, res->errMsg);
343 appendPQExpBufferStr(&errorBuf, msg);
344 pqSetResultError(res, errorBuf.data);
345 termPQExpBuffer(&errorBuf);
350 * free's the memory associated with a PGresult
353 PQclear(PGresult *res)
355 PGresult_data *block;
360 /* Free all the subsidiary blocks */
361 while ((block = res->curBlock) != NULL)
363 res->curBlock = block->next;
367 /* Free the top-level tuple pointer array */
371 /* zero out the pointer fields to catch programming errors */
372 res->attDescs = NULL;
374 res->paramDescs = NULL;
375 res->errFields = NULL;
376 /* res->curBlock was zeroed out earlier */
378 /* Free the PGresult structure itself */
383 * Handy subroutine to deallocate any partially constructed async result.
387 pqClearAsyncResult(PGconn *conn)
390 PQclear(conn->result);
392 conn->curTuple = NULL;
396 * This subroutine deletes any existing async result, sets conn->result
397 * to a PGresult with status PGRES_FATAL_ERROR, and stores the current
398 * contents of conn->errorMessage into that result. It differs from a
399 * plain call on PQmakeEmptyPGresult() in that if there is already an
400 * async result with status PGRES_FATAL_ERROR, the current error message
401 * is APPENDED to the old error message instead of replacing it. This
402 * behavior lets us report multiple error conditions properly, if necessary.
403 * (An example where this is needed is when the backend sends an 'E' message
404 * and immediately closes the connection --- we want to report both the
405 * backend error and the connection closure error.)
408 pqSaveErrorResult(PGconn *conn)
411 * If no old async result, just let PQmakeEmptyPGresult make one. Likewise
412 * if old result is not an error message.
414 if (conn->result == NULL ||
415 conn->result->resultStatus != PGRES_FATAL_ERROR ||
416 conn->result->errMsg == NULL)
418 pqClearAsyncResult(conn);
419 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
423 /* Else, concatenate error message to existing async result. */
424 pqCatenateResultError(conn->result, conn->errorMessage.data);
429 * This subroutine prepares an async result object for return to the caller.
430 * If there is not already an async result object, build an error object
431 * using whatever is in conn->errorMessage. In any case, clear the async
432 * result storage and make sure PQerrorMessage will agree with the result's
436 pqPrepareAsyncResult(PGconn *conn)
441 * conn->result is the PGresult to return. If it is NULL (which probably
442 * shouldn't happen) we assume there is an appropriate error message in
443 * conn->errorMessage.
446 conn->result = NULL; /* handing over ownership to caller */
447 conn->curTuple = NULL; /* just in case */
449 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
453 * Make sure PQerrorMessage agrees with result; it could be different
454 * if we have concatenated messages.
456 resetPQExpBuffer(&conn->errorMessage);
457 appendPQExpBufferStr(&conn->errorMessage,
458 PQresultErrorMessage(res));
464 * pqInternalNotice - produce an internally-generated notice message
466 * A format string and optional arguments can be passed. Note that we do
467 * libpq_gettext() here, so callers need not.
469 * The supplied text is taken as primary message (ie., it should not include
470 * a trailing newline, and should not be more than one line).
473 pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
479 if (hooks->noticeRec == NULL)
480 return; /* nobody home to receive notice? */
482 /* Format the message */
484 vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
486 msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
488 /* Make a PGresult to pass to the notice receiver */
489 res = PQmakeEmptyPGresult(NULL, PGRES_NONFATAL_ERROR);
492 res->noticeHooks = *hooks;
495 * Set up fields of notice.
497 pqSaveMessageField(res, PG_DIAG_MESSAGE_PRIMARY, msgBuf);
498 pqSaveMessageField(res, PG_DIAG_SEVERITY, libpq_gettext("NOTICE"));
499 /* XXX should provide a SQLSTATE too? */
502 * Result text is always just the primary message + newline. If we can't
503 * allocate it, don't bother invoking the receiver.
505 res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, FALSE);
508 sprintf(res->errMsg, "%s\n", msgBuf);
511 * Pass to receiver, then free it.
513 (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
520 * add a row pointer to the PGresult structure, growing it if necessary
521 * Returns TRUE if OK, FALSE if not enough memory to add the row
524 pqAddTuple(PGresult *res, PGresAttValue *tup)
526 if (res->ntups >= res->tupArrSize)
529 * Try to grow the array.
531 * We can use realloc because shallow copying of the structure is
532 * okay. Note that the first time through, res->tuples is NULL. While
533 * ANSI says that realloc() should act like malloc() in that case,
534 * some old C libraries (like SunOS 4.1.x) coredump instead. On
535 * failure realloc is supposed to return NULL without damaging the
536 * existing allocation. Note that the positions beyond res->ntups are
537 * garbage, not necessarily NULL.
539 int newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
540 PGresAttValue **newTuples;
542 if (res->tuples == NULL)
543 newTuples = (PGresAttValue **)
544 malloc(newSize * sizeof(PGresAttValue *));
546 newTuples = (PGresAttValue **)
547 realloc(res->tuples, newSize * sizeof(PGresAttValue *));
549 return FALSE; /* malloc or realloc failed */
550 res->tupArrSize = newSize;
551 res->tuples = newTuples;
553 res->tuples[res->ntups] = tup;
559 * pqSaveMessageField - save one field of an error or notice message
562 pqSaveMessageField(PGresult *res, char code, const char *value)
564 PGMessageField *pfield;
566 pfield = (PGMessageField *)
568 sizeof(PGMessageField) + strlen(value),
571 return; /* out of memory? */
573 strcpy(pfield->contents, value);
574 pfield->next = res->errFields;
575 res->errFields = pfield;
579 * pqSaveParameterStatus - remember parameter status sent by backend
582 pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
584 pgParameterStatus *pstatus;
585 pgParameterStatus *prev;
588 fprintf(conn->Pfdebug, "pqSaveParameterStatus: '%s' = '%s'\n",
592 * Forget any old information about the parameter
594 for (pstatus = conn->pstatus, prev = NULL;
596 prev = pstatus, pstatus = pstatus->next)
598 if (strcmp(pstatus->name, name) == 0)
601 prev->next = pstatus->next;
603 conn->pstatus = pstatus->next;
604 free(pstatus); /* frees name and value strings too */
610 * Store new info as a single malloc block
612 pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
613 strlen(name) +strlen(value) + 2);
618 ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
621 ptr += strlen(name) + 1;
622 pstatus->value = ptr;
624 pstatus->next = conn->pstatus;
625 conn->pstatus = pstatus;
629 * Special hacks: remember client_encoding and standard_conforming_strings,
630 * and convert server version to a numeric form. We keep the first two of
631 * these in static variables as well, so that PQescapeString and
632 * PQescapeBytea can behave somewhat sanely (at least in single-
633 * connection-using programs).
635 if (strcmp(name, "client_encoding") == 0)
637 conn->client_encoding = pg_char_to_encoding(value);
638 static_client_encoding = conn->client_encoding;
640 else if (strcmp(name, "standard_conforming_strings") == 0)
642 conn->std_strings = (strcmp(value, "on") == 0);
643 static_std_strings = conn->std_strings;
645 else if (strcmp(name, "server_version") == 0)
652 cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
655 conn->sversion = 0; /* unknown */
660 conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
668 * Submit a query, but don't wait for it to finish
670 * Returns: 1 if successfully submitted
671 * 0 if error (conn->errorMessage is set)
674 PQsendQuery(PGconn *conn, const char *query)
676 if (!PQsendQueryStart(conn))
681 printfPQExpBuffer(&conn->errorMessage,
682 libpq_gettext("command string is a null pointer\n"));
686 /* construct the outgoing Query message */
687 if (pqPutMsgStart('Q', false, conn) < 0 ||
688 pqPuts(query, conn) < 0 ||
689 pqPutMsgEnd(conn) < 0)
691 pqHandleSendFailure(conn);
695 /* remember we are using simple query protocol */
696 conn->queryclass = PGQUERY_SIMPLE;
698 /* and remember the query text too, if possible */
699 /* if insufficient memory, last_query just winds up NULL */
700 if (conn->last_query)
701 free(conn->last_query);
702 conn->last_query = strdup(query);
705 * Give the data a push. In nonblock mode, don't complain if we're unable
706 * to send it all; PQgetResult() will do any additional flushing needed.
708 if (pqFlush(conn) < 0)
710 pqHandleSendFailure(conn);
714 /* OK, it's launched! */
715 conn->asyncStatus = PGASYNC_BUSY;
721 * Like PQsendQuery, but use protocol 3.0 so we can pass parameters
724 PQsendQueryParams(PGconn *conn,
727 const Oid *paramTypes,
728 const char *const * paramValues,
729 const int *paramLengths,
730 const int *paramFormats,
733 if (!PQsendQueryStart(conn))
738 printfPQExpBuffer(&conn->errorMessage,
739 libpq_gettext("command string is a null pointer\n"));
743 return PQsendQueryGuts(conn,
745 "", /* use unnamed statement */
756 * Submit a Parse message, but don't wait for it to finish
758 * Returns: 1 if successfully submitted
759 * 0 if error (conn->errorMessage is set)
762 PQsendPrepare(PGconn *conn,
763 const char *stmtName, const char *query,
764 int nParams, const Oid *paramTypes)
766 if (!PQsendQueryStart(conn))
771 printfPQExpBuffer(&conn->errorMessage,
772 libpq_gettext("statement name is a null pointer\n"));
778 printfPQExpBuffer(&conn->errorMessage,
779 libpq_gettext("command string is a null pointer\n"));
783 /* This isn't gonna work on a 2.0 server */
784 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
786 printfPQExpBuffer(&conn->errorMessage,
787 libpq_gettext("function requires at least protocol version 3.0\n"));
791 /* construct the Parse message */
792 if (pqPutMsgStart('P', false, conn) < 0 ||
793 pqPuts(stmtName, conn) < 0 ||
794 pqPuts(query, conn) < 0)
797 if (nParams > 0 && paramTypes)
801 if (pqPutInt(nParams, 2, conn) < 0)
803 for (i = 0; i < nParams; i++)
805 if (pqPutInt(paramTypes[i], 4, conn) < 0)
811 if (pqPutInt(0, 2, conn) < 0)
814 if (pqPutMsgEnd(conn) < 0)
817 /* construct the Sync message */
818 if (pqPutMsgStart('S', false, conn) < 0 ||
819 pqPutMsgEnd(conn) < 0)
822 /* remember we are doing just a Parse */
823 conn->queryclass = PGQUERY_PREPARE;
825 /* and remember the query text too, if possible */
826 /* if insufficient memory, last_query just winds up NULL */
827 if (conn->last_query)
828 free(conn->last_query);
829 conn->last_query = strdup(query);
832 * Give the data a push. In nonblock mode, don't complain if we're unable
833 * to send it all; PQgetResult() will do any additional flushing needed.
835 if (pqFlush(conn) < 0)
838 /* OK, it's launched! */
839 conn->asyncStatus = PGASYNC_BUSY;
843 pqHandleSendFailure(conn);
848 * PQsendQueryPrepared
849 * Like PQsendQuery, but execute a previously prepared statement,
850 * using protocol 3.0 so we can pass parameters
853 PQsendQueryPrepared(PGconn *conn,
854 const char *stmtName,
856 const char *const * paramValues,
857 const int *paramLengths,
858 const int *paramFormats,
861 if (!PQsendQueryStart(conn))
866 printfPQExpBuffer(&conn->errorMessage,
867 libpq_gettext("statement name is a null pointer\n"));
871 return PQsendQueryGuts(conn,
872 NULL, /* no command to parse */
875 NULL, /* no param types */
883 * Common startup code for PQsendQuery and sibling routines
886 PQsendQueryStart(PGconn *conn)
891 /* clear the error string */
892 resetPQExpBuffer(&conn->errorMessage);
894 /* Don't try to send if we know there's no live connection. */
895 if (conn->status != CONNECTION_OK)
897 printfPQExpBuffer(&conn->errorMessage,
898 libpq_gettext("no connection to the server\n"));
901 /* Can't send while already busy, either. */
902 if (conn->asyncStatus != PGASYNC_IDLE)
904 printfPQExpBuffer(&conn->errorMessage,
905 libpq_gettext("another command is already in progress\n"));
909 /* initialize async result-accumulation state */
911 conn->curTuple = NULL;
913 /* ready to send command message */
919 * Common code for protocol-3.0 query sending
920 * PQsendQueryStart should be done already
922 * command may be NULL to indicate we use an already-prepared statement
925 PQsendQueryGuts(PGconn *conn,
927 const char *stmtName,
929 const Oid *paramTypes,
930 const char *const * paramValues,
931 const int *paramLengths,
932 const int *paramFormats,
937 /* This isn't gonna work on a 2.0 server */
938 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
940 printfPQExpBuffer(&conn->errorMessage,
941 libpq_gettext("function requires at least protocol version 3.0\n"));
946 * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync,
947 * using specified statement name and the unnamed portal.
952 /* construct the Parse message */
953 if (pqPutMsgStart('P', false, conn) < 0 ||
954 pqPuts(stmtName, conn) < 0 ||
955 pqPuts(command, conn) < 0)
957 if (nParams > 0 && paramTypes)
959 if (pqPutInt(nParams, 2, conn) < 0)
961 for (i = 0; i < nParams; i++)
963 if (pqPutInt(paramTypes[i], 4, conn) < 0)
969 if (pqPutInt(0, 2, conn) < 0)
972 if (pqPutMsgEnd(conn) < 0)
976 /* construct the Bind message */
977 if (pqPutMsgStart('B', false, conn) < 0 ||
978 pqPuts("", conn) < 0 ||
979 pqPuts(stmtName, conn) < 0)
982 if (nParams > 0 && paramFormats)
984 if (pqPutInt(nParams, 2, conn) < 0)
986 for (i = 0; i < nParams; i++)
988 if (pqPutInt(paramFormats[i], 2, conn) < 0)
994 if (pqPutInt(0, 2, conn) < 0)
998 if (pqPutInt(nParams, 2, conn) < 0)
1001 for (i = 0; i < nParams; i++)
1003 if (paramValues && paramValues[i])
1007 if (paramFormats && paramFormats[i] != 0)
1009 /* binary parameter */
1011 nbytes = paramLengths[i];
1014 printfPQExpBuffer(&conn->errorMessage,
1015 libpq_gettext("length must be given for binary parameter\n"));
1021 /* text parameter, do not use paramLengths */
1022 nbytes = strlen(paramValues[i]);
1024 if (pqPutInt(nbytes, 4, conn) < 0 ||
1025 pqPutnchar(paramValues[i], nbytes, conn) < 0)
1030 /* take the param as NULL */
1031 if (pqPutInt(-1, 4, conn) < 0)
1035 if (pqPutInt(1, 2, conn) < 0 ||
1036 pqPutInt(resultFormat, 2, conn))
1038 if (pqPutMsgEnd(conn) < 0)
1041 /* construct the Describe Portal message */
1042 if (pqPutMsgStart('D', false, conn) < 0 ||
1043 pqPutc('P', conn) < 0 ||
1044 pqPuts("", conn) < 0 ||
1045 pqPutMsgEnd(conn) < 0)
1048 /* construct the Execute message */
1049 if (pqPutMsgStart('E', false, conn) < 0 ||
1050 pqPuts("", conn) < 0 ||
1051 pqPutInt(0, 4, conn) < 0 ||
1052 pqPutMsgEnd(conn) < 0)
1055 /* construct the Sync message */
1056 if (pqPutMsgStart('S', false, conn) < 0 ||
1057 pqPutMsgEnd(conn) < 0)
1060 /* remember we are using extended query protocol */
1061 conn->queryclass = PGQUERY_EXTENDED;
1063 /* and remember the query text too, if possible */
1064 /* if insufficient memory, last_query just winds up NULL */
1065 if (conn->last_query)
1066 free(conn->last_query);
1068 conn->last_query = strdup(command);
1070 conn->last_query = NULL;
1073 * Give the data a push. In nonblock mode, don't complain if we're unable
1074 * to send it all; PQgetResult() will do any additional flushing needed.
1076 if (pqFlush(conn) < 0)
1079 /* OK, it's launched! */
1080 conn->asyncStatus = PGASYNC_BUSY;
1084 pqHandleSendFailure(conn);
1089 * pqHandleSendFailure: try to clean up after failure to send command.
1091 * Primarily, what we want to accomplish here is to process an async
1092 * NOTICE message that the backend might have sent just before it died.
1094 * NOTE: this routine should only be called in PGASYNC_IDLE state.
1097 pqHandleSendFailure(PGconn *conn)
1100 * Accept any available input data, ignoring errors. Note that if
1101 * pqReadData decides the backend has closed the channel, it will close
1102 * our side of the socket --- that's just what we want here.
1104 while (pqReadData(conn) > 0)
1105 /* loop until no more data readable */ ;
1108 * Parse any available input messages. Since we are in PGASYNC_IDLE
1109 * state, only NOTICE and NOTIFY messages will be eaten.
1115 * Consume any available input from the backend
1116 * 0 return: some kind of trouble
1117 * 1 return: no problem
1120 PQconsumeInput(PGconn *conn)
1126 * for non-blocking connections try to flush the send-queue, otherwise we
1127 * may never get a response for something that may not have already been
1128 * sent because it's in our write buffer!
1130 if (pqIsnonblocking(conn))
1132 if (pqFlush(conn) < 0)
1137 * Load more data, if available. We do this no matter what state we are
1138 * in, since we are probably getting called because the application wants
1139 * to get rid of a read-select condition. Note that we will NOT block
1140 * waiting for more input.
1142 if (pqReadData(conn) < 0)
1145 /* Parsing of the data waits till later. */
1151 * parseInput: if appropriate, parse input data from backend
1152 * until input is exhausted or a stopping state is reached.
1153 * Note that this function will NOT attempt to read more data from the backend.
1156 parseInput(PGconn *conn)
1158 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1159 pqParseInput3(conn);
1161 pqParseInput2(conn);
1166 * Return TRUE if PQgetResult would block waiting for input.
1170 PQisBusy(PGconn *conn)
1175 /* Parse any available data, if our state permits. */
1178 /* PQgetResult will return immediately in all states except BUSY. */
1179 return conn->asyncStatus == PGASYNC_BUSY;
1185 * Get the next PGresult produced by a query. Returns NULL if no
1186 * query work remains or an error has occurred (e.g. out of
1191 PQgetResult(PGconn *conn)
1198 /* Parse any available data, if our state permits. */
1201 /* If not ready to return something, block until we are. */
1202 while (conn->asyncStatus == PGASYNC_BUSY)
1207 * If data remains unsent, send it. Else we might be waiting for the
1208 * result of a command the backend hasn't even got yet.
1210 while ((flushResult = pqFlush(conn)) > 0)
1212 if (pqWait(FALSE, TRUE, conn))
1219 /* Wait for some more data, and load it. */
1221 pqWait(TRUE, FALSE, conn) ||
1222 pqReadData(conn) < 0)
1225 * conn->errorMessage has been set by pqWait or pqReadData. We
1226 * want to append it to any already-received error message.
1228 pqSaveErrorResult(conn);
1229 conn->asyncStatus = PGASYNC_IDLE;
1230 return pqPrepareAsyncResult(conn);
1237 /* Return the appropriate thing. */
1238 switch (conn->asyncStatus)
1241 res = NULL; /* query is complete */
1244 res = pqPrepareAsyncResult(conn);
1245 /* Set the state back to BUSY, allowing parsing to proceed. */
1246 conn->asyncStatus = PGASYNC_BUSY;
1248 case PGASYNC_COPY_IN:
1249 if (conn->result && conn->result->resultStatus == PGRES_COPY_IN)
1250 res = pqPrepareAsyncResult(conn);
1252 res = PQmakeEmptyPGresult(conn, PGRES_COPY_IN);
1254 case PGASYNC_COPY_OUT:
1255 if (conn->result && conn->result->resultStatus == PGRES_COPY_OUT)
1256 res = pqPrepareAsyncResult(conn);
1258 res = PQmakeEmptyPGresult(conn, PGRES_COPY_OUT);
1261 printfPQExpBuffer(&conn->errorMessage,
1262 libpq_gettext("unexpected asyncStatus: %d\n"),
1263 (int) conn->asyncStatus);
1264 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1274 * send a query to the backend and package up the result in a PGresult
1276 * If the query was not even sent, return NULL; conn->errorMessage is set to
1277 * a relevant message.
1278 * If the query was sent, a new PGresult is returned (which could indicate
1279 * either success or failure).
1280 * The user is responsible for freeing the PGresult via PQclear()
1281 * when done with it.
1284 PQexec(PGconn *conn, const char *query)
1286 if (!PQexecStart(conn))
1288 if (!PQsendQuery(conn, query))
1290 return PQexecFinish(conn);
1295 * Like PQexec, but use protocol 3.0 so we can pass parameters
1298 PQexecParams(PGconn *conn,
1299 const char *command,
1301 const Oid *paramTypes,
1302 const char *const * paramValues,
1303 const int *paramLengths,
1304 const int *paramFormats,
1307 if (!PQexecStart(conn))
1309 if (!PQsendQueryParams(conn, command,
1310 nParams, paramTypes, paramValues, paramLengths,
1311 paramFormats, resultFormat))
1313 return PQexecFinish(conn);
1318 * Creates a prepared statement by issuing a v3.0 parse message.
1320 * If the query was not even sent, return NULL; conn->errorMessage is set to
1321 * a relevant message.
1322 * If the query was sent, a new PGresult is returned (which could indicate
1323 * either success or failure).
1324 * The user is responsible for freeing the PGresult via PQclear()
1325 * when done with it.
1328 PQprepare(PGconn *conn,
1329 const char *stmtName, const char *query,
1330 int nParams, const Oid *paramTypes)
1332 if (!PQexecStart(conn))
1334 if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
1336 return PQexecFinish(conn);
1341 * Like PQexec, but execute a previously prepared statement,
1342 * using protocol 3.0 so we can pass parameters
1345 PQexecPrepared(PGconn *conn,
1346 const char *stmtName,
1348 const char *const * paramValues,
1349 const int *paramLengths,
1350 const int *paramFormats,
1353 if (!PQexecStart(conn))
1355 if (!PQsendQueryPrepared(conn, stmtName,
1356 nParams, paramValues, paramLengths,
1357 paramFormats, resultFormat))
1359 return PQexecFinish(conn);
1363 * Common code for PQexec and sibling routines: prepare to send command
1366 PQexecStart(PGconn *conn)
1374 * Silently discard any prior query result that application didn't eat.
1375 * This is probably poor design, but it's here for backward compatibility.
1377 while ((result = PQgetResult(conn)) != NULL)
1379 ExecStatusType resultStatus = result->resultStatus;
1381 PQclear(result); /* only need its status */
1382 if (resultStatus == PGRES_COPY_IN)
1384 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1386 /* In protocol 3, we can get out of a COPY IN state */
1387 if (PQputCopyEnd(conn,
1388 libpq_gettext("COPY terminated by new PQexec")) < 0)
1390 /* keep waiting to swallow the copy's failure message */
1394 /* In older protocols we have to punt */
1395 printfPQExpBuffer(&conn->errorMessage,
1396 libpq_gettext("COPY IN state must be terminated first\n"));
1400 else if (resultStatus == PGRES_COPY_OUT)
1402 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1405 * In protocol 3, we can get out of a COPY OUT state: we just
1406 * switch back to BUSY and allow the remaining COPY data to be
1407 * dropped on the floor.
1409 conn->asyncStatus = PGASYNC_BUSY;
1410 /* keep waiting to swallow the copy's completion message */
1414 /* In older protocols we have to punt */
1415 printfPQExpBuffer(&conn->errorMessage,
1416 libpq_gettext("COPY OUT state must be terminated first\n"));
1420 /* check for loss of connection, too */
1421 if (conn->status == CONNECTION_BAD)
1425 /* OK to send a command */
1430 * Common code for PQexec and sibling routines: wait for command result
1433 PQexecFinish(PGconn *conn)
1436 PGresult *lastResult;
1439 * For backwards compatibility, return the last result if there are more
1440 * than one --- but merge error messages if we get more than one error
1443 * We have to stop if we see copy in/out, however. We will resume parsing
1444 * after application performs the data transfer.
1446 * Also stop if the connection is lost (else we'll loop infinitely).
1449 while ((result = PQgetResult(conn)) != NULL)
1453 if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
1454 result->resultStatus == PGRES_FATAL_ERROR)
1456 pqCatenateResultError(lastResult, result->errMsg);
1458 result = lastResult;
1461 * Make sure PQerrorMessage agrees with concatenated result
1463 resetPQExpBuffer(&conn->errorMessage);
1464 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
1467 PQclear(lastResult);
1469 lastResult = result;
1470 if (result->resultStatus == PGRES_COPY_IN ||
1471 result->resultStatus == PGRES_COPY_OUT ||
1472 conn->status == CONNECTION_BAD)
1480 * PQdescribePrepared
1481 * Obtain information about a previously prepared statement
1483 * If the query was not even sent, return NULL; conn->errorMessage is set to
1484 * a relevant message.
1485 * If the query was sent, a new PGresult is returned (which could indicate
1486 * either success or failure). On success, the PGresult contains status
1487 * PGRES_COMMAND_OK, and its parameter and column-heading fields describe
1488 * the statement's inputs and outputs respectively.
1489 * The user is responsible for freeing the PGresult via PQclear()
1490 * when done with it.
1493 PQdescribePrepared(PGconn *conn, const char *stmt)
1495 if (!PQexecStart(conn))
1497 if (!PQsendDescribe(conn, 'S', stmt))
1499 return PQexecFinish(conn);
1504 * Obtain information about a previously created portal
1506 * This is much like PQdescribePrepared, except that no parameter info is
1507 * returned. Note that at the moment, libpq doesn't really expose portals
1508 * to the client; but this can be used with a portal created by a SQL
1509 * DECLARE CURSOR command.
1512 PQdescribePortal(PGconn *conn, const char *portal)
1514 if (!PQexecStart(conn))
1516 if (!PQsendDescribe(conn, 'P', portal))
1518 return PQexecFinish(conn);
1522 * PQsendDescribePrepared
1523 * Submit a Describe Statement command, but don't wait for it to finish
1525 * Returns: 1 if successfully submitted
1526 * 0 if error (conn->errorMessage is set)
1529 PQsendDescribePrepared(PGconn *conn, const char *stmt)
1531 return PQsendDescribe(conn, 'S', stmt);
1535 * PQsendDescribePortal
1536 * Submit a Describe Portal command, but don't wait for it to finish
1538 * Returns: 1 if successfully submitted
1539 * 0 if error (conn->errorMessage is set)
1542 PQsendDescribePortal(PGconn *conn, const char *portal)
1544 return PQsendDescribe(conn, 'P', portal);
1549 * Common code to send a Describe command
1551 * Available options for desc_type are
1552 * 'S' to describe a prepared statement; or
1553 * 'P' to describe a portal.
1554 * Returns 1 on success and 0 on failure.
1557 PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
1559 /* Treat null desc_target as empty string */
1563 if (!PQsendQueryStart(conn))
1566 /* This isn't gonna work on a 2.0 server */
1567 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1569 printfPQExpBuffer(&conn->errorMessage,
1570 libpq_gettext("function requires at least protocol version 3.0\n"));
1574 /* construct the Describe message */
1575 if (pqPutMsgStart('D', false, conn) < 0 ||
1576 pqPutc(desc_type, conn) < 0 ||
1577 pqPuts(desc_target, conn) < 0 ||
1578 pqPutMsgEnd(conn) < 0)
1581 /* construct the Sync message */
1582 if (pqPutMsgStart('S', false, conn) < 0 ||
1583 pqPutMsgEnd(conn) < 0)
1586 /* remember we are doing a Describe */
1587 conn->queryclass = PGQUERY_DESCRIBE;
1589 /* reset last-query string (not relevant now) */
1590 if (conn->last_query)
1592 free(conn->last_query);
1593 conn->last_query = NULL;
1597 * Give the data a push. In nonblock mode, don't complain if we're unable
1598 * to send it all; PQgetResult() will do any additional flushing needed.
1600 if (pqFlush(conn) < 0)
1603 /* OK, it's launched! */
1604 conn->asyncStatus = PGASYNC_BUSY;
1608 pqHandleSendFailure(conn);
1614 * returns a PGnotify* structure of the latest async notification
1615 * that has not yet been handled
1617 * returns NULL, if there is currently
1618 * no unhandled async notification from the backend
1620 * the CALLER is responsible for FREE'ing the structure returned
1623 PQnotifies(PGconn *conn)
1630 /* Parse any available data to see if we can extract NOTIFY messages. */
1633 event = conn->notifyHead;
1636 conn->notifyHead = event->next;
1637 if (!conn->notifyHead)
1638 conn->notifyTail = NULL;
1639 event->next = NULL; /* don't let app see the internal state */
1645 * PQputCopyData - send some data to the backend during COPY IN
1647 * Returns 1 if successful, 0 if data could not be sent (only possible
1648 * in nonblock mode), or -1 if an error occurs.
1651 PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
1655 if (conn->asyncStatus != PGASYNC_COPY_IN)
1657 printfPQExpBuffer(&conn->errorMessage,
1658 libpq_gettext("no COPY in progress\n"));
1663 * Process any NOTICE or NOTIFY messages that might be pending in the
1664 * input buffer. Since the server might generate many notices during
1665 * the COPY, we want to clean those out reasonably promptly to prevent
1666 * indefinite expansion of the input buffer. (Note: the actual read
1667 * of input data into the input buffer happens down inside pqSendSome,
1668 * but it's not authorized to get rid of the data again.)
1675 * Try to flush any previously sent data in preference to growing the
1676 * output buffer. If we can't enlarge the buffer enough to hold the
1677 * data, return 0 in the nonblock case, else hard error. (For
1678 * simplicity, always assume 5 bytes of overhead even in protocol 2.0
1681 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
1683 if (pqFlush(conn) < 0)
1685 if (pqCheckOutBufferSpace(conn->outCount + 5 + nbytes, conn))
1686 return pqIsnonblocking(conn) ? 0 : -1;
1688 /* Send the data (too simple to delegate to fe-protocol files) */
1689 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1691 if (pqPutMsgStart('d', false, conn) < 0 ||
1692 pqPutnchar(buffer, nbytes, conn) < 0 ||
1693 pqPutMsgEnd(conn) < 0)
1698 if (pqPutMsgStart(0, false, conn) < 0 ||
1699 pqPutnchar(buffer, nbytes, conn) < 0 ||
1700 pqPutMsgEnd(conn) < 0)
1708 * PQputCopyEnd - send EOF indication to the backend during COPY IN
1710 * After calling this, use PQgetResult() to check command completion status.
1712 * Returns 1 if successful, 0 if data could not be sent (only possible
1713 * in nonblock mode), or -1 if an error occurs.
1716 PQputCopyEnd(PGconn *conn, const char *errormsg)
1720 if (conn->asyncStatus != PGASYNC_COPY_IN)
1722 printfPQExpBuffer(&conn->errorMessage,
1723 libpq_gettext("no COPY in progress\n"));
1728 * Send the COPY END indicator. This is simple enough that we don't
1729 * bother delegating it to the fe-protocol files.
1731 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1735 /* Send COPY FAIL */
1736 if (pqPutMsgStart('f', false, conn) < 0 ||
1737 pqPuts(errormsg, conn) < 0 ||
1738 pqPutMsgEnd(conn) < 0)
1743 /* Send COPY DONE */
1744 if (pqPutMsgStart('c', false, conn) < 0 ||
1745 pqPutMsgEnd(conn) < 0)
1750 * If we sent the COPY command in extended-query mode, we must issue a
1753 if (conn->queryclass != PGQUERY_SIMPLE)
1755 if (pqPutMsgStart('S', false, conn) < 0 ||
1756 pqPutMsgEnd(conn) < 0)
1764 /* Ooops, no way to do this in 2.0 */
1765 printfPQExpBuffer(&conn->errorMessage,
1766 libpq_gettext("function requires at least protocol version 3.0\n"));
1771 /* Send old-style end-of-data marker */
1772 if (pqPutMsgStart(0, false, conn) < 0 ||
1773 pqPutnchar("\\.\n", 3, conn) < 0 ||
1774 pqPutMsgEnd(conn) < 0)
1779 /* Return to active duty */
1780 conn->asyncStatus = PGASYNC_BUSY;
1781 resetPQExpBuffer(&conn->errorMessage);
1783 /* Try to flush data */
1784 if (pqFlush(conn) < 0)
1791 * PQgetCopyData - read a row of data from the backend during COPY OUT
1793 * If successful, sets *buffer to point to a malloc'd row of data, and
1794 * returns row length (always > 0) as result.
1795 * Returns 0 if no row available yet (only possible if async is true),
1796 * -1 if end of copy (consult PQgetResult), or -2 if error (consult
1800 PQgetCopyData(PGconn *conn, char **buffer, int async)
1802 *buffer = NULL; /* for all failure cases */
1805 if (conn->asyncStatus != PGASYNC_COPY_OUT)
1807 printfPQExpBuffer(&conn->errorMessage,
1808 libpq_gettext("no COPY in progress\n"));
1811 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1812 return pqGetCopyData3(conn, buffer, async);
1814 return pqGetCopyData2(conn, buffer, async);
1818 * PQgetline - gets a newline-terminated string from the backend.
1820 * Chiefly here so that applications can use "COPY <rel> to stdout"
1821 * and read the output string. Returns a null-terminated string in s.
1823 * XXX this routine is now deprecated, because it can't handle binary data.
1824 * If called during a COPY BINARY we return EOF.
1826 * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
1827 * the terminating \n (like gets(3)).
1829 * CAUTION: the caller is responsible for detecting the end-of-copy signal
1830 * (a line containing just "\.") when using this routine.
1833 * EOF if error (eg, invalid arguments are given)
1834 * 0 if EOL is reached (i.e., \n has been read)
1835 * (this is required for backward-compatibility -- this
1836 * routine used to always return EOF or 0, assuming that
1837 * the line ended within maxlen bytes.)
1838 * 1 in other cases (i.e., the buffer was filled before \n is reached)
1841 PQgetline(PGconn *conn, char *s, int maxlen)
1843 if (!s || maxlen <= 0)
1846 /* maxlen must be at least 3 to hold the \. terminator! */
1853 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1854 return pqGetline3(conn, s, maxlen);
1856 return pqGetline2(conn, s, maxlen);
1860 * PQgetlineAsync - gets a COPY data row without blocking.
1862 * This routine is for applications that want to do "COPY <rel> to stdout"
1863 * asynchronously, that is without blocking. Having issued the COPY command
1864 * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
1865 * and this routine until the end-of-data signal is detected. Unlike
1866 * PQgetline, this routine takes responsibility for detecting end-of-data.
1868 * On each call, PQgetlineAsync will return data if a complete data row
1869 * is available in libpq's input buffer. Otherwise, no data is returned
1870 * until the rest of the row arrives.
1872 * If -1 is returned, the end-of-data signal has been recognized (and removed
1873 * from libpq's input buffer). The caller *must* next call PQendcopy and
1874 * then return to normal processing.
1877 * -1 if the end-of-copy-data marker has been recognized
1878 * 0 if no data is available
1879 * >0 the number of bytes returned.
1881 * The data returned will not extend beyond a data-row boundary. If possible
1882 * a whole row will be returned at one time. But if the buffer offered by
1883 * the caller is too small to hold a row sent by the backend, then a partial
1884 * data row will be returned. In text mode this can be detected by testing
1885 * whether the last returned byte is '\n' or not.
1887 * The returned data is *not* null-terminated.
1891 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
1896 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1897 return pqGetlineAsync3(conn, buffer, bufsize);
1899 return pqGetlineAsync2(conn, buffer, bufsize);
1903 * PQputline -- sends a string to the backend during COPY IN.
1904 * Returns 0 if OK, EOF if not.
1906 * This is deprecated primarily because the return convention doesn't allow
1907 * caller to tell the difference between a hard error and a nonblock-mode
1911 PQputline(PGconn *conn, const char *s)
1913 return PQputnbytes(conn, s, strlen(s));
1917 * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
1918 * Returns 0 if OK, EOF if not.
1921 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
1923 if (PQputCopyData(conn, buffer, nbytes) > 0)
1931 * After completing the data transfer portion of a copy in/out,
1932 * the application must call this routine to finish the command protocol.
1934 * When using protocol 3.0 this is deprecated; it's cleaner to use PQgetResult
1935 * to get the transfer status. Note however that when using 2.0 protocol,
1936 * recovering from a copy failure often requires a PQreset. PQendcopy will
1937 * take care of that, PQgetResult won't.
1944 PQendcopy(PGconn *conn)
1949 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1950 return pqEndcopy3(conn);
1952 return pqEndcopy2(conn);
1957 * PQfn - Send a function call to the POSTGRES backend.
1959 * conn : backend connection
1960 * fnid : function id
1961 * result_buf : pointer to result buffer (&int if integer)
1962 * result_len : length of return value.
1963 * actual_result_len: actual length returned. (differs from result_len
1964 * for varlena structures.)
1965 * result_type : If the result is an integer, this must be 1,
1966 * otherwise this should be 0
1967 * args : pointer to an array of function arguments.
1968 * (each has length, if integer, and value/pointer)
1969 * nargs : # of arguments in args array.
1972 * PGresult with status = PGRES_COMMAND_OK if successful.
1973 * *actual_result_len is > 0 if there is a return value, 0 if not.
1974 * PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
1975 * NULL on communications failure. conn->errorMessage will be set.
1983 int *actual_result_len,
1985 const PQArgBlock *args,
1988 *actual_result_len = 0;
1993 /* clear the error string */
1994 resetPQExpBuffer(&conn->errorMessage);
1996 if (conn->sock < 0 || conn->asyncStatus != PGASYNC_IDLE ||
1997 conn->result != NULL)
1999 printfPQExpBuffer(&conn->errorMessage,
2000 libpq_gettext("connection in wrong state\n"));
2004 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2005 return pqFunctionCall3(conn, fnid,
2006 result_buf, actual_result_len,
2010 return pqFunctionCall2(conn, fnid,
2011 result_buf, actual_result_len,
2017 /* ====== accessor funcs for PGresult ======== */
2020 PQresultStatus(const PGresult *res)
2023 return PGRES_FATAL_ERROR;
2024 return res->resultStatus;
2028 PQresStatus(ExecStatusType status)
2030 if (status < 0 || status >= sizeof pgresStatus / sizeof pgresStatus[0])
2031 return libpq_gettext("invalid ExecStatusType code");
2032 return pgresStatus[status];
2036 PQresultErrorMessage(const PGresult *res)
2038 if (!res || !res->errMsg)
2044 PQresultErrorField(const PGresult *res, int fieldcode)
2046 PGMessageField *pfield;
2050 for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
2052 if (pfield->code == fieldcode)
2053 return pfield->contents;
2059 PQntuples(const PGresult *res)
2067 PQnfields(const PGresult *res)
2071 return res->numAttributes;
2075 PQbinaryTuples(const PGresult *res)
2083 * Helper routines to range-check field numbers and tuple numbers.
2084 * Return TRUE if OK, FALSE if not
2088 check_field_number(const PGresult *res, int field_num)
2091 return FALSE; /* no way to display error message... */
2092 if (field_num < 0 || field_num >= res->numAttributes)
2094 pqInternalNotice(&res->noticeHooks,
2095 "column number %d is out of range 0..%d",
2096 field_num, res->numAttributes - 1);
2103 check_tuple_field_number(const PGresult *res,
2104 int tup_num, int field_num)
2107 return FALSE; /* no way to display error message... */
2108 if (tup_num < 0 || tup_num >= res->ntups)
2110 pqInternalNotice(&res->noticeHooks,
2111 "row number %d is out of range 0..%d",
2112 tup_num, res->ntups - 1);
2115 if (field_num < 0 || field_num >= res->numAttributes)
2117 pqInternalNotice(&res->noticeHooks,
2118 "column number %d is out of range 0..%d",
2119 field_num, res->numAttributes - 1);
2126 check_param_number(const PGresult *res, int param_num)
2129 return FALSE; /* no way to display error message... */
2130 if (param_num < 0 || param_num >= res->numParameters)
2132 pqInternalNotice(&res->noticeHooks,
2133 "parameter number %d is out of range 0..%d",
2134 param_num, res->numParameters - 1);
2142 * returns NULL if the field_num is invalid
2145 PQfname(const PGresult *res, int field_num)
2147 if (!check_field_number(res, field_num))
2150 return res->attDescs[field_num].name;
2156 * PQfnumber: find column number given column name
2158 * The column name is parsed as if it were in a SQL statement, including
2159 * case-folding and double-quote processing. But note a possible gotcha:
2160 * downcasing in the frontend might follow different locale rules than
2161 * downcasing in the backend...
2163 * Returns -1 if no match. In the present backend it is also possible
2164 * to have multiple matches, in which case the first one is found.
2167 PQfnumber(const PGresult *res, const char *field_name)
2179 * Note: it is correct to reject a zero-length input string; the proper
2180 * input to match a zero-length field name would be "".
2182 if (field_name == NULL ||
2183 field_name[0] == '\0' ||
2184 res->attDescs == NULL)
2188 * Note: this code will not reject partially quoted strings, eg
2189 * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
2192 field_case = strdup(field_name);
2193 if (field_case == NULL)
2194 return -1; /* grotty */
2198 for (iptr = field_case; *iptr; iptr++)
2208 /* doubled quotes become a single quote */
2222 c = pg_tolower((unsigned char) c);
2228 for (i = 0; i < res->numAttributes; i++)
2230 if (strcmp(field_case, res->attDescs[i].name) == 0)
2241 PQftable(const PGresult *res, int field_num)
2243 if (!check_field_number(res, field_num))
2246 return res->attDescs[field_num].tableid;
2252 PQftablecol(const PGresult *res, int field_num)
2254 if (!check_field_number(res, field_num))
2257 return res->attDescs[field_num].columnid;
2263 PQfformat(const PGresult *res, int field_num)
2265 if (!check_field_number(res, field_num))
2268 return res->attDescs[field_num].format;
2274 PQftype(const PGresult *res, int field_num)
2276 if (!check_field_number(res, field_num))
2279 return res->attDescs[field_num].typid;
2285 PQfsize(const PGresult *res, int field_num)
2287 if (!check_field_number(res, field_num))
2290 return res->attDescs[field_num].typlen;
2296 PQfmod(const PGresult *res, int field_num)
2298 if (!check_field_number(res, field_num))
2301 return res->attDescs[field_num].atttypmod;
2307 PQcmdStatus(PGresult *res)
2311 return res->cmdStatus;
2316 * if the last command was an INSERT, return the oid string
2320 PQoidStatus(const PGresult *res)
2323 * This must be enough to hold the result. Don't laugh, this is better
2324 * than what this function used to do.
2326 static char buf[24];
2330 if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2333 len = strspn(res->cmdStatus + 7, "0123456789");
2336 strncpy(buf, res->cmdStatus + 7, len);
2344 * a perhaps preferable form of the above which just returns
2348 PQoidValue(const PGresult *res)
2350 char *endptr = NULL;
2351 unsigned long result;
2355 strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
2356 res->cmdStatus[7] < '0' ||
2357 res->cmdStatus[7] > '9')
2360 result = strtoul(res->cmdStatus + 7, &endptr, 10);
2362 if (!endptr || (*endptr != ' ' && *endptr != '\0'))
2365 return (Oid) result;
2371 * If the last command was INSERT/UPDATE/DELETE/MOVE/FETCH/COPY, return
2372 * a string containing the number of inserted/affected tuples. If not,
2375 * XXX: this should probably return an int
2378 PQcmdTuples(PGresult *res)
2385 if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
2387 p = res->cmdStatus + 7;
2388 /* INSERT: skip oid and space */
2389 while (*p && *p != ' ')
2392 goto interpret_error; /* no space? */
2395 else if (strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
2396 strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
2397 p = res->cmdStatus + 7;
2398 else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
2399 p = res->cmdStatus + 6;
2400 else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
2401 strncmp(res->cmdStatus, "COPY ", 5) == 0)
2402 p = res->cmdStatus + 5;
2406 /* check that we have an integer (at least one digit, nothing else) */
2407 for (c = p; *c; c++)
2409 if (!isdigit((unsigned char) *c))
2410 goto interpret_error;
2413 goto interpret_error;
2418 pqInternalNotice(&res->noticeHooks,
2419 "could not interpret result from server: %s",
2426 * return the value of field 'field_num' of row 'tup_num'
2429 PQgetvalue(const PGresult *res, int tup_num, int field_num)
2431 if (!check_tuple_field_number(res, tup_num, field_num))
2433 return res->tuples[tup_num][field_num].value;
2437 * returns the actual length of a field value in bytes.
2440 PQgetlength(const PGresult *res, int tup_num, int field_num)
2442 if (!check_tuple_field_number(res, tup_num, field_num))
2444 if (res->tuples[tup_num][field_num].len != NULL_LEN)
2445 return res->tuples[tup_num][field_num].len;
2451 * returns the null status of a field value.
2454 PQgetisnull(const PGresult *res, int tup_num, int field_num)
2456 if (!check_tuple_field_number(res, tup_num, field_num))
2457 return 1; /* pretend it is null */
2458 if (res->tuples[tup_num][field_num].len == NULL_LEN)
2465 * returns the number of input parameters of a prepared statement.
2468 PQnparams(const PGresult *res)
2472 return res->numParameters;
2476 * returns type Oid of the specified statement parameter.
2479 PQparamtype(const PGresult *res, int param_num)
2481 if (!check_param_number(res, param_num))
2483 if (res->paramDescs)
2484 return res->paramDescs[param_num].typid;
2490 /* PQsetnonblocking:
2491 * sets the PGconn's database connection non-blocking if the arg is TRUE
2492 * or makes it non-blocking if the arg is FALSE, this will not protect
2493 * you from PQexec(), you'll only be safe when using the non-blocking API.
2494 * Needs to be called only on a connected database connection.
2497 PQsetnonblocking(PGconn *conn, int arg)
2501 if (!conn || conn->status == CONNECTION_BAD)
2504 barg = (arg ? TRUE : FALSE);
2506 /* early out if the socket is already in the state requested */
2507 if (barg == conn->nonblocking)
2511 * to guarantee constancy for flushing/query/result-polling behavior we
2512 * need to flush the send queue at this point in order to guarantee proper
2513 * behavior. this is ok because either they are making a transition _from_
2514 * or _to_ blocking mode, either way we can block them.
2516 /* if we are going from blocking to non-blocking flush here */
2520 conn->nonblocking = barg;
2526 * return the blocking status of the database connection
2527 * TRUE == nonblocking, FALSE == blocking
2530 PQisnonblocking(const PGconn *conn)
2532 return pqIsnonblocking(conn);
2535 /* libpq is thread-safe? */
2537 PQisthreadsafe(void)
2539 #ifdef ENABLE_THREAD_SAFETY
2547 /* try to force data out, really only useful for non-blocking users */
2549 PQflush(PGconn *conn)
2551 return pqFlush(conn);
2556 * PQfreemem - safely frees memory allocated
2558 * Needed mostly by Win32, unless multithreaded DLL (/MD in VC6)
2559 * Used for freeing memory from PQescapeByte()a/PQunescapeBytea()
2562 PQfreemem(void *ptr)
2568 * PQfreeNotify - free's the memory associated with a PGnotify
2570 * This function is here only for binary backward compatibility.
2571 * New code should use PQfreemem(). A macro will automatically map
2572 * calls to PQfreemem. It should be removed in the future. bjm 2003-03-24
2576 void PQfreeNotify(PGnotify *notify);
2579 PQfreeNotify(PGnotify *notify)
2586 * Escaping arbitrary strings to get valid SQL literal strings.
2588 * Replaces "'" with "''", and if not std_strings, replaces "\" with "\\".
2590 * length is the length of the source string. (Note: if a terminating NUL
2591 * is encountered sooner, PQescapeString stops short of "length"; the behavior
2592 * is thus rather like strncpy.)
2594 * For safety the buffer at "to" must be at least 2*length + 1 bytes long.
2595 * A terminating NUL character is added to the output string, whether the
2596 * input is NUL-terminated or not.
2598 * Returns the actual length of the output (not counting the terminating NUL).
2601 PQescapeStringInternal(PGconn *conn,
2602 char *to, const char *from, size_t length,
2604 int encoding, bool std_strings)
2606 const char *source = from;
2608 size_t remaining = length;
2613 while (remaining > 0 && *source != '\0')
2619 /* Fast path for plain ASCII */
2620 if (!IS_HIGHBIT_SET(c))
2622 /* Apply quoting if needed */
2623 if (SQL_STR_DOUBLE(c, !std_strings))
2625 /* Copy the character */
2632 /* Slow path for possible multibyte characters */
2633 len = pg_encoding_mblen(encoding, source);
2635 /* Copy the character */
2636 for (i = 0; i < len; i++)
2638 if (remaining == 0 || *source == '\0')
2640 *target++ = *source++;
2645 * If we hit premature end of string (ie, incomplete multibyte
2646 * character), try to pad out to the correct length with spaces.
2647 * We may not be able to pad completely, but we will always be able
2648 * to insert at least one pad space (since we'd not have quoted a
2649 * multibyte character). This should be enough to make a string that
2650 * the server will error out on.
2657 printfPQExpBuffer(&conn->errorMessage,
2658 libpq_gettext("incomplete multibyte character\n"));
2659 for (; i < len; i++)
2661 if (((size_t) (target - to)) / 2 >= length)
2669 /* Write the terminating NUL character. */
2676 PQescapeStringConn(PGconn *conn,
2677 char *to, const char *from, size_t length,
2682 /* force empty-string result */
2688 return PQescapeStringInternal(conn, to, from, length, error,
2689 conn->client_encoding,
2694 PQescapeString(char *to, const char *from, size_t length)
2696 return PQescapeStringInternal(NULL, to, from, length, NULL,
2697 static_client_encoding,
2698 static_std_strings);
2702 * PQescapeBytea - converts from binary string to the
2703 * minimal encoding necessary to include the string in an SQL
2704 * INSERT statement with a bytea type column as the target.
2706 * The following transformations are applied
2707 * '\0' == ASCII 0 == \000
2708 * '\'' == ASCII 39 == ''
2709 * '\\' == ASCII 92 == \\
2710 * anything < 0x20, or > 0x7e ---> \ooo
2711 * (where ooo is an octal expression)
2712 * If not std_strings, all backslashes sent to the output are doubled.
2714 static unsigned char *
2715 PQescapeByteaInternal(PGconn *conn,
2716 const unsigned char *from, size_t from_length,
2717 size_t *to_length, bool std_strings)
2719 const unsigned char *vp;
2721 unsigned char *result;
2724 size_t bslash_len = (std_strings ? 1 : 2);
2727 * empty string has 1 char ('\0')
2732 for (i = from_length; i > 0; i--, vp++)
2734 if (*vp < 0x20 || *vp > 0x7e)
2735 len += bslash_len + 3;
2736 else if (*vp == '\'')
2738 else if (*vp == '\\')
2739 len += bslash_len + bslash_len;
2745 rp = result = (unsigned char *) malloc(len);
2749 printfPQExpBuffer(&conn->errorMessage,
2750 libpq_gettext("out of memory\n"));
2755 for (i = from_length; i > 0; i--, vp++)
2757 if (*vp < 0x20 || *vp > 0x7e)
2761 (void) sprintf((char *) rp, "\\%03o", *vp);
2764 else if (*vp == '\'')
2769 else if (*vp == '\\')
2788 PQescapeByteaConn(PGconn *conn,
2789 const unsigned char *from, size_t from_length,
2794 return PQescapeByteaInternal(conn, from, from_length, to_length,
2799 PQescapeBytea(const unsigned char *from, size_t from_length, size_t *to_length)
2801 return PQescapeByteaInternal(NULL, from, from_length, to_length,
2802 static_std_strings);
2806 #define ISFIRSTOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '3')
2807 #define ISOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '7')
2808 #define OCTVAL(CH) ((CH) - '0')
2811 * PQunescapeBytea - converts the null terminated string representation
2812 * of a bytea, strtext, into binary, filling a buffer. It returns a
2813 * pointer to the buffer (or NULL on error), and the size of the
2814 * buffer in retbuflen. The pointer may subsequently be used as an
2815 * argument to the function PQfreemem.
2817 * The following transformations are made:
2818 * \\ == ASCII 92 == \
2819 * \ooo == a byte whose value = ooo (ooo is an octal number)
2820 * \x == x (x is any character not matched by the above transformations)
2823 PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
2827 unsigned char *buffer,
2832 if (strtext == NULL)
2835 strtextlen = strlen((const char *) strtext);
2838 * Length of input is max length of output, but add one to avoid
2839 * unportable malloc(0) if input is zero-length.
2841 buffer = (unsigned char *) malloc(strtextlen + 1);
2845 for (i = j = 0; i < strtextlen;)
2851 if (strtext[i] == '\\')
2852 buffer[j++] = strtext[i++];
2855 if ((ISFIRSTOCTDIGIT(strtext[i])) &&
2856 (ISOCTDIGIT(strtext[i + 1])) &&
2857 (ISOCTDIGIT(strtext[i + 2])))
2861 byte = OCTVAL(strtext[i++]);
2862 byte = (byte << 3) + OCTVAL(strtext[i++]);
2863 byte = (byte << 3) + OCTVAL(strtext[i++]);
2869 * Note: if we see '\' followed by something that isn't a
2870 * recognized escape sequence, we loop around having done
2871 * nothing except advance i. Therefore the something will be
2872 * emitted as ordinary data on the next cycle. Corner case:
2873 * '\' at end of string will just be discarded.
2878 buffer[j++] = strtext[i++];
2882 buflen = j; /* buflen is the length of the dequoted data */
2884 /* Shrink the buffer to be no larger than necessary */
2885 /* +1 avoids unportable behavior when buflen==0 */
2886 tmpbuf = realloc(buffer, buflen + 1);
2888 /* It would only be a very brain-dead realloc that could fail, but... */
2895 *retbuflen = buflen;