1 /*-------------------------------------------------------------------------
4 * functions related to sending a query down to the backend
6 * Portions Copyright (c) 1996-2004, 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.165 2004/10/21 19:28:36 tgl 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));
139 result->numAttributes = 0;
140 result->attDescs = NULL;
141 result->tuples = NULL;
142 result->tupArrSize = 0;
143 result->resultStatus = status;
144 result->cmdStatus[0] = '\0';
146 result->errMsg = NULL;
147 result->errFields = NULL;
148 result->null_field[0] = '\0';
149 result->curBlock = NULL;
150 result->curOffset = 0;
151 result->spaceLeft = 0;
155 /* copy connection data we might need for operations on PGresult */
156 result->noticeHooks = conn->noticeHooks;
157 result->client_encoding = conn->client_encoding;
159 /* consider copying conn's errorMessage */
162 case PGRES_EMPTY_QUERY:
163 case PGRES_COMMAND_OK:
164 case PGRES_TUPLES_OK:
167 /* non-error cases */
170 pqSetResultError(result, conn->errorMessage.data);
177 result->noticeHooks.noticeRec = NULL;
178 result->noticeHooks.noticeRecArg = NULL;
179 result->noticeHooks.noticeProc = NULL;
180 result->noticeHooks.noticeProcArg = NULL;
181 result->client_encoding = PG_SQL_ASCII;
189 * Allocate subsidiary storage for a PGresult.
191 * nBytes is the amount of space needed for the object.
192 * If isBinary is true, we assume that we need to align the object on
193 * a machine allocation boundary.
194 * If isBinary is false, we assume the object is a char string and can
195 * be allocated on any byte boundary.
198 pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
201 PGresult_data *block;
207 return res->null_field;
210 * If alignment is needed, round up the current position to an
211 * alignment boundary.
215 int offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
219 res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
220 res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
224 /* If there's enough space in the current block, no problem. */
225 if (nBytes <= (size_t) res->spaceLeft)
227 space = res->curBlock->space + res->curOffset;
228 res->curOffset += nBytes;
229 res->spaceLeft -= nBytes;
234 * If the requested object is very large, give it its own block; this
235 * avoids wasting what might be most of the current block to start a
236 * new block. (We'd have to special-case requests bigger than the
237 * block size anyway.) The object is always given binary alignment in
240 if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
242 block = (PGresult_data *) malloc(nBytes + PGRESULT_BLOCK_OVERHEAD);
245 space = block->space + PGRESULT_BLOCK_OVERHEAD;
249 * Tuck special block below the active block, so that we don't
250 * have to waste the free space in the active block.
252 block->next = res->curBlock->next;
253 res->curBlock->next = block;
257 /* Must set up the new block as the first active block. */
259 res->curBlock = block;
260 res->spaceLeft = 0; /* be sure it's marked full */
265 /* Otherwise, start a new block. */
266 block = (PGresult_data *) malloc(PGRESULT_DATA_BLOCKSIZE);
269 block->next = res->curBlock;
270 res->curBlock = block;
273 /* object needs full alignment */
274 res->curOffset = PGRESULT_BLOCK_OVERHEAD;
275 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - PGRESULT_BLOCK_OVERHEAD;
279 /* we can cram it right after the overhead pointer */
280 res->curOffset = sizeof(PGresult_data);
281 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - sizeof(PGresult_data);
284 space = block->space + res->curOffset;
285 res->curOffset += nBytes;
286 res->spaceLeft -= nBytes;
292 * Like strdup, but the space is subsidiary PGresult space.
295 pqResultStrdup(PGresult *res, const char *str)
297 char *space = (char *) pqResultAlloc(res, strlen(str) + 1, FALSE);
306 * assign a new error message to a PGresult
309 pqSetResultError(PGresult *res, const char *msg)
314 res->errMsg = pqResultStrdup(res, msg);
320 * pqCatenateResultError -
321 * concatenate a new error message to the one already in a PGresult
324 pqCatenateResultError(PGresult *res, const char *msg)
326 PQExpBufferData errorBuf;
330 initPQExpBuffer(&errorBuf);
332 appendPQExpBufferStr(&errorBuf, res->errMsg);
333 appendPQExpBufferStr(&errorBuf, msg);
334 pqSetResultError(res, errorBuf.data);
335 termPQExpBuffer(&errorBuf);
340 * free's the memory associated with a PGresult
343 PQclear(PGresult *res)
345 PGresult_data *block;
350 /* Free all the subsidiary blocks */
351 while ((block = res->curBlock) != NULL)
353 res->curBlock = block->next;
357 /* Free the top-level tuple pointer array */
361 /* Free the PGresult structure itself */
366 * Handy subroutine to deallocate any partially constructed async result.
370 pqClearAsyncResult(PGconn *conn)
373 PQclear(conn->result);
375 conn->curTuple = NULL;
379 * This subroutine deletes any existing async result, sets conn->result
380 * to a PGresult with status PGRES_FATAL_ERROR, and stores the current
381 * contents of conn->errorMessage into that result. It differs from a
382 * plain call on PQmakeEmptyPGresult() in that if there is already an
383 * async result with status PGRES_FATAL_ERROR, the current error message
384 * is APPENDED to the old error message instead of replacing it. This
385 * behavior lets us report multiple error conditions properly, if necessary.
386 * (An example where this is needed is when the backend sends an 'E' message
387 * and immediately closes the connection --- we want to report both the
388 * backend error and the connection closure error.)
391 pqSaveErrorResult(PGconn *conn)
394 * If no old async result, just let PQmakeEmptyPGresult make one.
395 * Likewise if old result is not an error message.
397 if (conn->result == NULL ||
398 conn->result->resultStatus != PGRES_FATAL_ERROR ||
399 conn->result->errMsg == NULL)
401 pqClearAsyncResult(conn);
402 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
406 /* Else, concatenate error message to existing async result. */
407 pqCatenateResultError(conn->result, conn->errorMessage.data);
412 * This subroutine prepares an async result object for return to the caller.
413 * If there is not already an async result object, build an error object
414 * using whatever is in conn->errorMessage. In any case, clear the async
415 * result storage and make sure PQerrorMessage will agree with the result's
419 pqPrepareAsyncResult(PGconn *conn)
424 * conn->result is the PGresult to return. If it is NULL (which
425 * probably shouldn't happen) we assume there is an appropriate error
426 * message in conn->errorMessage.
429 conn->result = NULL; /* handing over ownership to caller */
430 conn->curTuple = NULL; /* just in case */
432 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
436 * Make sure PQerrorMessage agrees with result; it could be
437 * different if we have concatenated messages.
439 resetPQExpBuffer(&conn->errorMessage);
440 appendPQExpBufferStr(&conn->errorMessage,
441 PQresultErrorMessage(res));
447 * pqInternalNotice - produce an internally-generated notice message
449 * A format string and optional arguments can be passed. Note that we do
450 * libpq_gettext() here, so callers need not.
452 * The supplied text is taken as primary message (ie., it should not include
453 * a trailing newline, and should not be more than one line).
456 pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
462 if (hooks->noticeRec == NULL)
463 return; /* nobody home to receive notice? */
465 /* Format the message */
467 vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
469 msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
471 /* Make a PGresult to pass to the notice receiver */
472 res = PQmakeEmptyPGresult(NULL, PGRES_NONFATAL_ERROR);
473 res->noticeHooks = *hooks;
476 * Set up fields of notice.
478 pqSaveMessageField(res, PG_DIAG_MESSAGE_PRIMARY, msgBuf);
479 pqSaveMessageField(res, PG_DIAG_SEVERITY, libpq_gettext("NOTICE"));
480 /* XXX should provide a SQLSTATE too? */
483 * Result text is always just the primary message + newline.
485 res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, FALSE);
486 sprintf(res->errMsg, "%s\n", msgBuf);
489 * Pass to receiver, then free it.
491 (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
497 * add a row pointer to the PGresult structure, growing it if necessary
498 * Returns TRUE if OK, FALSE if not enough memory to add the row
501 pqAddTuple(PGresult *res, PGresAttValue *tup)
503 if (res->ntups >= res->tupArrSize)
506 * Try to grow the array.
508 * We can use realloc because shallow copying of the structure is
509 * okay. Note that the first time through, res->tuples is NULL.
510 * While ANSI says that realloc() should act like malloc() in that
511 * case, some old C libraries (like SunOS 4.1.x) coredump instead.
512 * On failure realloc is supposed to return NULL without damaging
513 * the existing allocation. Note that the positions beyond
514 * res->ntups are garbage, not necessarily NULL.
516 int newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
517 PGresAttValue **newTuples;
519 if (res->tuples == NULL)
520 newTuples = (PGresAttValue **)
521 malloc(newSize * sizeof(PGresAttValue *));
523 newTuples = (PGresAttValue **)
524 realloc(res->tuples, newSize * sizeof(PGresAttValue *));
526 return FALSE; /* malloc or realloc failed */
527 res->tupArrSize = newSize;
528 res->tuples = newTuples;
530 res->tuples[res->ntups] = tup;
536 * pqSaveMessageField - save one field of an error or notice message
539 pqSaveMessageField(PGresult *res, char code, const char *value)
541 PGMessageField *pfield;
543 pfield = (PGMessageField *)
545 sizeof(PGMessageField) + strlen(value),
548 return; /* out of memory? */
550 strcpy(pfield->contents, value);
551 pfield->next = res->errFields;
552 res->errFields = pfield;
556 * pqSaveParameterStatus - remember parameter status sent by backend
559 pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
561 pgParameterStatus *pstatus;
562 pgParameterStatus *prev;
565 fprintf(conn->Pfdebug, "pqSaveParameterStatus: '%s' = '%s'\n",
569 * Forget any old information about the parameter
571 for (pstatus = conn->pstatus, prev = NULL;
573 prev = pstatus, pstatus = pstatus->next)
575 if (strcmp(pstatus->name, name) == 0)
578 prev->next = pstatus->next;
580 conn->pstatus = pstatus->next;
581 free(pstatus); /* frees name and value strings too */
587 * Store new info as a single malloc block
589 pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
590 strlen(name) +strlen(value) + 2);
595 ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
598 ptr += strlen(name) + 1;
599 pstatus->value = ptr;
601 pstatus->next = conn->pstatus;
602 conn->pstatus = pstatus;
606 * Special hacks: remember client_encoding as a numeric value, and
607 * convert server version to a numeric form as well.
609 if (strcmp(name, "client_encoding") == 0)
610 conn->client_encoding = pg_char_to_encoding(value);
611 else if (strcmp(name, "server_version") == 0)
618 cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
621 conn->sversion = 0; /* unknown */
626 conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
634 * Submit a query, but don't wait for it to finish
636 * Returns: 1 if successfully submitted
637 * 0 if error (conn->errorMessage is set)
640 PQsendQuery(PGconn *conn, const char *query)
642 if (!PQsendQueryStart(conn))
647 printfPQExpBuffer(&conn->errorMessage,
648 libpq_gettext("command string is a null pointer\n"));
652 /* construct the outgoing Query message */
653 if (pqPutMsgStart('Q', false, conn) < 0 ||
654 pqPuts(query, conn) < 0 ||
655 pqPutMsgEnd(conn) < 0)
657 pqHandleSendFailure(conn);
661 /* remember we are using simple query protocol */
662 conn->queryclass = PGQUERY_SIMPLE;
665 * Give the data a push. In nonblock mode, don't complain if we're
666 * unable to send it all; PQgetResult() will do any additional
669 if (pqFlush(conn) < 0)
671 pqHandleSendFailure(conn);
675 /* OK, it's launched! */
676 conn->asyncStatus = PGASYNC_BUSY;
682 * Like PQsendQuery, but use protocol 3.0 so we can pass parameters
685 PQsendQueryParams(PGconn *conn,
688 const Oid *paramTypes,
689 const char *const * paramValues,
690 const int *paramLengths,
691 const int *paramFormats,
694 if (!PQsendQueryStart(conn))
699 printfPQExpBuffer(&conn->errorMessage,
700 libpq_gettext("command string is a null pointer\n"));
704 return PQsendQueryGuts(conn,
706 "", /* use unnamed statement */
717 * Submit a Parse message, but don't wait for it to finish
719 * Returns: 1 if successfully submitted
720 * 0 if error (conn->errorMessage is set)
723 PQsendPrepare(PGconn *conn,
724 const char *stmtName, const char *query,
725 int nParams, const Oid *paramTypes)
727 if (!PQsendQueryStart(conn))
732 printfPQExpBuffer(&conn->errorMessage,
733 libpq_gettext("statement name is a null pointer\n"));
739 printfPQExpBuffer(&conn->errorMessage,
740 libpq_gettext("command string is a null pointer\n"));
744 /* This isn't gonna work on a 2.0 server */
745 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
747 printfPQExpBuffer(&conn->errorMessage,
748 libpq_gettext("function requires at least protocol version 3.0\n"));
752 /* construct the Parse message */
753 if (pqPutMsgStart('P', false, conn) < 0 ||
754 pqPuts(stmtName, conn) < 0 ||
755 pqPuts(query, conn) < 0)
758 if (nParams > 0 && paramTypes)
762 if (pqPutInt(nParams, 2, conn) < 0)
764 for (i = 0; i < nParams; i++)
766 if (pqPutInt(paramTypes[i], 4, conn) < 0)
772 if (pqPutInt(0, 2, conn) < 0)
775 if (pqPutMsgEnd(conn) < 0)
778 /* construct the Sync message */
779 if (pqPutMsgStart('S', false, conn) < 0 ||
780 pqPutMsgEnd(conn) < 0)
783 /* remember we are doing just a Parse */
784 conn->queryclass = PGQUERY_PREPARE;
787 * Give the data a push. In nonblock mode, don't complain if we're
788 * unable to send it all; PQgetResult() will do any additional
791 if (pqFlush(conn) < 0)
794 /* OK, it's launched! */
795 conn->asyncStatus = PGASYNC_BUSY;
799 pqHandleSendFailure(conn);
804 * PQsendQueryPrepared
805 * Like PQsendQuery, but execute a previously prepared statement,
806 * using protocol 3.0 so we can pass parameters
809 PQsendQueryPrepared(PGconn *conn,
810 const char *stmtName,
812 const char *const * paramValues,
813 const int *paramLengths,
814 const int *paramFormats,
817 if (!PQsendQueryStart(conn))
822 printfPQExpBuffer(&conn->errorMessage,
823 libpq_gettext("statement name is a null pointer\n"));
827 return PQsendQueryGuts(conn,
828 NULL, /* no command to parse */
831 NULL, /* no param types */
839 * Common startup code for PQsendQuery and sibling routines
842 PQsendQueryStart(PGconn *conn)
847 /* clear the error string */
848 resetPQExpBuffer(&conn->errorMessage);
850 /* Don't try to send if we know there's no live connection. */
851 if (conn->status != CONNECTION_OK)
853 printfPQExpBuffer(&conn->errorMessage,
854 libpq_gettext("no connection to the server\n"));
857 /* Can't send while already busy, either. */
858 if (conn->asyncStatus != PGASYNC_IDLE)
860 printfPQExpBuffer(&conn->errorMessage,
861 libpq_gettext("another command is already in progress\n"));
865 /* initialize async result-accumulation state */
867 conn->curTuple = NULL;
869 /* ready to send command message */
875 * Common code for protocol-3.0 query sending
876 * PQsendQueryStart should be done already
878 * command may be NULL to indicate we use an already-prepared statement
881 PQsendQueryGuts(PGconn *conn,
883 const char *stmtName,
885 const Oid *paramTypes,
886 const char *const * paramValues,
887 const int *paramLengths,
888 const int *paramFormats,
893 /* This isn't gonna work on a 2.0 server */
894 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
896 printfPQExpBuffer(&conn->errorMessage,
897 libpq_gettext("function requires at least protocol version 3.0\n"));
902 * We will send Parse (if needed), Bind, Describe Portal, Execute,
903 * Sync, using specified statement name and the unnamed portal.
908 /* construct the Parse message */
909 if (pqPutMsgStart('P', false, conn) < 0 ||
910 pqPuts(stmtName, conn) < 0 ||
911 pqPuts(command, conn) < 0)
913 if (nParams > 0 && paramTypes)
915 if (pqPutInt(nParams, 2, conn) < 0)
917 for (i = 0; i < nParams; i++)
919 if (pqPutInt(paramTypes[i], 4, conn) < 0)
925 if (pqPutInt(0, 2, conn) < 0)
928 if (pqPutMsgEnd(conn) < 0)
932 /* construct the Bind message */
933 if (pqPutMsgStart('B', false, conn) < 0 ||
934 pqPuts("", conn) < 0 ||
935 pqPuts(stmtName, conn) < 0)
937 if (nParams > 0 && paramFormats)
939 if (pqPutInt(nParams, 2, conn) < 0)
941 for (i = 0; i < nParams; i++)
943 if (pqPutInt(paramFormats[i], 2, conn) < 0)
949 if (pqPutInt(0, 2, conn) < 0)
952 if (pqPutInt(nParams, 2, conn) < 0)
954 for (i = 0; i < nParams; i++)
956 if (paramValues && paramValues[i])
960 if (paramFormats && paramFormats[i] != 0)
962 /* binary parameter */
963 nbytes = paramLengths[i];
967 /* text parameter, do not use paramLengths */
968 nbytes = strlen(paramValues[i]);
970 if (pqPutInt(nbytes, 4, conn) < 0 ||
971 pqPutnchar(paramValues[i], nbytes, conn) < 0)
976 /* take the param as NULL */
977 if (pqPutInt(-1, 4, conn) < 0)
981 if (pqPutInt(1, 2, conn) < 0 ||
982 pqPutInt(resultFormat, 2, conn))
984 if (pqPutMsgEnd(conn) < 0)
987 /* construct the Describe Portal message */
988 if (pqPutMsgStart('D', false, conn) < 0 ||
989 pqPutc('P', conn) < 0 ||
990 pqPuts("", conn) < 0 ||
991 pqPutMsgEnd(conn) < 0)
994 /* construct the Execute message */
995 if (pqPutMsgStart('E', false, conn) < 0 ||
996 pqPuts("", conn) < 0 ||
997 pqPutInt(0, 4, conn) < 0 ||
998 pqPutMsgEnd(conn) < 0)
1001 /* construct the Sync message */
1002 if (pqPutMsgStart('S', false, conn) < 0 ||
1003 pqPutMsgEnd(conn) < 0)
1006 /* remember we are using extended query protocol */
1007 conn->queryclass = PGQUERY_EXTENDED;
1010 * Give the data a push. In nonblock mode, don't complain if we're
1011 * unable to send it all; PQgetResult() will do any additional
1014 if (pqFlush(conn) < 0)
1017 /* OK, it's launched! */
1018 conn->asyncStatus = PGASYNC_BUSY;
1022 pqHandleSendFailure(conn);
1027 * pqHandleSendFailure: try to clean up after failure to send command.
1029 * Primarily, what we want to accomplish here is to process an async
1030 * NOTICE message that the backend might have sent just before it died.
1032 * NOTE: this routine should only be called in PGASYNC_IDLE state.
1035 pqHandleSendFailure(PGconn *conn)
1038 * Accept any available input data, ignoring errors. Note that if
1039 * pqReadData decides the backend has closed the channel, it will
1040 * close our side of the socket --- that's just what we want here.
1042 while (pqReadData(conn) > 0)
1043 /* loop until no more data readable */ ;
1046 * Parse any available input messages. Since we are in PGASYNC_IDLE
1047 * state, only NOTICE and NOTIFY messages will be eaten.
1053 * Consume any available input from the backend
1054 * 0 return: some kind of trouble
1055 * 1 return: no problem
1058 PQconsumeInput(PGconn *conn)
1064 * for non-blocking connections try to flush the send-queue, otherwise
1065 * we may never get a response for something that may not have already
1066 * been sent because it's in our write buffer!
1068 if (pqIsnonblocking(conn))
1070 if (pqFlush(conn) < 0)
1075 * Load more data, if available. We do this no matter what state we
1076 * are in, since we are probably getting called because the
1077 * application wants to get rid of a read-select condition. Note that
1078 * we will NOT block waiting for more input.
1080 if (pqReadData(conn) < 0)
1083 /* Parsing of the data waits till later. */
1089 * parseInput: if appropriate, parse input data from backend
1090 * until input is exhausted or a stopping state is reached.
1091 * Note that this function will NOT attempt to read more data from the backend.
1094 parseInput(PGconn *conn)
1096 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1097 pqParseInput3(conn);
1099 pqParseInput2(conn);
1104 * Return TRUE if PQgetResult would block waiting for input.
1108 PQisBusy(PGconn *conn)
1113 /* Parse any available data, if our state permits. */
1116 /* PQgetResult will return immediately in all states except BUSY. */
1117 return conn->asyncStatus == PGASYNC_BUSY;
1123 * Get the next PGresult produced by a query.
1124 * Returns NULL if and only if no query work remains.
1128 PQgetResult(PGconn *conn)
1135 /* Parse any available data, if our state permits. */
1138 /* If not ready to return something, block until we are. */
1139 while (conn->asyncStatus == PGASYNC_BUSY)
1144 * If data remains unsent, send it. Else we might be waiting for
1145 * the result of a command the backend hasn't even got yet.
1147 while ((flushResult = pqFlush(conn)) > 0)
1149 if (pqWait(FALSE, TRUE, conn))
1156 /* Wait for some more data, and load it. */
1158 pqWait(TRUE, FALSE, conn) ||
1159 pqReadData(conn) < 0)
1162 * conn->errorMessage has been set by pqWait or pqReadData. We
1163 * want to append it to any already-received error message.
1165 pqSaveErrorResult(conn);
1166 conn->asyncStatus = PGASYNC_IDLE;
1167 return pqPrepareAsyncResult(conn);
1174 /* Return the appropriate thing. */
1175 switch (conn->asyncStatus)
1178 res = NULL; /* query is complete */
1181 res = pqPrepareAsyncResult(conn);
1182 /* Set the state back to BUSY, allowing parsing to proceed. */
1183 conn->asyncStatus = PGASYNC_BUSY;
1185 case PGASYNC_COPY_IN:
1186 if (conn->result && conn->result->resultStatus == PGRES_COPY_IN)
1187 res = pqPrepareAsyncResult(conn);
1189 res = PQmakeEmptyPGresult(conn, PGRES_COPY_IN);
1191 case PGASYNC_COPY_OUT:
1192 if (conn->result && conn->result->resultStatus == PGRES_COPY_OUT)
1193 res = pqPrepareAsyncResult(conn);
1195 res = PQmakeEmptyPGresult(conn, PGRES_COPY_OUT);
1198 printfPQExpBuffer(&conn->errorMessage,
1199 libpq_gettext("unexpected asyncStatus: %d\n"),
1200 (int) conn->asyncStatus);
1201 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1211 * send a query to the backend and package up the result in a PGresult
1213 * If the query was not even sent, return NULL; conn->errorMessage is set to
1214 * a relevant message.
1215 * If the query was sent, a new PGresult is returned (which could indicate
1216 * either success or failure).
1217 * The user is responsible for freeing the PGresult via PQclear()
1218 * when done with it.
1221 PQexec(PGconn *conn, const char *query)
1223 if (!PQexecStart(conn))
1225 if (!PQsendQuery(conn, query))
1227 return PQexecFinish(conn);
1232 * Like PQexec, but use protocol 3.0 so we can pass parameters
1235 PQexecParams(PGconn *conn,
1236 const char *command,
1238 const Oid *paramTypes,
1239 const char *const * paramValues,
1240 const int *paramLengths,
1241 const int *paramFormats,
1244 if (!PQexecStart(conn))
1246 if (!PQsendQueryParams(conn, command,
1247 nParams, paramTypes, paramValues, paramLengths,
1248 paramFormats, resultFormat))
1250 return PQexecFinish(conn);
1255 * Creates a prepared statement by issuing a v3.0 parse message.
1257 * If the query was not even sent, return NULL; conn->errorMessage is set to
1258 * a relevant message.
1259 * If the query was sent, a new PGresult is returned (which could indicate
1260 * either success or failure).
1261 * The user is responsible for freeing the PGresult via PQclear()
1262 * when done with it.
1265 PQprepare(PGconn *conn,
1266 const char *stmtName, const char *query,
1267 int nParams, const Oid *paramTypes)
1269 if (!PQexecStart(conn))
1271 if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
1273 return PQexecFinish(conn);
1278 * Like PQexec, but execute a previously prepared statement,
1279 * using protocol 3.0 so we can pass parameters
1282 PQexecPrepared(PGconn *conn,
1283 const char *stmtName,
1285 const char *const * paramValues,
1286 const int *paramLengths,
1287 const int *paramFormats,
1290 if (!PQexecStart(conn))
1292 if (!PQsendQueryPrepared(conn, stmtName,
1293 nParams, paramValues, paramLengths,
1294 paramFormats, resultFormat))
1296 return PQexecFinish(conn);
1300 * Common code for PQexec and sibling routines: prepare to send command
1303 PQexecStart(PGconn *conn)
1311 * Silently discard any prior query result that application didn't
1312 * eat. This is probably poor design, but it's here for backward
1315 while ((result = PQgetResult(conn)) != NULL)
1317 ExecStatusType resultStatus = result->resultStatus;
1319 PQclear(result); /* only need its status */
1320 if (resultStatus == PGRES_COPY_IN)
1322 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1324 /* In protocol 3, we can get out of a COPY IN state */
1325 if (PQputCopyEnd(conn,
1326 libpq_gettext("COPY terminated by new PQexec")) < 0)
1328 /* keep waiting to swallow the copy's failure message */
1332 /* In older protocols we have to punt */
1333 printfPQExpBuffer(&conn->errorMessage,
1334 libpq_gettext("COPY IN state must be terminated first\n"));
1338 else if (resultStatus == PGRES_COPY_OUT)
1340 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1343 * In protocol 3, we can get out of a COPY OUT state: we
1344 * just switch back to BUSY and allow the remaining COPY
1345 * data to be dropped on the floor.
1347 conn->asyncStatus = PGASYNC_BUSY;
1348 /* keep waiting to swallow the copy's completion message */
1352 /* In older protocols we have to punt */
1353 printfPQExpBuffer(&conn->errorMessage,
1354 libpq_gettext("COPY OUT state must be terminated first\n"));
1358 /* check for loss of connection, too */
1359 if (conn->status == CONNECTION_BAD)
1363 /* OK to send a command */
1368 * Common code for PQexec and sibling routines: wait for command result
1371 PQexecFinish(PGconn *conn)
1374 PGresult *lastResult;
1377 * For backwards compatibility, return the last result if there are
1378 * more than one --- but merge error messages if we get more than one
1381 * We have to stop if we see copy in/out, however. We will resume parsing
1382 * after application performs the data transfer.
1384 * Also stop if the connection is lost (else we'll loop infinitely).
1387 while ((result = PQgetResult(conn)) != NULL)
1391 if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
1392 result->resultStatus == PGRES_FATAL_ERROR)
1394 pqCatenateResultError(lastResult, result->errMsg);
1396 result = lastResult;
1399 * Make sure PQerrorMessage agrees with concatenated
1402 resetPQExpBuffer(&conn->errorMessage);
1403 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
1406 PQclear(lastResult);
1408 lastResult = result;
1409 if (result->resultStatus == PGRES_COPY_IN ||
1410 result->resultStatus == PGRES_COPY_OUT ||
1411 conn->status == CONNECTION_BAD)
1420 * returns a PGnotify* structure of the latest async notification
1421 * that has not yet been handled
1423 * returns NULL, if there is currently
1424 * no unhandled async notification from the backend
1426 * the CALLER is responsible for FREE'ing the structure returned
1429 PQnotifies(PGconn *conn)
1436 /* Parse any available data to see if we can extract NOTIFY messages. */
1439 event = conn->notifyHead;
1442 conn->notifyHead = event->next;
1443 if (!conn->notifyHead)
1444 conn->notifyTail = NULL;
1445 event->next = NULL; /* don't let app see the internal state */
1451 * PQputCopyData - send some data to the backend during COPY IN
1453 * Returns 1 if successful, 0 if data could not be sent (only possible
1454 * in nonblock mode), or -1 if an error occurs.
1457 PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
1461 if (conn->asyncStatus != PGASYNC_COPY_IN)
1463 printfPQExpBuffer(&conn->errorMessage,
1464 libpq_gettext("no COPY in progress\n"));
1469 * Check for NOTICE messages coming back from the server. Since the
1470 * server might generate multiple notices during the COPY, we have to
1471 * consume those in a reasonably prompt fashion to prevent the comm
1472 * buffers from filling up and possibly blocking the server.
1474 if (!PQconsumeInput(conn))
1475 return -1; /* I/O failure */
1481 * Try to flush any previously sent data in preference to growing
1482 * the output buffer. If we can't enlarge the buffer enough to
1483 * hold the data, return 0 in the nonblock case, else hard error.
1484 * (For simplicity, always assume 5 bytes of overhead even in
1485 * protocol 2.0 case.)
1487 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
1489 if (pqFlush(conn) < 0)
1491 if (pqCheckOutBufferSpace(conn->outCount + 5 + nbytes, conn))
1492 return pqIsnonblocking(conn) ? 0 : -1;
1494 /* Send the data (too simple to delegate to fe-protocol files) */
1495 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1497 if (pqPutMsgStart('d', false, conn) < 0 ||
1498 pqPutnchar(buffer, nbytes, conn) < 0 ||
1499 pqPutMsgEnd(conn) < 0)
1504 if (pqPutMsgStart(0, false, conn) < 0 ||
1505 pqPutnchar(buffer, nbytes, conn) < 0 ||
1506 pqPutMsgEnd(conn) < 0)
1514 * PQputCopyEnd - send EOF indication to the backend during COPY IN
1516 * After calling this, use PQgetResult() to check command completion status.
1518 * Returns 1 if successful, 0 if data could not be sent (only possible
1519 * in nonblock mode), or -1 if an error occurs.
1522 PQputCopyEnd(PGconn *conn, const char *errormsg)
1526 if (conn->asyncStatus != PGASYNC_COPY_IN)
1528 printfPQExpBuffer(&conn->errorMessage,
1529 libpq_gettext("no COPY in progress\n"));
1534 * Send the COPY END indicator. This is simple enough that we don't
1535 * bother delegating it to the fe-protocol files.
1537 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1541 /* Send COPY FAIL */
1542 if (pqPutMsgStart('f', false, conn) < 0 ||
1543 pqPuts(errormsg, conn) < 0 ||
1544 pqPutMsgEnd(conn) < 0)
1549 /* Send COPY DONE */
1550 if (pqPutMsgStart('c', false, conn) < 0 ||
1551 pqPutMsgEnd(conn) < 0)
1556 * If we sent the COPY command in extended-query mode, we must
1557 * issue a Sync as well.
1559 if (conn->queryclass != PGQUERY_SIMPLE)
1561 if (pqPutMsgStart('S', false, conn) < 0 ||
1562 pqPutMsgEnd(conn) < 0)
1570 /* Ooops, no way to do this in 2.0 */
1571 printfPQExpBuffer(&conn->errorMessage,
1572 libpq_gettext("function requires at least protocol version 3.0\n"));
1577 /* Send old-style end-of-data marker */
1578 if (pqPutMsgStart(0, false, conn) < 0 ||
1579 pqPutnchar("\\.\n", 3, conn) < 0 ||
1580 pqPutMsgEnd(conn) < 0)
1585 /* Return to active duty */
1586 conn->asyncStatus = PGASYNC_BUSY;
1587 resetPQExpBuffer(&conn->errorMessage);
1589 /* Try to flush data */
1590 if (pqFlush(conn) < 0)
1597 * PQgetCopyData - read a row of data from the backend during COPY OUT
1599 * If successful, sets *buffer to point to a malloc'd row of data, and
1600 * returns row length (always > 0) as result.
1601 * Returns 0 if no row available yet (only possible if async is true),
1602 * -1 if end of copy (consult PQgetResult), or -2 if error (consult
1606 PQgetCopyData(PGconn *conn, char **buffer, int async)
1608 *buffer = NULL; /* for all failure cases */
1611 if (conn->asyncStatus != PGASYNC_COPY_OUT)
1613 printfPQExpBuffer(&conn->errorMessage,
1614 libpq_gettext("no COPY in progress\n"));
1617 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1618 return pqGetCopyData3(conn, buffer, async);
1620 return pqGetCopyData2(conn, buffer, async);
1624 * PQgetline - gets a newline-terminated string from the backend.
1626 * Chiefly here so that applications can use "COPY <rel> to stdout"
1627 * and read the output string. Returns a null-terminated string in s.
1629 * XXX this routine is now deprecated, because it can't handle binary data.
1630 * If called during a COPY BINARY we return EOF.
1632 * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
1633 * the terminating \n (like gets(3)).
1635 * CAUTION: the caller is responsible for detecting the end-of-copy signal
1636 * (a line containing just "\.") when using this routine.
1639 * EOF if error (eg, invalid arguments are given)
1640 * 0 if EOL is reached (i.e., \n has been read)
1641 * (this is required for backward-compatibility -- this
1642 * routine used to always return EOF or 0, assuming that
1643 * the line ended within maxlen bytes.)
1644 * 1 in other cases (i.e., the buffer was filled before \n is reached)
1647 PQgetline(PGconn *conn, char *s, int maxlen)
1649 if (!s || maxlen <= 0)
1652 /* maxlen must be at least 3 to hold the \. terminator! */
1659 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1660 return pqGetline3(conn, s, maxlen);
1662 return pqGetline2(conn, s, maxlen);
1666 * PQgetlineAsync - gets a COPY data row without blocking.
1668 * This routine is for applications that want to do "COPY <rel> to stdout"
1669 * asynchronously, that is without blocking. Having issued the COPY command
1670 * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
1671 * and this routine until the end-of-data signal is detected. Unlike
1672 * PQgetline, this routine takes responsibility for detecting end-of-data.
1674 * On each call, PQgetlineAsync will return data if a complete data row
1675 * is available in libpq's input buffer. Otherwise, no data is returned
1676 * until the rest of the row arrives.
1678 * If -1 is returned, the end-of-data signal has been recognized (and removed
1679 * from libpq's input buffer). The caller *must* next call PQendcopy and
1680 * then return to normal processing.
1683 * -1 if the end-of-copy-data marker has been recognized
1684 * 0 if no data is available
1685 * >0 the number of bytes returned.
1687 * The data returned will not extend beyond a data-row boundary. If possible
1688 * a whole row will be returned at one time. But if the buffer offered by
1689 * the caller is too small to hold a row sent by the backend, then a partial
1690 * data row will be returned. In text mode this can be detected by testing
1691 * whether the last returned byte is '\n' or not.
1693 * The returned data is *not* null-terminated.
1697 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
1702 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1703 return pqGetlineAsync3(conn, buffer, bufsize);
1705 return pqGetlineAsync2(conn, buffer, bufsize);
1709 * PQputline -- sends a string to the backend during COPY IN.
1710 * Returns 0 if OK, EOF if not.
1712 * This is deprecated primarily because the return convention doesn't allow
1713 * caller to tell the difference between a hard error and a nonblock-mode
1717 PQputline(PGconn *conn, const char *s)
1719 return PQputnbytes(conn, s, strlen(s));
1723 * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
1724 * Returns 0 if OK, EOF if not.
1727 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
1729 if (PQputCopyData(conn, buffer, nbytes) > 0)
1737 * After completing the data transfer portion of a copy in/out,
1738 * the application must call this routine to finish the command protocol.
1740 * When using protocol 3.0 this is deprecated; it's cleaner to use PQgetResult
1741 * to get the transfer status. Note however that when using 2.0 protocol,
1742 * recovering from a copy failure often requires a PQreset. PQendcopy will
1743 * take care of that, PQgetResult won't.
1750 PQendcopy(PGconn *conn)
1755 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1756 return pqEndcopy3(conn);
1758 return pqEndcopy2(conn);
1763 * PQfn - Send a function call to the POSTGRES backend.
1765 * conn : backend connection
1766 * fnid : function id
1767 * result_buf : pointer to result buffer (&int if integer)
1768 * result_len : length of return value.
1769 * actual_result_len: actual length returned. (differs from result_len
1770 * for varlena structures.)
1771 * result_type : If the result is an integer, this must be 1,
1772 * otherwise this should be 0
1773 * args : pointer to an array of function arguments.
1774 * (each has length, if integer, and value/pointer)
1775 * nargs : # of arguments in args array.
1778 * PGresult with status = PGRES_COMMAND_OK if successful.
1779 * *actual_result_len is > 0 if there is a return value, 0 if not.
1780 * PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
1781 * NULL on communications failure. conn->errorMessage will be set.
1789 int *actual_result_len,
1791 const PQArgBlock *args,
1794 *actual_result_len = 0;
1799 /* clear the error string */
1800 resetPQExpBuffer(&conn->errorMessage);
1802 if (conn->sock < 0 || conn->asyncStatus != PGASYNC_IDLE ||
1803 conn->result != NULL)
1805 printfPQExpBuffer(&conn->errorMessage,
1806 libpq_gettext("connection in wrong state\n"));
1810 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1811 return pqFunctionCall3(conn, fnid,
1812 result_buf, actual_result_len,
1816 return pqFunctionCall2(conn, fnid,
1817 result_buf, actual_result_len,
1823 /* ====== accessor funcs for PGresult ======== */
1826 PQresultStatus(const PGresult *res)
1829 return PGRES_FATAL_ERROR;
1830 return res->resultStatus;
1834 PQresStatus(ExecStatusType status)
1836 if (status < 0 || status >= sizeof pgresStatus / sizeof pgresStatus[0])
1837 return libpq_gettext("invalid ExecStatusType code");
1838 return pgresStatus[status];
1842 PQresultErrorMessage(const PGresult *res)
1844 if (!res || !res->errMsg)
1850 PQresultErrorField(const PGresult *res, int fieldcode)
1852 PGMessageField *pfield;
1856 for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
1858 if (pfield->code == fieldcode)
1859 return pfield->contents;
1865 PQntuples(const PGresult *res)
1873 PQnfields(const PGresult *res)
1877 return res->numAttributes;
1881 PQbinaryTuples(const PGresult *res)
1889 * Helper routines to range-check field numbers and tuple numbers.
1890 * Return TRUE if OK, FALSE if not
1894 check_field_number(const PGresult *res, int field_num)
1897 return FALSE; /* no way to display error message... */
1898 if (field_num < 0 || field_num >= res->numAttributes)
1900 pqInternalNotice(&res->noticeHooks,
1901 "column number %d is out of range 0..%d",
1902 field_num, res->numAttributes - 1);
1909 check_tuple_field_number(const PGresult *res,
1910 int tup_num, int field_num)
1913 return FALSE; /* no way to display error message... */
1914 if (tup_num < 0 || tup_num >= res->ntups)
1916 pqInternalNotice(&res->noticeHooks,
1917 "row number %d is out of range 0..%d",
1918 tup_num, res->ntups - 1);
1921 if (field_num < 0 || field_num >= res->numAttributes)
1923 pqInternalNotice(&res->noticeHooks,
1924 "column number %d is out of range 0..%d",
1925 field_num, res->numAttributes - 1);
1932 * returns NULL if the field_num is invalid
1935 PQfname(const PGresult *res, int field_num)
1937 if (!check_field_number(res, field_num))
1940 return res->attDescs[field_num].name;
1946 * PQfnumber: find column number given column name
1948 * The column name is parsed as if it were in a SQL statement, including
1949 * case-folding and double-quote processing. But note a possible gotcha:
1950 * downcasing in the frontend might follow different locale rules than
1951 * downcasing in the backend...
1953 * Returns -1 if no match. In the present backend it is also possible
1954 * to have multiple matches, in which case the first one is found.
1957 PQfnumber(const PGresult *res, const char *field_name)
1969 * Note: it is correct to reject a zero-length input string; the
1970 * proper input to match a zero-length field name would be "".
1972 if (field_name == NULL ||
1973 field_name[0] == '\0' ||
1974 res->attDescs == NULL)
1978 * Note: this code will not reject partially quoted strings, eg
1979 * foo"BAR"foo will become fooBARfoo when it probably ought to be an
1982 field_case = strdup(field_name);
1983 if (field_case == NULL)
1984 return -1; /* grotty */
1988 for (iptr = field_case; *iptr; iptr++)
1998 /* doubled quotes become a single quote */
2012 c = pg_tolower((unsigned char) c);
2018 for (i = 0; i < res->numAttributes; i++)
2020 if (strcmp(field_case, res->attDescs[i].name) == 0)
2031 PQftable(const PGresult *res, int field_num)
2033 if (!check_field_number(res, field_num))
2036 return res->attDescs[field_num].tableid;
2042 PQftablecol(const PGresult *res, int field_num)
2044 if (!check_field_number(res, field_num))
2047 return res->attDescs[field_num].columnid;
2053 PQfformat(const PGresult *res, int field_num)
2055 if (!check_field_number(res, field_num))
2058 return res->attDescs[field_num].format;
2064 PQftype(const PGresult *res, int field_num)
2066 if (!check_field_number(res, field_num))
2069 return res->attDescs[field_num].typid;
2075 PQfsize(const PGresult *res, int field_num)
2077 if (!check_field_number(res, field_num))
2080 return res->attDescs[field_num].typlen;
2086 PQfmod(const PGresult *res, int field_num)
2088 if (!check_field_number(res, field_num))
2091 return res->attDescs[field_num].atttypmod;
2097 PQcmdStatus(PGresult *res)
2101 return res->cmdStatus;
2106 * if the last command was an INSERT, return the oid string
2110 PQoidStatus(const PGresult *res)
2113 * This must be enough to hold the result. Don't laugh, this is better
2114 * than what this function used to do.
2116 static char buf[24];
2120 if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2123 len = strspn(res->cmdStatus + 7, "0123456789");
2126 strncpy(buf, res->cmdStatus + 7, len);
2134 * a perhaps preferable form of the above which just returns
2138 PQoidValue(const PGresult *res)
2140 char *endptr = NULL;
2141 unsigned long result;
2143 if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2151 result = strtoul(res->cmdStatus + 7, &endptr, 10);
2153 if (!endptr || (*endptr != ' ' && *endptr != '\0') || errno == ERANGE)
2156 return (Oid) result;
2162 * If the last command was an INSERT/UPDATE/DELETE/MOVE/FETCH, return a
2163 * string containing the number of inserted/affected tuples. If not,
2166 * XXX: this should probably return an int
2169 PQcmdTuples(PGresult *res)
2176 if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
2178 p = res->cmdStatus + 6;
2180 /* INSERT: skip oid */
2181 while (*p != ' ' && *p)
2184 else if (strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
2185 strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
2186 p = res->cmdStatus + 6;
2187 else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
2188 p = res->cmdStatus + 5;
2189 else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0)
2190 p = res->cmdStatus + 4;
2198 pqInternalNotice(&res->noticeHooks,
2199 "could not interpret result from server: %s",
2209 * return the value of field 'field_num' of row 'tup_num'
2212 PQgetvalue(const PGresult *res, int tup_num, int field_num)
2214 if (!check_tuple_field_number(res, tup_num, field_num))
2216 return res->tuples[tup_num][field_num].value;
2220 * returns the actual length of a field value in bytes.
2223 PQgetlength(const PGresult *res, int tup_num, int field_num)
2225 if (!check_tuple_field_number(res, tup_num, field_num))
2227 if (res->tuples[tup_num][field_num].len != NULL_LEN)
2228 return res->tuples[tup_num][field_num].len;
2234 * returns the null status of a field value.
2237 PQgetisnull(const PGresult *res, int tup_num, int field_num)
2239 if (!check_tuple_field_number(res, tup_num, field_num))
2240 return 1; /* pretend it is null */
2241 if (res->tuples[tup_num][field_num].len == NULL_LEN)
2247 /* PQsetnonblocking:
2248 * sets the PGconn's database connection non-blocking if the arg is TRUE
2249 * or makes it non-blocking if the arg is FALSE, this will not protect
2250 * you from PQexec(), you'll only be safe when using the non-blocking API.
2251 * Needs to be called only on a connected database connection.
2254 PQsetnonblocking(PGconn *conn, int arg)
2258 if (!conn || conn->status == CONNECTION_BAD)
2261 barg = (arg ? TRUE : FALSE);
2263 /* early out if the socket is already in the state requested */
2264 if (barg == conn->nonblocking)
2268 * to guarantee constancy for flushing/query/result-polling behavior
2269 * we need to flush the send queue at this point in order to guarantee
2270 * proper behavior. this is ok because either they are making a
2271 * transition _from_ or _to_ blocking mode, either way we can block
2274 /* if we are going from blocking to non-blocking flush here */
2278 conn->nonblocking = barg;
2284 * return the blocking status of the database connection
2285 * TRUE == nonblocking, FALSE == blocking
2288 PQisnonblocking(const PGconn *conn)
2290 return (pqIsnonblocking(conn));
2293 /* try to force data out, really only useful for non-blocking users */
2295 PQflush(PGconn *conn)
2297 return (pqFlush(conn));
2302 * PQfreemem - safely frees memory allocated
2304 * Needed mostly by Win32, unless multithreaded DLL (/MD in VC6)
2305 * Used for freeing memory from PQescapeByte()a/PQunescapeBytea()
2308 PQfreemem(void *ptr)
2314 * PQfreeNotify - free's the memory associated with a PGnotify
2316 * This function is here only for binary backward compatibility.
2317 * New code should use PQfreemem(). A macro will automatically map
2318 * calls to PQfreemem. It should be removed in the future. bjm 2003-03-24
2322 void PQfreeNotify(PGnotify *notify);
2325 PQfreeNotify(PGnotify *notify)
2332 * Escaping arbitrary strings to get valid SQL literal strings.
2334 * Replaces "\\" with "\\\\" and "'" with "''".
2336 * length is the length of the source string. (Note: if a terminating NUL
2337 * is encountered sooner, PQescapeString stops short of "length"; the behavior
2338 * is thus rather like strncpy.)
2340 * For safety the buffer at "to" must be at least 2*length + 1 bytes long.
2341 * A terminating NUL character is added to the output string, whether the
2342 * input is NUL-terminated or not.
2344 * Returns the actual length of the output (not counting the terminating NUL).
2347 PQescapeString(char *to, const char *from, size_t length)
2349 const char *source = from;
2351 size_t remaining = length;
2353 while (remaining > 0 && *source != '\0')
2368 *target++ = *source;
2375 /* Write the terminating NUL character. */
2382 * PQescapeBytea - converts from binary string to the
2383 * minimal encoding necessary to include the string in an SQL
2384 * INSERT statement with a bytea type column as the target.
2386 * The following transformations are applied
2387 * '\0' == ASCII 0 == \\000
2388 * '\'' == ASCII 39 == \'
2389 * '\\' == ASCII 92 == \\\\
2390 * anything < 0x20, or > 0x7e ---> \\ooo
2391 * (where ooo is an octal expression)
2394 PQescapeBytea(const unsigned char *bintext, size_t binlen, size_t *bytealen)
2396 const unsigned char *vp;
2398 unsigned char *result;
2403 * empty string has 1 char ('\0')
2408 for (i = binlen; i > 0; i--, vp++)
2410 if (*vp < 0x20 || *vp > 0x7e)
2411 len += 5; /* '5' is for '\\ooo' */
2412 else if (*vp == '\'')
2414 else if (*vp == '\\')
2420 rp = result = (unsigned char *) malloc(len);
2427 for (i = binlen; i > 0; i--, vp++)
2429 if (*vp < 0x20 || *vp > 0x7e)
2431 (void) sprintf(rp, "\\\\%03o", *vp);
2434 else if (*vp == '\'')
2440 else if (*vp == '\\')
2456 #define ISFIRSTOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '3')
2457 #define ISOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '7')
2458 #define OCTVAL(CH) ((CH) - '0')
2461 * PQunescapeBytea - converts the null terminated string representation
2462 * of a bytea, strtext, into binary, filling a buffer. It returns a
2463 * pointer to the buffer (or NULL on error), and the size of the
2464 * buffer in retbuflen. The pointer may subsequently be used as an
2465 * argument to the function free(3). It is the reverse of PQescapeBytea.
2467 * The following transformations are made:
2468 * \\ == ASCII 92 == \
2469 * \ooo == a byte whose value = ooo (ooo is an octal number)
2470 * \x == x (x is any character not matched by the above transformations)
2473 PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
2477 unsigned char *buffer,
2482 if (strtext == NULL)
2485 strtextlen = strlen(strtext);
2488 * Length of input is max length of output, but add one to avoid
2489 * unportable malloc(0) if input is zero-length.
2491 buffer = (unsigned char *) malloc(strtextlen + 1);
2495 for (i = j = 0; i < strtextlen;)
2501 if (strtext[i] == '\\')
2502 buffer[j++] = strtext[i++];
2505 if ((ISFIRSTOCTDIGIT(strtext[i])) &&
2506 (ISOCTDIGIT(strtext[i + 1])) &&
2507 (ISOCTDIGIT(strtext[i + 2])))
2511 byte = OCTVAL(strtext[i++]);
2512 byte = (byte << 3) + OCTVAL(strtext[i++]);
2513 byte = (byte << 3) + OCTVAL(strtext[i++]);
2519 * Note: if we see '\' followed by something that isn't a
2520 * recognized escape sequence, we loop around having done
2521 * nothing except advance i. Therefore the something will
2522 * be emitted as ordinary data on the next cycle. Corner
2523 * case: '\' at end of string will just be discarded.
2528 buffer[j++] = strtext[i++];
2532 buflen = j; /* buflen is the length of the dequoted
2535 /* Shrink the buffer to be no larger than necessary */
2536 /* +1 avoids unportable behavior when buflen==0 */
2537 tmpbuf = realloc(buffer, buflen + 1);
2539 /* It would only be a very brain-dead realloc that could fail, but... */
2546 *retbuflen = buflen;