1 /*-------------------------------------------------------------------------
4 * functions related to sending a query down to the backend
6 * Portions Copyright (c) 1996-2005, 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.173 2005/08/23 20:48:47 momjian Exp $
13 *-------------------------------------------------------------------------
15 #include "postgres_fe.h"
22 #include "libpq-int.h"
24 #include "mb/pg_wchar.h"
32 /* keep this in same order as ExecStatusType in libpq-fe.h */
33 char *const pgresStatus[] = {
40 "PGRES_NONFATAL_ERROR",
46 static bool PQsendQueryStart(PGconn *conn);
47 static int PQsendQueryGuts(PGconn *conn,
51 const Oid *paramTypes,
52 const char *const * paramValues,
53 const int *paramLengths,
54 const int *paramFormats,
56 static void parseInput(PGconn *conn);
57 static bool PQexecStart(PGconn *conn);
58 static PGresult *PQexecFinish(PGconn *conn);
62 * Space management for PGresult.
64 * Formerly, libpq did a separate malloc() for each field of each tuple
65 * returned by a query. This was remarkably expensive --- malloc/free
66 * consumed a sizable part of the application's runtime. And there is
67 * no real need to keep track of the fields separately, since they will
68 * all be freed together when the PGresult is released. So now, we grab
69 * large blocks of storage from malloc and allocate space for query data
70 * within these blocks, using a trivially simple allocator. This reduces
71 * the number of malloc/free calls dramatically, and it also avoids
72 * fragmentation of the malloc storage arena.
73 * The PGresult structure itself is still malloc'd separately. We could
74 * combine it with the first allocation block, but that would waste space
75 * for the common case that no extra storage is actually needed (that is,
76 * the SQL command did not return tuples).
78 * We also malloc the top-level array of tuple pointers separately, because
79 * we need to be able to enlarge it via realloc, and our trivial space
80 * allocator doesn't handle that effectively. (Too bad the FE/BE protocol
81 * doesn't tell us up front how many tuples will be returned.)
82 * All other subsidiary storage for a PGresult is kept in PGresult_data blocks
83 * of size PGRESULT_DATA_BLOCKSIZE. The overhead at the start of each block
84 * is just a link to the next one, if any. Free-space management info is
85 * kept in the owning PGresult.
86 * A query returning a small amount of data will thus require three malloc
87 * calls: one for the PGresult, one for the tuples pointer array, and one
88 * PGresult_data block.
90 * Only the most recently allocated PGresult_data block is a candidate to
91 * have more stuff added to it --- any extra space left over in older blocks
92 * is wasted. We could be smarter and search the whole chain, but the point
93 * here is to be simple and fast. Typical applications do not keep a PGresult
94 * around very long anyway, so some wasted space within one is not a problem.
96 * Tuning constants for the space allocator are:
97 * PGRESULT_DATA_BLOCKSIZE: size of a standard allocation block, in bytes
98 * PGRESULT_ALIGN_BOUNDARY: assumed alignment requirement for binary data
99 * PGRESULT_SEP_ALLOC_THRESHOLD: objects bigger than this are given separate
100 * blocks, instead of being crammed into a regular allocation block.
101 * Requirements for correct function are:
102 * PGRESULT_ALIGN_BOUNDARY must be a multiple of the alignment requirements
103 * of all machine data types. (Currently this is set from configure
104 * tests, so it should be OK automatically.)
105 * PGRESULT_SEP_ALLOC_THRESHOLD + PGRESULT_BLOCK_OVERHEAD <=
106 * PGRESULT_DATA_BLOCKSIZE
107 * pqResultAlloc assumes an object smaller than the threshold will fit
109 * The amount of space wasted at the end of a block could be as much as
110 * PGRESULT_SEP_ALLOC_THRESHOLD, so it doesn't pay to make that too large.
114 #define PGRESULT_DATA_BLOCKSIZE 2048
115 #define PGRESULT_ALIGN_BOUNDARY MAXIMUM_ALIGNOF /* from configure */
116 #define PGRESULT_BLOCK_OVERHEAD Max(sizeof(PGresult_data), PGRESULT_ALIGN_BOUNDARY)
117 #define PGRESULT_SEP_ALLOC_THRESHOLD (PGRESULT_DATA_BLOCKSIZE / 2)
121 * PQmakeEmptyPGresult
122 * returns a newly allocated, initialized PGresult with given status.
123 * If conn is not NULL and status indicates an error, the conn's
124 * errorMessage is copied.
126 * Note this is exported --- you wouldn't think an application would need
127 * to build its own PGresults, but this has proven useful in both libpgtcl
128 * and the Perl5 interface, so maybe it's not so unreasonable.
132 PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
136 result = (PGresult *) malloc(sizeof(PGresult));
141 result->numAttributes = 0;
142 result->attDescs = NULL;
143 result->tuples = NULL;
144 result->tupArrSize = 0;
145 result->resultStatus = status;
146 result->cmdStatus[0] = '\0';
148 result->errMsg = NULL;
149 result->errFields = NULL;
150 result->null_field[0] = '\0';
151 result->curBlock = NULL;
152 result->curOffset = 0;
153 result->spaceLeft = 0;
157 /* copy connection data we might need for operations on PGresult */
158 result->noticeHooks = conn->noticeHooks;
159 result->client_encoding = conn->client_encoding;
161 /* consider copying conn's errorMessage */
164 case PGRES_EMPTY_QUERY:
165 case PGRES_COMMAND_OK:
166 case PGRES_TUPLES_OK:
169 /* non-error cases */
172 pqSetResultError(result, conn->errorMessage.data);
179 result->noticeHooks.noticeRec = NULL;
180 result->noticeHooks.noticeRecArg = NULL;
181 result->noticeHooks.noticeProc = NULL;
182 result->noticeHooks.noticeProcArg = NULL;
183 result->client_encoding = PG_SQL_ASCII;
191 * Allocate subsidiary storage for a PGresult.
193 * nBytes is the amount of space needed for the object.
194 * If isBinary is true, we assume that we need to align the object on
195 * a machine allocation boundary.
196 * If isBinary is false, we assume the object is a char string and can
197 * be allocated on any byte boundary.
200 pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
203 PGresult_data *block;
209 return res->null_field;
212 * If alignment is needed, round up the current position to an
213 * alignment boundary.
217 int offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
221 res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
222 res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
226 /* If there's enough space in the current block, no problem. */
227 if (nBytes <= (size_t) res->spaceLeft)
229 space = res->curBlock->space + res->curOffset;
230 res->curOffset += nBytes;
231 res->spaceLeft -= nBytes;
236 * If the requested object is very large, give it its own block; this
237 * avoids wasting what might be most of the current block to start a
238 * new block. (We'd have to special-case requests bigger than the
239 * block size anyway.) The object is always given binary alignment in
242 if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
244 block = (PGresult_data *) malloc(nBytes + PGRESULT_BLOCK_OVERHEAD);
247 space = block->space + PGRESULT_BLOCK_OVERHEAD;
251 * Tuck special block below the active block, so that we don't
252 * have to waste the free space in the active block.
254 block->next = res->curBlock->next;
255 res->curBlock->next = block;
259 /* Must set up the new block as the first active block. */
261 res->curBlock = block;
262 res->spaceLeft = 0; /* be sure it's marked full */
267 /* Otherwise, start a new block. */
268 block = (PGresult_data *) malloc(PGRESULT_DATA_BLOCKSIZE);
271 block->next = res->curBlock;
272 res->curBlock = block;
275 /* object needs full alignment */
276 res->curOffset = PGRESULT_BLOCK_OVERHEAD;
277 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - PGRESULT_BLOCK_OVERHEAD;
281 /* we can cram it right after the overhead pointer */
282 res->curOffset = sizeof(PGresult_data);
283 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - sizeof(PGresult_data);
286 space = block->space + res->curOffset;
287 res->curOffset += nBytes;
288 res->spaceLeft -= nBytes;
294 * Like strdup, but the space is subsidiary PGresult space.
297 pqResultStrdup(PGresult *res, const char *str)
299 char *space = (char *) pqResultAlloc(res, strlen(str) + 1, FALSE);
308 * assign a new error message to a PGresult
311 pqSetResultError(PGresult *res, const char *msg)
316 res->errMsg = pqResultStrdup(res, msg);
322 * pqCatenateResultError -
323 * concatenate a new error message to the one already in a PGresult
326 pqCatenateResultError(PGresult *res, const char *msg)
328 PQExpBufferData errorBuf;
332 initPQExpBuffer(&errorBuf);
334 appendPQExpBufferStr(&errorBuf, res->errMsg);
335 appendPQExpBufferStr(&errorBuf, msg);
336 pqSetResultError(res, errorBuf.data);
337 termPQExpBuffer(&errorBuf);
342 * free's the memory associated with a PGresult
345 PQclear(PGresult *res)
347 PGresult_data *block;
352 /* Free all the subsidiary blocks */
353 while ((block = res->curBlock) != NULL)
355 res->curBlock = block->next;
359 /* Free the top-level tuple pointer array */
363 /* Free the PGresult structure itself */
368 * Handy subroutine to deallocate any partially constructed async result.
372 pqClearAsyncResult(PGconn *conn)
375 PQclear(conn->result);
377 conn->curTuple = NULL;
381 * This subroutine deletes any existing async result, sets conn->result
382 * to a PGresult with status PGRES_FATAL_ERROR, and stores the current
383 * contents of conn->errorMessage into that result. It differs from a
384 * plain call on PQmakeEmptyPGresult() in that if there is already an
385 * async result with status PGRES_FATAL_ERROR, the current error message
386 * is APPENDED to the old error message instead of replacing it. This
387 * behavior lets us report multiple error conditions properly, if necessary.
388 * (An example where this is needed is when the backend sends an 'E' message
389 * and immediately closes the connection --- we want to report both the
390 * backend error and the connection closure error.)
393 pqSaveErrorResult(PGconn *conn)
396 * If no old async result, just let PQmakeEmptyPGresult make one.
397 * Likewise if old result is not an error message.
399 if (conn->result == NULL ||
400 conn->result->resultStatus != PGRES_FATAL_ERROR ||
401 conn->result->errMsg == NULL)
403 pqClearAsyncResult(conn);
404 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
408 /* Else, concatenate error message to existing async result. */
409 pqCatenateResultError(conn->result, conn->errorMessage.data);
414 * This subroutine prepares an async result object for return to the caller.
415 * If there is not already an async result object, build an error object
416 * using whatever is in conn->errorMessage. In any case, clear the async
417 * result storage and make sure PQerrorMessage will agree with the result's
421 pqPrepareAsyncResult(PGconn *conn)
426 * conn->result is the PGresult to return. If it is NULL (which
427 * probably shouldn't happen) we assume there is an appropriate error
428 * message in conn->errorMessage.
431 conn->result = NULL; /* handing over ownership to caller */
432 conn->curTuple = NULL; /* just in case */
434 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
438 * Make sure PQerrorMessage agrees with result; it could be
439 * different if we have concatenated messages.
441 resetPQExpBuffer(&conn->errorMessage);
442 appendPQExpBufferStr(&conn->errorMessage,
443 PQresultErrorMessage(res));
449 * pqInternalNotice - produce an internally-generated notice message
451 * A format string and optional arguments can be passed. Note that we do
452 * libpq_gettext() here, so callers need not.
454 * The supplied text is taken as primary message (ie., it should not include
455 * a trailing newline, and should not be more than one line).
458 pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt, ...)
464 if (hooks->noticeRec == NULL)
465 return; /* nobody home to receive notice? */
467 /* Format the message */
469 vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
471 msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
473 /* Make a PGresult to pass to the notice receiver */
474 res = PQmakeEmptyPGresult(NULL, PGRES_NONFATAL_ERROR);
477 res->noticeHooks = *hooks;
480 * Set up fields of notice.
482 pqSaveMessageField(res, PG_DIAG_MESSAGE_PRIMARY, msgBuf);
483 pqSaveMessageField(res, PG_DIAG_SEVERITY, libpq_gettext("NOTICE"));
484 /* XXX should provide a SQLSTATE too? */
487 * Result text is always just the primary message + newline. If we
488 * can't allocate it, don't bother invoking the receiver.
490 res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, FALSE);
493 sprintf(res->errMsg, "%s\n", msgBuf);
496 * Pass to receiver, then free it.
498 (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
505 * add a row pointer to the PGresult structure, growing it if necessary
506 * Returns TRUE if OK, FALSE if not enough memory to add the row
509 pqAddTuple(PGresult *res, PGresAttValue *tup)
511 if (res->ntups >= res->tupArrSize)
514 * Try to grow the array.
516 * We can use realloc because shallow copying of the structure is
517 * okay. Note that the first time through, res->tuples is NULL.
518 * While ANSI says that realloc() should act like malloc() in that
519 * case, some old C libraries (like SunOS 4.1.x) coredump instead.
520 * On failure realloc is supposed to return NULL without damaging
521 * the existing allocation. Note that the positions beyond
522 * res->ntups are garbage, not necessarily NULL.
524 int newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
525 PGresAttValue **newTuples;
527 if (res->tuples == NULL)
528 newTuples = (PGresAttValue **)
529 malloc(newSize * sizeof(PGresAttValue *));
531 newTuples = (PGresAttValue **)
532 realloc(res->tuples, newSize * sizeof(PGresAttValue *));
534 return FALSE; /* malloc or realloc failed */
535 res->tupArrSize = newSize;
536 res->tuples = newTuples;
538 res->tuples[res->ntups] = tup;
544 * pqSaveMessageField - save one field of an error or notice message
547 pqSaveMessageField(PGresult *res, char code, const char *value)
549 PGMessageField *pfield;
551 pfield = (PGMessageField *)
553 sizeof(PGMessageField) + strlen(value),
556 return; /* out of memory? */
558 strcpy(pfield->contents, value);
559 pfield->next = res->errFields;
560 res->errFields = pfield;
564 * pqSaveParameterStatus - remember parameter status sent by backend
567 pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
569 pgParameterStatus *pstatus;
570 pgParameterStatus *prev;
573 fprintf(conn->Pfdebug, "pqSaveParameterStatus: '%s' = '%s'\n",
577 * Forget any old information about the parameter
579 for (pstatus = conn->pstatus, prev = NULL;
581 prev = pstatus, pstatus = pstatus->next)
583 if (strcmp(pstatus->name, name) == 0)
586 prev->next = pstatus->next;
588 conn->pstatus = pstatus->next;
589 free(pstatus); /* frees name and value strings too */
595 * Store new info as a single malloc block
597 pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
598 strlen(name) +strlen(value) + 2);
603 ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
606 ptr += strlen(name) + 1;
607 pstatus->value = ptr;
609 pstatus->next = conn->pstatus;
610 conn->pstatus = pstatus;
614 * Special hacks: remember client_encoding as a numeric value, and
615 * convert server version to a numeric form as well.
617 if (strcmp(name, "client_encoding") == 0)
618 conn->client_encoding = pg_char_to_encoding(value);
619 else if (strcmp(name, "server_version") == 0)
626 cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
629 conn->sversion = 0; /* unknown */
634 conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
642 * Submit a query, but don't wait for it to finish
644 * Returns: 1 if successfully submitted
645 * 0 if error (conn->errorMessage is set)
648 PQsendQuery(PGconn *conn, const char *query)
650 if (!PQsendQueryStart(conn))
655 printfPQExpBuffer(&conn->errorMessage,
656 libpq_gettext("command string is a null pointer\n"));
660 /* construct the outgoing Query message */
661 if (pqPutMsgStart('Q', false, conn) < 0 ||
662 pqPuts(query, conn) < 0 ||
663 pqPutMsgEnd(conn) < 0)
665 pqHandleSendFailure(conn);
669 /* remember we are using simple query protocol */
670 conn->queryclass = PGQUERY_SIMPLE;
673 * Give the data a push. In nonblock mode, don't complain if we're
674 * unable to send it all; PQgetResult() will do any additional
677 if (pqFlush(conn) < 0)
679 pqHandleSendFailure(conn);
683 /* OK, it's launched! */
684 conn->asyncStatus = PGASYNC_BUSY;
690 * Like PQsendQuery, but use protocol 3.0 so we can pass parameters
693 PQsendQueryParams(PGconn *conn,
696 const Oid *paramTypes,
697 const char *const * paramValues,
698 const int *paramLengths,
699 const int *paramFormats,
702 if (!PQsendQueryStart(conn))
707 printfPQExpBuffer(&conn->errorMessage,
708 libpq_gettext("command string is a null pointer\n"));
712 return PQsendQueryGuts(conn,
714 "", /* use unnamed statement */
725 * Submit a Parse message, but don't wait for it to finish
727 * Returns: 1 if successfully submitted
728 * 0 if error (conn->errorMessage is set)
731 PQsendPrepare(PGconn *conn,
732 const char *stmtName, const char *query,
733 int nParams, const Oid *paramTypes)
735 if (!PQsendQueryStart(conn))
740 printfPQExpBuffer(&conn->errorMessage,
741 libpq_gettext("statement name is a null pointer\n"));
747 printfPQExpBuffer(&conn->errorMessage,
748 libpq_gettext("command string is a null pointer\n"));
752 /* This isn't gonna work on a 2.0 server */
753 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
755 printfPQExpBuffer(&conn->errorMessage,
756 libpq_gettext("function requires at least protocol version 3.0\n"));
760 /* construct the Parse message */
761 if (pqPutMsgStart('P', false, conn) < 0 ||
762 pqPuts(stmtName, conn) < 0 ||
763 pqPuts(query, conn) < 0)
766 if (nParams > 0 && paramTypes)
770 if (pqPutInt(nParams, 2, conn) < 0)
772 for (i = 0; i < nParams; i++)
774 if (pqPutInt(paramTypes[i], 4, conn) < 0)
780 if (pqPutInt(0, 2, conn) < 0)
783 if (pqPutMsgEnd(conn) < 0)
786 /* construct the Sync message */
787 if (pqPutMsgStart('S', false, conn) < 0 ||
788 pqPutMsgEnd(conn) < 0)
791 /* remember we are doing just a Parse */
792 conn->queryclass = PGQUERY_PREPARE;
795 * Give the data a push. In nonblock mode, don't complain if we're
796 * unable to send it all; PQgetResult() will do any additional
799 if (pqFlush(conn) < 0)
802 /* OK, it's launched! */
803 conn->asyncStatus = PGASYNC_BUSY;
807 pqHandleSendFailure(conn);
812 * PQsendQueryPrepared
813 * Like PQsendQuery, but execute a previously prepared statement,
814 * using protocol 3.0 so we can pass parameters
817 PQsendQueryPrepared(PGconn *conn,
818 const char *stmtName,
820 const char *const * paramValues,
821 const int *paramLengths,
822 const int *paramFormats,
825 if (!PQsendQueryStart(conn))
830 printfPQExpBuffer(&conn->errorMessage,
831 libpq_gettext("statement name is a null pointer\n"));
835 return PQsendQueryGuts(conn,
836 NULL, /* no command to parse */
839 NULL, /* no param types */
847 * Common startup code for PQsendQuery and sibling routines
850 PQsendQueryStart(PGconn *conn)
855 /* clear the error string */
856 resetPQExpBuffer(&conn->errorMessage);
858 /* Don't try to send if we know there's no live connection. */
859 if (conn->status != CONNECTION_OK)
861 printfPQExpBuffer(&conn->errorMessage,
862 libpq_gettext("no connection to the server\n"));
865 /* Can't send while already busy, either. */
866 if (conn->asyncStatus != PGASYNC_IDLE)
868 printfPQExpBuffer(&conn->errorMessage,
869 libpq_gettext("another command is already in progress\n"));
873 /* initialize async result-accumulation state */
875 conn->curTuple = NULL;
877 /* ready to send command message */
883 * Common code for protocol-3.0 query sending
884 * PQsendQueryStart should be done already
886 * command may be NULL to indicate we use an already-prepared statement
889 PQsendQueryGuts(PGconn *conn,
891 const char *stmtName,
893 const Oid *paramTypes,
894 const char *const * paramValues,
895 const int *paramLengths,
896 const int *paramFormats,
901 /* This isn't gonna work on a 2.0 server */
902 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
904 printfPQExpBuffer(&conn->errorMessage,
905 libpq_gettext("function requires at least protocol version 3.0\n"));
910 * We will send Parse (if needed), Bind, Describe Portal, Execute,
911 * Sync, using specified statement name and the unnamed portal.
916 /* construct the Parse message */
917 if (pqPutMsgStart('P', false, conn) < 0 ||
918 pqPuts(stmtName, conn) < 0 ||
919 pqPuts(command, conn) < 0)
921 if (nParams > 0 && paramTypes)
923 if (pqPutInt(nParams, 2, conn) < 0)
925 for (i = 0; i < nParams; i++)
927 if (pqPutInt(paramTypes[i], 4, conn) < 0)
933 if (pqPutInt(0, 2, conn) < 0)
936 if (pqPutMsgEnd(conn) < 0)
940 /* construct the Bind message */
941 if (pqPutMsgStart('B', false, conn) < 0 ||
942 pqPuts("", conn) < 0 ||
943 pqPuts(stmtName, conn) < 0)
945 if (nParams > 0 && paramFormats)
947 if (pqPutInt(nParams, 2, conn) < 0)
949 for (i = 0; i < nParams; i++)
951 if (pqPutInt(paramFormats[i], 2, conn) < 0)
957 if (pqPutInt(0, 2, conn) < 0)
960 if (pqPutInt(nParams, 2, conn) < 0)
962 for (i = 0; i < nParams; i++)
964 if (paramValues && paramValues[i])
968 if (paramFormats && paramFormats[i] != 0)
970 /* binary parameter */
972 nbytes = paramLengths[i];
975 printfPQExpBuffer(&conn->errorMessage,
976 libpq_gettext("length must be given for binary parameter\n"));
982 /* text parameter, do not use paramLengths */
983 nbytes = strlen(paramValues[i]);
985 if (pqPutInt(nbytes, 4, conn) < 0 ||
986 pqPutnchar(paramValues[i], nbytes, conn) < 0)
991 /* take the param as NULL */
992 if (pqPutInt(-1, 4, conn) < 0)
996 if (pqPutInt(1, 2, conn) < 0 ||
997 pqPutInt(resultFormat, 2, conn))
999 if (pqPutMsgEnd(conn) < 0)
1002 /* construct the Describe Portal message */
1003 if (pqPutMsgStart('D', false, conn) < 0 ||
1004 pqPutc('P', conn) < 0 ||
1005 pqPuts("", conn) < 0 ||
1006 pqPutMsgEnd(conn) < 0)
1009 /* construct the Execute message */
1010 if (pqPutMsgStart('E', false, conn) < 0 ||
1011 pqPuts("", conn) < 0 ||
1012 pqPutInt(0, 4, conn) < 0 ||
1013 pqPutMsgEnd(conn) < 0)
1016 /* construct the Sync message */
1017 if (pqPutMsgStart('S', false, conn) < 0 ||
1018 pqPutMsgEnd(conn) < 0)
1021 /* remember we are using extended query protocol */
1022 conn->queryclass = PGQUERY_EXTENDED;
1025 * Give the data a push. In nonblock mode, don't complain if we're
1026 * unable to send it all; PQgetResult() will do any additional
1029 if (pqFlush(conn) < 0)
1032 /* OK, it's launched! */
1033 conn->asyncStatus = PGASYNC_BUSY;
1037 pqHandleSendFailure(conn);
1042 * pqHandleSendFailure: try to clean up after failure to send command.
1044 * Primarily, what we want to accomplish here is to process an async
1045 * NOTICE message that the backend might have sent just before it died.
1047 * NOTE: this routine should only be called in PGASYNC_IDLE state.
1050 pqHandleSendFailure(PGconn *conn)
1053 * Accept any available input data, ignoring errors. Note that if
1054 * pqReadData decides the backend has closed the channel, it will
1055 * close our side of the socket --- that's just what we want here.
1057 while (pqReadData(conn) > 0)
1058 /* loop until no more data readable */ ;
1061 * Parse any available input messages. Since we are in PGASYNC_IDLE
1062 * state, only NOTICE and NOTIFY messages will be eaten.
1068 * Consume any available input from the backend
1069 * 0 return: some kind of trouble
1070 * 1 return: no problem
1073 PQconsumeInput(PGconn *conn)
1079 * for non-blocking connections try to flush the send-queue, otherwise
1080 * we may never get a response for something that may not have already
1081 * been sent because it's in our write buffer!
1083 if (pqIsnonblocking(conn))
1085 if (pqFlush(conn) < 0)
1090 * Load more data, if available. We do this no matter what state we
1091 * are in, since we are probably getting called because the
1092 * application wants to get rid of a read-select condition. Note that
1093 * we will NOT block waiting for more input.
1095 if (pqReadData(conn) < 0)
1098 /* Parsing of the data waits till later. */
1104 * parseInput: if appropriate, parse input data from backend
1105 * until input is exhausted or a stopping state is reached.
1106 * Note that this function will NOT attempt to read more data from the backend.
1109 parseInput(PGconn *conn)
1111 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1112 pqParseInput3(conn);
1114 pqParseInput2(conn);
1119 * Return TRUE if PQgetResult would block waiting for input.
1123 PQisBusy(PGconn *conn)
1128 /* Parse any available data, if our state permits. */
1131 /* PQgetResult will return immediately in all states except BUSY. */
1132 return conn->asyncStatus == PGASYNC_BUSY;
1138 * Get the next PGresult produced by a query. Returns NULL if no
1139 * query work remains or an error has occurred (e.g. out of
1144 PQgetResult(PGconn *conn)
1151 /* Parse any available data, if our state permits. */
1154 /* If not ready to return something, block until we are. */
1155 while (conn->asyncStatus == PGASYNC_BUSY)
1160 * If data remains unsent, send it. Else we might be waiting for
1161 * the result of a command the backend hasn't even got yet.
1163 while ((flushResult = pqFlush(conn)) > 0)
1165 if (pqWait(FALSE, TRUE, conn))
1172 /* Wait for some more data, and load it. */
1174 pqWait(TRUE, FALSE, conn) ||
1175 pqReadData(conn) < 0)
1178 * conn->errorMessage has been set by pqWait or pqReadData. We
1179 * want to append it to any already-received error message.
1181 pqSaveErrorResult(conn);
1182 conn->asyncStatus = PGASYNC_IDLE;
1183 return pqPrepareAsyncResult(conn);
1190 /* Return the appropriate thing. */
1191 switch (conn->asyncStatus)
1194 res = NULL; /* query is complete */
1197 res = pqPrepareAsyncResult(conn);
1198 /* Set the state back to BUSY, allowing parsing to proceed. */
1199 conn->asyncStatus = PGASYNC_BUSY;
1201 case PGASYNC_COPY_IN:
1202 if (conn->result && conn->result->resultStatus == PGRES_COPY_IN)
1203 res = pqPrepareAsyncResult(conn);
1205 res = PQmakeEmptyPGresult(conn, PGRES_COPY_IN);
1207 case PGASYNC_COPY_OUT:
1208 if (conn->result && conn->result->resultStatus == PGRES_COPY_OUT)
1209 res = pqPrepareAsyncResult(conn);
1211 res = PQmakeEmptyPGresult(conn, PGRES_COPY_OUT);
1214 printfPQExpBuffer(&conn->errorMessage,
1215 libpq_gettext("unexpected asyncStatus: %d\n"),
1216 (int) conn->asyncStatus);
1217 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1227 * send a query to the backend and package up the result in a PGresult
1229 * If the query was not even sent, return NULL; conn->errorMessage is set to
1230 * a relevant message.
1231 * If the query was sent, a new PGresult is returned (which could indicate
1232 * either success or failure).
1233 * The user is responsible for freeing the PGresult via PQclear()
1234 * when done with it.
1237 PQexec(PGconn *conn, const char *query)
1239 if (!PQexecStart(conn))
1241 if (!PQsendQuery(conn, query))
1243 return PQexecFinish(conn);
1248 * Like PQexec, but use protocol 3.0 so we can pass parameters
1251 PQexecParams(PGconn *conn,
1252 const char *command,
1254 const Oid *paramTypes,
1255 const char *const * paramValues,
1256 const int *paramLengths,
1257 const int *paramFormats,
1260 if (!PQexecStart(conn))
1262 if (!PQsendQueryParams(conn, command,
1263 nParams, paramTypes, paramValues, paramLengths,
1264 paramFormats, resultFormat))
1266 return PQexecFinish(conn);
1271 * Creates a prepared statement by issuing a v3.0 parse message.
1273 * If the query was not even sent, return NULL; conn->errorMessage is set to
1274 * a relevant message.
1275 * If the query was sent, a new PGresult is returned (which could indicate
1276 * either success or failure).
1277 * The user is responsible for freeing the PGresult via PQclear()
1278 * when done with it.
1281 PQprepare(PGconn *conn,
1282 const char *stmtName, const char *query,
1283 int nParams, const Oid *paramTypes)
1285 if (!PQexecStart(conn))
1287 if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
1289 return PQexecFinish(conn);
1294 * Like PQexec, but execute a previously prepared statement,
1295 * using protocol 3.0 so we can pass parameters
1298 PQexecPrepared(PGconn *conn,
1299 const char *stmtName,
1301 const char *const * paramValues,
1302 const int *paramLengths,
1303 const int *paramFormats,
1306 if (!PQexecStart(conn))
1308 if (!PQsendQueryPrepared(conn, stmtName,
1309 nParams, paramValues, paramLengths,
1310 paramFormats, resultFormat))
1312 return PQexecFinish(conn);
1316 * Common code for PQexec and sibling routines: prepare to send command
1319 PQexecStart(PGconn *conn)
1327 * Silently discard any prior query result that application didn't
1328 * eat. This is probably poor design, but it's here for backward
1331 while ((result = PQgetResult(conn)) != NULL)
1333 ExecStatusType resultStatus = result->resultStatus;
1335 PQclear(result); /* only need its status */
1336 if (resultStatus == PGRES_COPY_IN)
1338 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1340 /* In protocol 3, we can get out of a COPY IN state */
1341 if (PQputCopyEnd(conn,
1342 libpq_gettext("COPY terminated by new PQexec")) < 0)
1344 /* keep waiting to swallow the copy's failure message */
1348 /* In older protocols we have to punt */
1349 printfPQExpBuffer(&conn->errorMessage,
1350 libpq_gettext("COPY IN state must be terminated first\n"));
1354 else if (resultStatus == PGRES_COPY_OUT)
1356 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1359 * In protocol 3, we can get out of a COPY OUT state: we
1360 * just switch back to BUSY and allow the remaining COPY
1361 * data to be dropped on the floor.
1363 conn->asyncStatus = PGASYNC_BUSY;
1364 /* keep waiting to swallow the copy's completion message */
1368 /* In older protocols we have to punt */
1369 printfPQExpBuffer(&conn->errorMessage,
1370 libpq_gettext("COPY OUT state must be terminated first\n"));
1374 /* check for loss of connection, too */
1375 if (conn->status == CONNECTION_BAD)
1379 /* OK to send a command */
1384 * Common code for PQexec and sibling routines: wait for command result
1387 PQexecFinish(PGconn *conn)
1390 PGresult *lastResult;
1393 * For backwards compatibility, return the last result if there are
1394 * more than one --- but merge error messages if we get more than one
1397 * We have to stop if we see copy in/out, however. We will resume parsing
1398 * after application performs the data transfer.
1400 * Also stop if the connection is lost (else we'll loop infinitely).
1403 while ((result = PQgetResult(conn)) != NULL)
1407 if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
1408 result->resultStatus == PGRES_FATAL_ERROR)
1410 pqCatenateResultError(lastResult, result->errMsg);
1412 result = lastResult;
1415 * Make sure PQerrorMessage agrees with concatenated
1418 resetPQExpBuffer(&conn->errorMessage);
1419 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
1422 PQclear(lastResult);
1424 lastResult = result;
1425 if (result->resultStatus == PGRES_COPY_IN ||
1426 result->resultStatus == PGRES_COPY_OUT ||
1427 conn->status == CONNECTION_BAD)
1436 * returns a PGnotify* structure of the latest async notification
1437 * that has not yet been handled
1439 * returns NULL, if there is currently
1440 * no unhandled async notification from the backend
1442 * the CALLER is responsible for FREE'ing the structure returned
1445 PQnotifies(PGconn *conn)
1452 /* Parse any available data to see if we can extract NOTIFY messages. */
1455 event = conn->notifyHead;
1458 conn->notifyHead = event->next;
1459 if (!conn->notifyHead)
1460 conn->notifyTail = NULL;
1461 event->next = NULL; /* don't let app see the internal state */
1467 * PQputCopyData - send some data to the backend during COPY IN
1469 * Returns 1 if successful, 0 if data could not be sent (only possible
1470 * in nonblock mode), or -1 if an error occurs.
1473 PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
1477 if (conn->asyncStatus != PGASYNC_COPY_IN)
1479 printfPQExpBuffer(&conn->errorMessage,
1480 libpq_gettext("no COPY in progress\n"));
1485 * Check for NOTICE messages coming back from the server. Since the
1486 * server might generate multiple notices during the COPY, we have to
1487 * consume those in a reasonably prompt fashion to prevent the comm
1488 * buffers from filling up and possibly blocking the server.
1490 if (!PQconsumeInput(conn))
1491 return -1; /* I/O failure */
1497 * Try to flush any previously sent data in preference to growing
1498 * the output buffer. If we can't enlarge the buffer enough to
1499 * hold the data, return 0 in the nonblock case, else hard error.
1500 * (For simplicity, always assume 5 bytes of overhead even in
1501 * protocol 2.0 case.)
1503 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
1505 if (pqFlush(conn) < 0)
1507 if (pqCheckOutBufferSpace(conn->outCount + 5 + nbytes, conn))
1508 return pqIsnonblocking(conn) ? 0 : -1;
1510 /* Send the data (too simple to delegate to fe-protocol files) */
1511 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1513 if (pqPutMsgStart('d', false, conn) < 0 ||
1514 pqPutnchar(buffer, nbytes, conn) < 0 ||
1515 pqPutMsgEnd(conn) < 0)
1520 if (pqPutMsgStart(0, false, conn) < 0 ||
1521 pqPutnchar(buffer, nbytes, conn) < 0 ||
1522 pqPutMsgEnd(conn) < 0)
1530 * PQputCopyEnd - send EOF indication to the backend during COPY IN
1532 * After calling this, use PQgetResult() to check command completion status.
1534 * Returns 1 if successful, 0 if data could not be sent (only possible
1535 * in nonblock mode), or -1 if an error occurs.
1538 PQputCopyEnd(PGconn *conn, const char *errormsg)
1542 if (conn->asyncStatus != PGASYNC_COPY_IN)
1544 printfPQExpBuffer(&conn->errorMessage,
1545 libpq_gettext("no COPY in progress\n"));
1550 * Send the COPY END indicator. This is simple enough that we don't
1551 * bother delegating it to the fe-protocol files.
1553 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1557 /* Send COPY FAIL */
1558 if (pqPutMsgStart('f', false, conn) < 0 ||
1559 pqPuts(errormsg, conn) < 0 ||
1560 pqPutMsgEnd(conn) < 0)
1565 /* Send COPY DONE */
1566 if (pqPutMsgStart('c', false, conn) < 0 ||
1567 pqPutMsgEnd(conn) < 0)
1572 * If we sent the COPY command in extended-query mode, we must
1573 * issue a Sync as well.
1575 if (conn->queryclass != PGQUERY_SIMPLE)
1577 if (pqPutMsgStart('S', false, conn) < 0 ||
1578 pqPutMsgEnd(conn) < 0)
1586 /* Ooops, no way to do this in 2.0 */
1587 printfPQExpBuffer(&conn->errorMessage,
1588 libpq_gettext("function requires at least protocol version 3.0\n"));
1593 /* Send old-style end-of-data marker */
1594 if (pqPutMsgStart(0, false, conn) < 0 ||
1595 pqPutnchar("\\.\n", 3, conn) < 0 ||
1596 pqPutMsgEnd(conn) < 0)
1601 /* Return to active duty */
1602 conn->asyncStatus = PGASYNC_BUSY;
1603 resetPQExpBuffer(&conn->errorMessage);
1605 /* Try to flush data */
1606 if (pqFlush(conn) < 0)
1613 * PQgetCopyData - read a row of data from the backend during COPY OUT
1615 * If successful, sets *buffer to point to a malloc'd row of data, and
1616 * returns row length (always > 0) as result.
1617 * Returns 0 if no row available yet (only possible if async is true),
1618 * -1 if end of copy (consult PQgetResult), or -2 if error (consult
1622 PQgetCopyData(PGconn *conn, char **buffer, int async)
1624 *buffer = NULL; /* for all failure cases */
1627 if (conn->asyncStatus != PGASYNC_COPY_OUT)
1629 printfPQExpBuffer(&conn->errorMessage,
1630 libpq_gettext("no COPY in progress\n"));
1633 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1634 return pqGetCopyData3(conn, buffer, async);
1636 return pqGetCopyData2(conn, buffer, async);
1640 * PQgetline - gets a newline-terminated string from the backend.
1642 * Chiefly here so that applications can use "COPY <rel> to stdout"
1643 * and read the output string. Returns a null-terminated string in s.
1645 * XXX this routine is now deprecated, because it can't handle binary data.
1646 * If called during a COPY BINARY we return EOF.
1648 * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
1649 * the terminating \n (like gets(3)).
1651 * CAUTION: the caller is responsible for detecting the end-of-copy signal
1652 * (a line containing just "\.") when using this routine.
1655 * EOF if error (eg, invalid arguments are given)
1656 * 0 if EOL is reached (i.e., \n has been read)
1657 * (this is required for backward-compatibility -- this
1658 * routine used to always return EOF or 0, assuming that
1659 * the line ended within maxlen bytes.)
1660 * 1 in other cases (i.e., the buffer was filled before \n is reached)
1663 PQgetline(PGconn *conn, char *s, int maxlen)
1665 if (!s || maxlen <= 0)
1668 /* maxlen must be at least 3 to hold the \. terminator! */
1675 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1676 return pqGetline3(conn, s, maxlen);
1678 return pqGetline2(conn, s, maxlen);
1682 * PQgetlineAsync - gets a COPY data row without blocking.
1684 * This routine is for applications that want to do "COPY <rel> to stdout"
1685 * asynchronously, that is without blocking. Having issued the COPY command
1686 * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
1687 * and this routine until the end-of-data signal is detected. Unlike
1688 * PQgetline, this routine takes responsibility for detecting end-of-data.
1690 * On each call, PQgetlineAsync will return data if a complete data row
1691 * is available in libpq's input buffer. Otherwise, no data is returned
1692 * until the rest of the row arrives.
1694 * If -1 is returned, the end-of-data signal has been recognized (and removed
1695 * from libpq's input buffer). The caller *must* next call PQendcopy and
1696 * then return to normal processing.
1699 * -1 if the end-of-copy-data marker has been recognized
1700 * 0 if no data is available
1701 * >0 the number of bytes returned.
1703 * The data returned will not extend beyond a data-row boundary. If possible
1704 * a whole row will be returned at one time. But if the buffer offered by
1705 * the caller is too small to hold a row sent by the backend, then a partial
1706 * data row will be returned. In text mode this can be detected by testing
1707 * whether the last returned byte is '\n' or not.
1709 * The returned data is *not* null-terminated.
1713 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
1718 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1719 return pqGetlineAsync3(conn, buffer, bufsize);
1721 return pqGetlineAsync2(conn, buffer, bufsize);
1725 * PQputline -- sends a string to the backend during COPY IN.
1726 * Returns 0 if OK, EOF if not.
1728 * This is deprecated primarily because the return convention doesn't allow
1729 * caller to tell the difference between a hard error and a nonblock-mode
1733 PQputline(PGconn *conn, const char *s)
1735 return PQputnbytes(conn, s, strlen(s));
1739 * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
1740 * Returns 0 if OK, EOF if not.
1743 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
1745 if (PQputCopyData(conn, buffer, nbytes) > 0)
1753 * After completing the data transfer portion of a copy in/out,
1754 * the application must call this routine to finish the command protocol.
1756 * When using protocol 3.0 this is deprecated; it's cleaner to use PQgetResult
1757 * to get the transfer status. Note however that when using 2.0 protocol,
1758 * recovering from a copy failure often requires a PQreset. PQendcopy will
1759 * take care of that, PQgetResult won't.
1766 PQendcopy(PGconn *conn)
1771 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1772 return pqEndcopy3(conn);
1774 return pqEndcopy2(conn);
1779 * PQfn - Send a function call to the POSTGRES backend.
1781 * conn : backend connection
1782 * fnid : function id
1783 * result_buf : pointer to result buffer (&int if integer)
1784 * result_len : length of return value.
1785 * actual_result_len: actual length returned. (differs from result_len
1786 * for varlena structures.)
1787 * result_type : If the result is an integer, this must be 1,
1788 * otherwise this should be 0
1789 * args : pointer to an array of function arguments.
1790 * (each has length, if integer, and value/pointer)
1791 * nargs : # of arguments in args array.
1794 * PGresult with status = PGRES_COMMAND_OK if successful.
1795 * *actual_result_len is > 0 if there is a return value, 0 if not.
1796 * PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
1797 * NULL on communications failure. conn->errorMessage will be set.
1805 int *actual_result_len,
1807 const PQArgBlock *args,
1810 *actual_result_len = 0;
1815 /* clear the error string */
1816 resetPQExpBuffer(&conn->errorMessage);
1818 if (conn->sock < 0 || conn->asyncStatus != PGASYNC_IDLE ||
1819 conn->result != NULL)
1821 printfPQExpBuffer(&conn->errorMessage,
1822 libpq_gettext("connection in wrong state\n"));
1826 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1827 return pqFunctionCall3(conn, fnid,
1828 result_buf, actual_result_len,
1832 return pqFunctionCall2(conn, fnid,
1833 result_buf, actual_result_len,
1839 /* ====== accessor funcs for PGresult ======== */
1842 PQresultStatus(const PGresult *res)
1845 return PGRES_FATAL_ERROR;
1846 return res->resultStatus;
1850 PQresStatus(ExecStatusType status)
1852 if (status < 0 || status >= sizeof pgresStatus / sizeof pgresStatus[0])
1853 return libpq_gettext("invalid ExecStatusType code");
1854 return pgresStatus[status];
1858 PQresultErrorMessage(const PGresult *res)
1860 if (!res || !res->errMsg)
1866 PQresultErrorField(const PGresult *res, int fieldcode)
1868 PGMessageField *pfield;
1872 for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
1874 if (pfield->code == fieldcode)
1875 return pfield->contents;
1881 PQntuples(const PGresult *res)
1889 PQnfields(const PGresult *res)
1893 return res->numAttributes;
1897 PQbinaryTuples(const PGresult *res)
1905 * Helper routines to range-check field numbers and tuple numbers.
1906 * Return TRUE if OK, FALSE if not
1910 check_field_number(const PGresult *res, int field_num)
1913 return FALSE; /* no way to display error message... */
1914 if (field_num < 0 || field_num >= res->numAttributes)
1916 pqInternalNotice(&res->noticeHooks,
1917 "column number %d is out of range 0..%d",
1918 field_num, res->numAttributes - 1);
1925 check_tuple_field_number(const PGresult *res,
1926 int tup_num, int field_num)
1929 return FALSE; /* no way to display error message... */
1930 if (tup_num < 0 || tup_num >= res->ntups)
1932 pqInternalNotice(&res->noticeHooks,
1933 "row number %d is out of range 0..%d",
1934 tup_num, res->ntups - 1);
1937 if (field_num < 0 || field_num >= res->numAttributes)
1939 pqInternalNotice(&res->noticeHooks,
1940 "column number %d is out of range 0..%d",
1941 field_num, res->numAttributes - 1);
1948 * returns NULL if the field_num is invalid
1951 PQfname(const PGresult *res, int field_num)
1953 if (!check_field_number(res, field_num))
1956 return res->attDescs[field_num].name;
1962 * PQfnumber: find column number given column name
1964 * The column name is parsed as if it were in a SQL statement, including
1965 * case-folding and double-quote processing. But note a possible gotcha:
1966 * downcasing in the frontend might follow different locale rules than
1967 * downcasing in the backend...
1969 * Returns -1 if no match. In the present backend it is also possible
1970 * to have multiple matches, in which case the first one is found.
1973 PQfnumber(const PGresult *res, const char *field_name)
1985 * Note: it is correct to reject a zero-length input string; the
1986 * proper input to match a zero-length field name would be "".
1988 if (field_name == NULL ||
1989 field_name[0] == '\0' ||
1990 res->attDescs == NULL)
1994 * Note: this code will not reject partially quoted strings, eg
1995 * foo"BAR"foo will become fooBARfoo when it probably ought to be an
1998 field_case = strdup(field_name);
1999 if (field_case == NULL)
2000 return -1; /* grotty */
2004 for (iptr = field_case; *iptr; iptr++)
2014 /* doubled quotes become a single quote */
2028 c = pg_tolower((unsigned char) c);
2034 for (i = 0; i < res->numAttributes; i++)
2036 if (strcmp(field_case, res->attDescs[i].name) == 0)
2047 PQftable(const PGresult *res, int field_num)
2049 if (!check_field_number(res, field_num))
2052 return res->attDescs[field_num].tableid;
2058 PQftablecol(const PGresult *res, int field_num)
2060 if (!check_field_number(res, field_num))
2063 return res->attDescs[field_num].columnid;
2069 PQfformat(const PGresult *res, int field_num)
2071 if (!check_field_number(res, field_num))
2074 return res->attDescs[field_num].format;
2080 PQftype(const PGresult *res, int field_num)
2082 if (!check_field_number(res, field_num))
2085 return res->attDescs[field_num].typid;
2091 PQfsize(const PGresult *res, int field_num)
2093 if (!check_field_number(res, field_num))
2096 return res->attDescs[field_num].typlen;
2102 PQfmod(const PGresult *res, int field_num)
2104 if (!check_field_number(res, field_num))
2107 return res->attDescs[field_num].atttypmod;
2113 PQcmdStatus(PGresult *res)
2117 return res->cmdStatus;
2122 * if the last command was an INSERT, return the oid string
2126 PQoidStatus(const PGresult *res)
2129 * This must be enough to hold the result. Don't laugh, this is better
2130 * than what this function used to do.
2132 static char buf[24];
2136 if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2139 len = strspn(res->cmdStatus + 7, "0123456789");
2142 strncpy(buf, res->cmdStatus + 7, len);
2150 * a perhaps preferable form of the above which just returns
2154 PQoidValue(const PGresult *res)
2156 char *endptr = NULL;
2157 unsigned long result;
2159 if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2167 result = strtoul(res->cmdStatus + 7, &endptr, 10);
2169 if (!endptr || (*endptr != ' ' && *endptr != '\0')
2172 * On WIN32, errno is not thread-safe and GetLastError() isn't set by
2173 * strtoul(), so we can't check on this platform.
2180 return (Oid) result;
2186 * If the last command was an INSERT/UPDATE/DELETE/MOVE/FETCH, return a
2187 * string containing the number of inserted/affected tuples. If not,
2190 * XXX: this should probably return an int
2193 PQcmdTuples(PGresult *res)
2200 if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
2202 p = res->cmdStatus + 6;
2204 /* INSERT: skip oid */
2205 while (*p != ' ' && *p)
2208 else if (strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
2209 strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
2210 p = res->cmdStatus + 6;
2211 else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
2212 p = res->cmdStatus + 5;
2213 else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0)
2214 p = res->cmdStatus + 4;
2222 pqInternalNotice(&res->noticeHooks,
2223 "could not interpret result from server: %s",
2233 * return the value of field 'field_num' of row 'tup_num'
2236 PQgetvalue(const PGresult *res, int tup_num, int field_num)
2238 if (!check_tuple_field_number(res, tup_num, field_num))
2240 return res->tuples[tup_num][field_num].value;
2244 * returns the actual length of a field value in bytes.
2247 PQgetlength(const PGresult *res, int tup_num, int field_num)
2249 if (!check_tuple_field_number(res, tup_num, field_num))
2251 if (res->tuples[tup_num][field_num].len != NULL_LEN)
2252 return res->tuples[tup_num][field_num].len;
2258 * returns the null status of a field value.
2261 PQgetisnull(const PGresult *res, int tup_num, int field_num)
2263 if (!check_tuple_field_number(res, tup_num, field_num))
2264 return 1; /* pretend it is null */
2265 if (res->tuples[tup_num][field_num].len == NULL_LEN)
2271 /* PQsetnonblocking:
2272 * sets the PGconn's database connection non-blocking if the arg is TRUE
2273 * or makes it non-blocking if the arg is FALSE, this will not protect
2274 * you from PQexec(), you'll only be safe when using the non-blocking API.
2275 * Needs to be called only on a connected database connection.
2278 PQsetnonblocking(PGconn *conn, int arg)
2282 if (!conn || conn->status == CONNECTION_BAD)
2285 barg = (arg ? TRUE : FALSE);
2287 /* early out if the socket is already in the state requested */
2288 if (barg == conn->nonblocking)
2292 * to guarantee constancy for flushing/query/result-polling behavior
2293 * we need to flush the send queue at this point in order to guarantee
2294 * proper behavior. this is ok because either they are making a
2295 * transition _from_ or _to_ blocking mode, either way we can block
2298 /* if we are going from blocking to non-blocking flush here */
2302 conn->nonblocking = barg;
2308 * return the blocking status of the database connection
2309 * TRUE == nonblocking, FALSE == blocking
2312 PQisnonblocking(const PGconn *conn)
2314 return (pqIsnonblocking(conn));
2317 /* try to force data out, really only useful for non-blocking users */
2319 PQflush(PGconn *conn)
2321 return pqFlush(conn);
2326 * PQfreemem - safely frees memory allocated
2328 * Needed mostly by Win32, unless multithreaded DLL (/MD in VC6)
2329 * Used for freeing memory from PQescapeByte()a/PQunescapeBytea()
2332 PQfreemem(void *ptr)
2338 * PQfreeNotify - free's the memory associated with a PGnotify
2340 * This function is here only for binary backward compatibility.
2341 * New code should use PQfreemem(). A macro will automatically map
2342 * calls to PQfreemem. It should be removed in the future. bjm 2003-03-24
2346 void PQfreeNotify(PGnotify *notify);
2349 PQfreeNotify(PGnotify *notify)
2356 * Escaping arbitrary strings to get valid SQL literal strings.
2358 * Replaces "\\" with "\\\\" and "'" with "''".
2360 * length is the length of the source string. (Note: if a terminating NUL
2361 * is encountered sooner, PQescapeString stops short of "length"; the behavior
2362 * is thus rather like strncpy.)
2364 * For safety the buffer at "to" must be at least 2*length + 1 bytes long.
2365 * A terminating NUL character is added to the output string, whether the
2366 * input is NUL-terminated or not.
2368 * Returns the actual length of the output (not counting the terminating NUL).
2371 PQescapeString(char *to, const char *from, size_t length)
2373 const char *source = from;
2375 size_t remaining = length;
2377 while (remaining > 0 && *source != '\0')
2379 if (SQL_STR_DOUBLE(*source))
2380 *target++ = *source;
2381 *target++ = *source++;
2385 /* Write the terminating NUL character. */
2392 * PQescapeBytea - converts from binary string to the
2393 * minimal encoding necessary to include the string in an SQL
2394 * INSERT statement with a bytea type column as the target.
2396 * The following transformations are applied
2397 * '\0' == ASCII 0 == \\000
2398 * '\'' == ASCII 39 == \'
2399 * '\\' == ASCII 92 == \\\\
2400 * anything < 0x20, or > 0x7e ---> \\ooo
2401 * (where ooo is an octal expression)
2404 PQescapeBytea(const unsigned char *bintext, size_t binlen, size_t *bytealen)
2406 const unsigned char *vp;
2408 unsigned char *result;
2413 * empty string has 1 char ('\0')
2418 for (i = binlen; i > 0; i--, vp++)
2420 if (*vp < 0x20 || *vp > 0x7e)
2421 len += 5; /* '5' is for '\\ooo' */
2422 else if (*vp == '\'')
2424 else if (*vp == '\\')
2430 rp = result = (unsigned char *) malloc(len);
2437 for (i = binlen; i > 0; i--, vp++)
2439 if (*vp < 0x20 || *vp > 0x7e)
2441 (void) sprintf(rp, "\\\\%03o", *vp);
2444 else if (*vp == '\'')
2450 else if (*vp == '\\')
2466 #define ISFIRSTOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '3')
2467 #define ISOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '7')
2468 #define OCTVAL(CH) ((CH) - '0')
2471 * PQunescapeBytea - converts the null terminated string representation
2472 * of a bytea, strtext, into binary, filling a buffer. It returns a
2473 * pointer to the buffer (or NULL on error), and the size of the
2474 * buffer in retbuflen. The pointer may subsequently be used as an
2475 * argument to the function free(3). It is the reverse of PQescapeBytea.
2477 * The following transformations are made:
2478 * \\ == ASCII 92 == \
2479 * \ooo == a byte whose value = ooo (ooo is an octal number)
2480 * \x == x (x is any character not matched by the above transformations)
2483 PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
2487 unsigned char *buffer,
2492 if (strtext == NULL)
2495 strtextlen = strlen(strtext);
2498 * Length of input is max length of output, but add one to avoid
2499 * unportable malloc(0) if input is zero-length.
2501 buffer = (unsigned char *) malloc(strtextlen + 1);
2505 for (i = j = 0; i < strtextlen;)
2511 if (strtext[i] == '\\')
2512 buffer[j++] = strtext[i++];
2515 if ((ISFIRSTOCTDIGIT(strtext[i])) &&
2516 (ISOCTDIGIT(strtext[i + 1])) &&
2517 (ISOCTDIGIT(strtext[i + 2])))
2521 byte = OCTVAL(strtext[i++]);
2522 byte = (byte << 3) + OCTVAL(strtext[i++]);
2523 byte = (byte << 3) + OCTVAL(strtext[i++]);
2529 * Note: if we see '\' followed by something that isn't a
2530 * recognized escape sequence, we loop around having done
2531 * nothing except advance i. Therefore the something will
2532 * be emitted as ordinary data on the next cycle. Corner
2533 * case: '\' at end of string will just be discarded.
2538 buffer[j++] = strtext[i++];
2542 buflen = j; /* buflen is the length of the dequoted
2545 /* Shrink the buffer to be no larger than necessary */
2546 /* +1 avoids unportable behavior when buflen==0 */
2547 tmpbuf = realloc(buffer, buflen + 1);
2549 /* It would only be a very brain-dead realloc that could fail, but... */
2556 *retbuflen = buflen;