1 /*-------------------------------------------------------------------------
4 * functions related to sending a query down to the backend
6 * Portions Copyright (c) 1996-2003, 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.156 2003/12/28 17:29:41 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.
117 #define MAX(a,b) ((a) > (b) ? (a) : (b))
119 #define PGRESULT_DATA_BLOCKSIZE 2048
120 #define PGRESULT_ALIGN_BOUNDARY MAXIMUM_ALIGNOF /* from configure */
121 #define PGRESULT_BLOCK_OVERHEAD MAX(sizeof(PGresult_data), PGRESULT_ALIGN_BOUNDARY)
122 #define PGRESULT_SEP_ALLOC_THRESHOLD (PGRESULT_DATA_BLOCKSIZE / 2)
126 * PQmakeEmptyPGresult
127 * returns a newly allocated, initialized PGresult with given status.
128 * If conn is not NULL and status indicates an error, the conn's
129 * errorMessage is copied.
131 * Note this is exported --- you wouldn't think an application would need
132 * to build its own PGresults, but this has proven useful in both libpgtcl
133 * and the Perl5 interface, so maybe it's not so unreasonable.
137 PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
141 result = (PGresult *) malloc(sizeof(PGresult));
144 result->numAttributes = 0;
145 result->attDescs = NULL;
146 result->tuples = NULL;
147 result->tupArrSize = 0;
148 result->resultStatus = status;
149 result->cmdStatus[0] = '\0';
151 result->errMsg = NULL;
152 result->errFields = NULL;
153 result->null_field[0] = '\0';
154 result->curBlock = NULL;
155 result->curOffset = 0;
156 result->spaceLeft = 0;
160 /* copy connection data we might need for operations on PGresult */
161 result->noticeHooks = conn->noticeHooks;
162 result->client_encoding = conn->client_encoding;
164 /* consider copying conn's errorMessage */
167 case PGRES_EMPTY_QUERY:
168 case PGRES_COMMAND_OK:
169 case PGRES_TUPLES_OK:
172 /* non-error cases */
175 pqSetResultError(result, conn->errorMessage.data);
182 result->noticeHooks.noticeRec = NULL;
183 result->noticeHooks.noticeRecArg = NULL;
184 result->noticeHooks.noticeProc = NULL;
185 result->noticeHooks.noticeProcArg = NULL;
186 result->client_encoding = PG_SQL_ASCII;
194 * Allocate subsidiary storage for a PGresult.
196 * nBytes is the amount of space needed for the object.
197 * If isBinary is true, we assume that we need to align the object on
198 * a machine allocation boundary.
199 * If isBinary is false, we assume the object is a char string and can
200 * be allocated on any byte boundary.
203 pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
206 PGresult_data *block;
212 return res->null_field;
215 * If alignment is needed, round up the current position to an
216 * alignment boundary.
220 int offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
224 res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
225 res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
229 /* If there's enough space in the current block, no problem. */
230 if (nBytes <= (size_t) res->spaceLeft)
232 space = res->curBlock->space + res->curOffset;
233 res->curOffset += nBytes;
234 res->spaceLeft -= nBytes;
239 * If the requested object is very large, give it its own block; this
240 * avoids wasting what might be most of the current block to start a
241 * new block. (We'd have to special-case requests bigger than the
242 * block size anyway.) The object is always given binary alignment in
245 if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
247 block = (PGresult_data *) malloc(nBytes + PGRESULT_BLOCK_OVERHEAD);
250 space = block->space + PGRESULT_BLOCK_OVERHEAD;
254 * Tuck special block below the active block, so that we don't
255 * have to waste the free space in the active block.
257 block->next = res->curBlock->next;
258 res->curBlock->next = block;
262 /* Must set up the new block as the first active block. */
264 res->curBlock = block;
265 res->spaceLeft = 0; /* be sure it's marked full */
270 /* Otherwise, start a new block. */
271 block = (PGresult_data *) malloc(PGRESULT_DATA_BLOCKSIZE);
274 block->next = res->curBlock;
275 res->curBlock = block;
278 /* object needs full alignment */
279 res->curOffset = PGRESULT_BLOCK_OVERHEAD;
280 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - PGRESULT_BLOCK_OVERHEAD;
284 /* we can cram it right after the overhead pointer */
285 res->curOffset = sizeof(PGresult_data);
286 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - sizeof(PGresult_data);
289 space = block->space + res->curOffset;
290 res->curOffset += nBytes;
291 res->spaceLeft -= nBytes;
297 * Like strdup, but the space is subsidiary PGresult space.
300 pqResultStrdup(PGresult *res, const char *str)
302 char *space = (char *) pqResultAlloc(res, strlen(str) + 1, FALSE);
311 * assign a new error message to a PGresult
314 pqSetResultError(PGresult *res, const char *msg)
319 res->errMsg = pqResultStrdup(res, msg);
325 * pqCatenateResultError -
326 * concatenate a new error message to the one already in a PGresult
329 pqCatenateResultError(PGresult *res, const char *msg)
331 PQExpBufferData errorBuf;
335 initPQExpBuffer(&errorBuf);
337 appendPQExpBufferStr(&errorBuf, res->errMsg);
338 appendPQExpBufferStr(&errorBuf, msg);
339 pqSetResultError(res, errorBuf.data);
340 termPQExpBuffer(&errorBuf);
345 * free's the memory associated with a PGresult
348 PQclear(PGresult *res)
350 PGresult_data *block;
355 /* Free all the subsidiary blocks */
356 while ((block = res->curBlock) != NULL)
358 res->curBlock = block->next;
362 /* Free the top-level tuple pointer array */
366 /* Free the PGresult structure itself */
371 * Handy subroutine to deallocate any partially constructed async result.
375 pqClearAsyncResult(PGconn *conn)
378 PQclear(conn->result);
380 conn->curTuple = NULL;
384 * This subroutine deletes any existing async result, sets conn->result
385 * to a PGresult with status PGRES_FATAL_ERROR, and stores the current
386 * contents of conn->errorMessage into that result. It differs from a
387 * plain call on PQmakeEmptyPGresult() in that if there is already an
388 * async result with status PGRES_FATAL_ERROR, the current error message
389 * is APPENDED to the old error message instead of replacing it. This
390 * behavior lets us report multiple error conditions properly, if necessary.
391 * (An example where this is needed is when the backend sends an 'E' message
392 * and immediately closes the connection --- we want to report both the
393 * backend error and the connection closure error.)
396 pqSaveErrorResult(PGconn *conn)
399 * If no old async result, just let PQmakeEmptyPGresult make one.
400 * Likewise if old result is not an error message.
402 if (conn->result == NULL ||
403 conn->result->resultStatus != PGRES_FATAL_ERROR ||
404 conn->result->errMsg == NULL)
406 pqClearAsyncResult(conn);
407 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
411 /* Else, concatenate error message to existing async result. */
412 pqCatenateResultError(conn->result, conn->errorMessage.data);
417 * This subroutine prepares an async result object for return to the caller.
418 * If there is not already an async result object, build an error object
419 * using whatever is in conn->errorMessage. In any case, clear the async
420 * result storage and make sure PQerrorMessage will agree with the result's
424 pqPrepareAsyncResult(PGconn *conn)
429 * conn->result is the PGresult to return. If it is NULL (which
430 * probably shouldn't happen) we assume there is an appropriate error
431 * message in conn->errorMessage.
434 conn->result = NULL; /* handing over ownership to caller */
435 conn->curTuple = NULL; /* just in case */
437 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
441 * Make sure PQerrorMessage agrees with result; it could be
442 * different if we have concatenated messages.
444 resetPQExpBuffer(&conn->errorMessage);
445 appendPQExpBufferStr(&conn->errorMessage,
446 PQresultErrorMessage(res));
452 * pqInternalNotice - produce an internally-generated notice message
454 * A format string and optional arguments can be passed. Note that we do
455 * libpq_gettext() here, so callers need not.
457 * The supplied text is taken as primary message (ie., it should not include
458 * a trailing newline, and should not be more than one line).
461 pqInternalNotice(const PGNoticeHooks * hooks, const char *fmt,...)
467 if (hooks->noticeRec == NULL)
468 return; /* nobody home to receive notice? */
470 /* Format the message */
472 vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
474 msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
476 /* Make a PGresult to pass to the notice receiver */
477 res = PQmakeEmptyPGresult(NULL, PGRES_NONFATAL_ERROR);
478 res->noticeHooks = *hooks;
481 * Set up fields of notice.
483 pqSaveMessageField(res, PG_DIAG_MESSAGE_PRIMARY, msgBuf);
484 pqSaveMessageField(res, PG_DIAG_SEVERITY, libpq_gettext("NOTICE"));
485 /* XXX should provide a SQLSTATE too? */
488 * Result text is always just the primary message + newline.
490 res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, FALSE);
491 sprintf(res->errMsg, "%s\n", msgBuf);
494 * Pass to receiver, then free it.
496 (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
502 * add a row pointer to the PGresult structure, growing it if necessary
503 * Returns TRUE if OK, FALSE if not enough memory to add the row
506 pqAddTuple(PGresult *res, PGresAttValue * tup)
508 if (res->ntups >= res->tupArrSize)
511 * Try to grow the array.
513 * We can use realloc because shallow copying of the structure is
514 * okay. Note that the first time through, res->tuples is NULL.
515 * While ANSI says that realloc() should act like malloc() in that
516 * case, some old C libraries (like SunOS 4.1.x) coredump instead.
517 * On failure realloc is supposed to return NULL without damaging
518 * the existing allocation. Note that the positions beyond
519 * res->ntups are garbage, not necessarily NULL.
521 int newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
522 PGresAttValue **newTuples;
524 if (res->tuples == NULL)
525 newTuples = (PGresAttValue **)
526 malloc(newSize * sizeof(PGresAttValue *));
528 newTuples = (PGresAttValue **)
529 realloc(res->tuples, newSize * sizeof(PGresAttValue *));
531 return FALSE; /* malloc or realloc failed */
532 res->tupArrSize = newSize;
533 res->tuples = newTuples;
535 res->tuples[res->ntups] = tup;
541 * pqSaveMessageField - save one field of an error or notice message
544 pqSaveMessageField(PGresult *res, char code, const char *value)
546 PGMessageField *pfield;
548 pfield = (PGMessageField *)
550 sizeof(PGMessageField) + strlen(value),
553 return; /* out of memory? */
555 strcpy(pfield->contents, value);
556 pfield->next = res->errFields;
557 res->errFields = pfield;
561 * pqSaveParameterStatus - remember parameter status sent by backend
564 pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
566 pgParameterStatus *pstatus;
567 pgParameterStatus *prev;
570 fprintf(conn->Pfdebug, "pqSaveParameterStatus: '%s' = '%s'\n",
574 * Forget any old information about the parameter
576 for (pstatus = conn->pstatus, prev = NULL;
578 prev = pstatus, pstatus = pstatus->next)
580 if (strcmp(pstatus->name, name) == 0)
583 prev->next = pstatus->next;
585 conn->pstatus = pstatus->next;
586 free(pstatus); /* frees name and value strings too */
592 * Store new info as a single malloc block
594 pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
595 strlen(name) + strlen(value) + 2);
600 ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
603 ptr += strlen(name) + 1;
604 pstatus->value = ptr;
606 pstatus->next = conn->pstatus;
607 conn->pstatus = pstatus;
611 * Special hacks: remember client_encoding as a numeric value, and
612 * remember at least the first few bytes of server version.
614 if (strcmp(name, "client_encoding") == 0)
615 conn->client_encoding = pg_char_to_encoding(value);
616 if (strcmp(name, "server_version") == 0)
617 StrNCpy(conn->sversion, value, sizeof(conn->sversion));
623 * Submit a query, but don't wait for it to finish
625 * Returns: 1 if successfully submitted
626 * 0 if error (conn->errorMessage is set)
629 PQsendQuery(PGconn *conn, const char *query)
631 if (!PQsendQueryStart(conn))
636 printfPQExpBuffer(&conn->errorMessage,
637 libpq_gettext("command string is a null pointer\n"));
641 /* construct the outgoing Query message */
642 if (pqPutMsgStart('Q', false, conn) < 0 ||
643 pqPuts(query, conn) < 0 ||
644 pqPutMsgEnd(conn) < 0)
646 pqHandleSendFailure(conn);
650 /* remember we are using simple query protocol */
651 conn->ext_query = false;
654 * Give the data a push. In nonblock mode, don't complain if we're
655 * unable to send it all; PQgetResult() will do any additional
658 if (pqFlush(conn) < 0)
660 pqHandleSendFailure(conn);
664 /* OK, it's launched! */
665 conn->asyncStatus = PGASYNC_BUSY;
671 * Like PQsendQuery, but use protocol 3.0 so we can pass parameters
674 PQsendQueryParams(PGconn *conn,
677 const Oid *paramTypes,
678 const char *const * paramValues,
679 const int *paramLengths,
680 const int *paramFormats,
683 if (!PQsendQueryStart(conn))
688 printfPQExpBuffer(&conn->errorMessage,
689 libpq_gettext("command string is a null pointer\n"));
693 return PQsendQueryGuts(conn,
695 "", /* use unnamed statement */
705 * PQsendQueryPrepared
706 * Like PQsendQuery, but execute a previously prepared statement,
707 * using protocol 3.0 so we can pass parameters
710 PQsendQueryPrepared(PGconn *conn,
711 const char *stmtName,
713 const char *const * paramValues,
714 const int *paramLengths,
715 const int *paramFormats,
718 if (!PQsendQueryStart(conn))
723 printfPQExpBuffer(&conn->errorMessage,
724 libpq_gettext("statement name is a null pointer\n"));
728 return PQsendQueryGuts(conn,
729 NULL, /* no command to parse */
732 NULL, /* no param types */
740 * Common startup code for PQsendQuery and sibling routines
743 PQsendQueryStart(PGconn *conn)
748 /* clear the error string */
749 resetPQExpBuffer(&conn->errorMessage);
751 /* Don't try to send if we know there's no live connection. */
752 if (conn->status != CONNECTION_OK)
754 printfPQExpBuffer(&conn->errorMessage,
755 libpq_gettext("no connection to the server\n"));
758 /* Can't send while already busy, either. */
759 if (conn->asyncStatus != PGASYNC_IDLE)
761 printfPQExpBuffer(&conn->errorMessage,
762 libpq_gettext("another command is already in progress\n"));
766 /* initialize async result-accumulation state */
768 conn->curTuple = NULL;
770 /* ready to send command message */
776 * Common code for protocol-3.0 query sending
777 * PQsendQueryStart should be done already
779 * command may be NULL to indicate we use an already-prepared statement
782 PQsendQueryGuts(PGconn *conn,
784 const char *stmtName,
786 const Oid *paramTypes,
787 const char *const * paramValues,
788 const int *paramLengths,
789 const int *paramFormats,
794 /* This isn't gonna work on a 2.0 server */
795 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
797 printfPQExpBuffer(&conn->errorMessage,
798 libpq_gettext("function requires at least protocol version 3.0\n"));
803 * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync,
804 * using specified statement name and the unnamed portal.
809 /* construct the Parse message */
810 if (pqPutMsgStart('P', false, conn) < 0 ||
811 pqPuts(stmtName, conn) < 0 ||
812 pqPuts(command, conn) < 0)
814 if (nParams > 0 && paramTypes)
816 if (pqPutInt(nParams, 2, conn) < 0)
818 for (i = 0; i < nParams; i++)
820 if (pqPutInt(paramTypes[i], 4, conn) < 0)
826 if (pqPutInt(0, 2, conn) < 0)
829 if (pqPutMsgEnd(conn) < 0)
833 /* construct the Bind message */
834 if (pqPutMsgStart('B', false, conn) < 0 ||
835 pqPuts("", conn) < 0 ||
836 pqPuts(stmtName, conn) < 0)
838 if (nParams > 0 && paramFormats)
840 if (pqPutInt(nParams, 2, conn) < 0)
842 for (i = 0; i < nParams; i++)
844 if (pqPutInt(paramFormats[i], 2, conn) < 0)
850 if (pqPutInt(0, 2, conn) < 0)
853 if (pqPutInt(nParams, 2, conn) < 0)
855 for (i = 0; i < nParams; i++)
857 if (paramValues && paramValues[i])
861 if (paramFormats && paramFormats[i] != 0)
863 /* binary parameter */
864 nbytes = paramLengths[i];
868 /* text parameter, do not use paramLengths */
869 nbytes = strlen(paramValues[i]);
871 if (pqPutInt(nbytes, 4, conn) < 0 ||
872 pqPutnchar(paramValues[i], nbytes, conn) < 0)
877 /* take the param as NULL */
878 if (pqPutInt(-1, 4, conn) < 0)
882 if (pqPutInt(1, 2, conn) < 0 ||
883 pqPutInt(resultFormat, 2, conn))
885 if (pqPutMsgEnd(conn) < 0)
888 /* construct the Describe Portal message */
889 if (pqPutMsgStart('D', false, conn) < 0 ||
890 pqPutc('P', conn) < 0 ||
891 pqPuts("", conn) < 0 ||
892 pqPutMsgEnd(conn) < 0)
895 /* construct the Execute message */
896 if (pqPutMsgStart('E', false, conn) < 0 ||
897 pqPuts("", conn) < 0 ||
898 pqPutInt(0, 4, conn) < 0 ||
899 pqPutMsgEnd(conn) < 0)
902 /* construct the Sync message */
903 if (pqPutMsgStart('S', false, conn) < 0 ||
904 pqPutMsgEnd(conn) < 0)
907 /* remember we are using extended query protocol */
908 conn->ext_query = true;
911 * Give the data a push. In nonblock mode, don't complain if we're
912 * unable to send it all; PQgetResult() will do any additional
915 if (pqFlush(conn) < 0)
918 /* OK, it's launched! */
919 conn->asyncStatus = PGASYNC_BUSY;
923 pqHandleSendFailure(conn);
928 * pqHandleSendFailure: try to clean up after failure to send command.
930 * Primarily, what we want to accomplish here is to process an async
931 * NOTICE message that the backend might have sent just before it died.
933 * NOTE: this routine should only be called in PGASYNC_IDLE state.
936 pqHandleSendFailure(PGconn *conn)
939 * Accept any available input data, ignoring errors. Note that if
940 * pqReadData decides the backend has closed the channel, it will
941 * close our side of the socket --- that's just what we want here.
943 while (pqReadData(conn) > 0)
944 /* loop until no more data readable */ ;
947 * Parse any available input messages. Since we are in PGASYNC_IDLE
948 * state, only NOTICE and NOTIFY messages will be eaten.
954 * Consume any available input from the backend
955 * 0 return: some kind of trouble
956 * 1 return: no problem
959 PQconsumeInput(PGconn *conn)
965 * for non-blocking connections try to flush the send-queue, otherwise
966 * we may never get a response for something that may not have already
967 * been sent because it's in our write buffer!
969 if (pqIsnonblocking(conn))
971 if (pqFlush(conn) < 0)
976 * Load more data, if available. We do this no matter what state we
977 * are in, since we are probably getting called because the
978 * application wants to get rid of a read-select condition. Note that
979 * we will NOT block waiting for more input.
981 if (pqReadData(conn) < 0)
984 /* Parsing of the data waits till later. */
990 * parseInput: if appropriate, parse input data from backend
991 * until input is exhausted or a stopping state is reached.
992 * Note that this function will NOT attempt to read more data from the backend.
995 parseInput(PGconn *conn)
997 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1000 pqParseInput2(conn);
1005 * Return TRUE if PQgetResult would block waiting for input.
1009 PQisBusy(PGconn *conn)
1014 /* Parse any available data, if our state permits. */
1017 /* PQgetResult will return immediately in all states except BUSY. */
1018 return conn->asyncStatus == PGASYNC_BUSY;
1024 * Get the next PGresult produced by a query.
1025 * Returns NULL if and only if no query work remains.
1029 PQgetResult(PGconn *conn)
1036 /* Parse any available data, if our state permits. */
1039 /* If not ready to return something, block until we are. */
1040 while (conn->asyncStatus == PGASYNC_BUSY)
1045 * If data remains unsent, send it. Else we might be waiting for
1046 * the result of a command the backend hasn't even got yet.
1048 while ((flushResult = pqFlush(conn)) > 0)
1050 if (pqWait(FALSE, TRUE, conn))
1057 /* Wait for some more data, and load it. */
1059 pqWait(TRUE, FALSE, conn) ||
1060 pqReadData(conn) < 0)
1063 * conn->errorMessage has been set by pqWait or pqReadData. We
1064 * want to append it to any already-received error message.
1066 pqSaveErrorResult(conn);
1067 conn->asyncStatus = PGASYNC_IDLE;
1068 return pqPrepareAsyncResult(conn);
1075 /* Return the appropriate thing. */
1076 switch (conn->asyncStatus)
1079 res = NULL; /* query is complete */
1082 res = pqPrepareAsyncResult(conn);
1083 /* Set the state back to BUSY, allowing parsing to proceed. */
1084 conn->asyncStatus = PGASYNC_BUSY;
1086 case PGASYNC_COPY_IN:
1087 if (conn->result && conn->result->resultStatus == PGRES_COPY_IN)
1088 res = pqPrepareAsyncResult(conn);
1090 res = PQmakeEmptyPGresult(conn, PGRES_COPY_IN);
1092 case PGASYNC_COPY_OUT:
1093 if (conn->result && conn->result->resultStatus == PGRES_COPY_OUT)
1094 res = pqPrepareAsyncResult(conn);
1096 res = PQmakeEmptyPGresult(conn, PGRES_COPY_OUT);
1099 printfPQExpBuffer(&conn->errorMessage,
1100 libpq_gettext("unexpected asyncStatus: %d\n"),
1101 (int) conn->asyncStatus);
1102 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1112 * send a query to the backend and package up the result in a PGresult
1114 * If the query was not even sent, return NULL; conn->errorMessage is set to
1115 * a relevant message.
1116 * If the query was sent, a new PGresult is returned (which could indicate
1117 * either success or failure).
1118 * The user is responsible for freeing the PGresult via PQclear()
1119 * when done with it.
1123 PQexec(PGconn *conn, const char *query)
1125 if (!PQexecStart(conn))
1127 if (!PQsendQuery(conn, query))
1129 return PQexecFinish(conn);
1134 * Like PQexec, but use protocol 3.0 so we can pass parameters
1137 PQexecParams(PGconn *conn,
1138 const char *command,
1140 const Oid *paramTypes,
1141 const char *const * paramValues,
1142 const int *paramLengths,
1143 const int *paramFormats,
1146 if (!PQexecStart(conn))
1148 if (!PQsendQueryParams(conn, command,
1149 nParams, paramTypes, paramValues, paramLengths,
1150 paramFormats, resultFormat))
1152 return PQexecFinish(conn);
1157 * Like PQexec, but execute a previously prepared statement,
1158 * using protocol 3.0 so we can pass parameters
1161 PQexecPrepared(PGconn *conn,
1162 const char *stmtName,
1164 const char *const * paramValues,
1165 const int *paramLengths,
1166 const int *paramFormats,
1169 if (!PQexecStart(conn))
1171 if (!PQsendQueryPrepared(conn, stmtName,
1172 nParams, paramValues, paramLengths,
1173 paramFormats, resultFormat))
1175 return PQexecFinish(conn);
1179 * Common code for PQexec and sibling routines: prepare to send command
1182 PQexecStart(PGconn *conn)
1190 * Silently discard any prior query result that application didn't
1191 * eat. This is probably poor design, but it's here for backward
1194 while ((result = PQgetResult(conn)) != NULL)
1196 ExecStatusType resultStatus = result->resultStatus;
1198 PQclear(result); /* only need its status */
1199 if (resultStatus == PGRES_COPY_IN)
1201 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1203 /* In protocol 3, we can get out of a COPY IN state */
1204 if (PQputCopyEnd(conn,
1205 libpq_gettext("COPY terminated by new PQexec")) < 0)
1207 /* keep waiting to swallow the copy's failure message */
1211 /* In older protocols we have to punt */
1212 printfPQExpBuffer(&conn->errorMessage,
1213 libpq_gettext("COPY IN state must be terminated first\n"));
1217 else if (resultStatus == PGRES_COPY_OUT)
1219 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1222 * In protocol 3, we can get out of a COPY OUT state: we
1223 * just switch back to BUSY and allow the remaining COPY
1224 * data to be dropped on the floor.
1226 conn->asyncStatus = PGASYNC_BUSY;
1227 /* keep waiting to swallow the copy's completion message */
1231 /* In older protocols we have to punt */
1232 printfPQExpBuffer(&conn->errorMessage,
1233 libpq_gettext("COPY OUT state must be terminated first\n"));
1237 /* check for loss of connection, too */
1238 if (conn->status == CONNECTION_BAD)
1242 /* OK to send a command */
1247 * Common code for PQexec and sibling routines: wait for command result
1250 PQexecFinish(PGconn *conn)
1253 PGresult *lastResult;
1256 * For backwards compatibility, return the last result if there are
1257 * more than one --- but merge error messages if we get more than one
1260 * We have to stop if we see copy in/out, however. We will resume parsing
1261 * after application performs the data transfer.
1263 * Also stop if the connection is lost (else we'll loop infinitely).
1266 while ((result = PQgetResult(conn)) != NULL)
1270 if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
1271 result->resultStatus == PGRES_FATAL_ERROR)
1273 pqCatenateResultError(lastResult, result->errMsg);
1275 result = lastResult;
1278 * Make sure PQerrorMessage agrees with concatenated
1281 resetPQExpBuffer(&conn->errorMessage);
1282 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
1285 PQclear(lastResult);
1287 lastResult = result;
1288 if (result->resultStatus == PGRES_COPY_IN ||
1289 result->resultStatus == PGRES_COPY_OUT ||
1290 conn->status == CONNECTION_BAD)
1299 * returns a PGnotify* structure of the latest async notification
1300 * that has not yet been handled
1302 * returns NULL, if there is currently
1303 * no unhandled async notification from the backend
1305 * the CALLER is responsible for FREE'ing the structure returned
1308 PQnotifies(PGconn *conn)
1316 /* Parse any available data to see if we can extract NOTIFY messages. */
1319 /* RemHead returns NULL if list is empty */
1320 e = DLRemHead(conn->notifyList);
1323 event = (PGnotify *) DLE_VAL(e);
1329 * PQputCopyData - send some data to the backend during COPY IN
1331 * Returns 1 if successful, 0 if data could not be sent (only possible
1332 * in nonblock mode), or -1 if an error occurs.
1335 PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
1339 if (conn->asyncStatus != PGASYNC_COPY_IN)
1341 printfPQExpBuffer(&conn->errorMessage,
1342 libpq_gettext("no COPY in progress\n"));
1347 * Check for NOTICE messages coming back from the server. Since the
1348 * server might generate multiple notices during the COPY, we have to
1349 * consume those in a reasonably prompt fashion to prevent the comm
1350 * buffers from filling up and possibly blocking the server.
1352 if (!PQconsumeInput(conn))
1353 return -1; /* I/O failure */
1359 * Try to flush any previously sent data in preference to growing
1360 * the output buffer. If we can't enlarge the buffer enough to
1361 * hold the data, return 0 in the nonblock case, else hard error.
1362 * (For simplicity, always assume 5 bytes of overhead even in
1363 * protocol 2.0 case.)
1365 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
1367 if (pqFlush(conn) < 0)
1369 if (pqCheckOutBufferSpace(conn->outCount + 5 + nbytes, conn))
1370 return pqIsnonblocking(conn) ? 0 : -1;
1372 /* Send the data (too simple to delegate to fe-protocol files) */
1373 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1375 if (pqPutMsgStart('d', false, conn) < 0 ||
1376 pqPutnchar(buffer, nbytes, conn) < 0 ||
1377 pqPutMsgEnd(conn) < 0)
1382 if (pqPutMsgStart(0, false, conn) < 0 ||
1383 pqPutnchar(buffer, nbytes, conn) < 0 ||
1384 pqPutMsgEnd(conn) < 0)
1392 * PQputCopyEnd - send EOF indication to the backend during COPY IN
1394 * After calling this, use PQgetResult() to check command completion status.
1396 * Returns 1 if successful, 0 if data could not be sent (only possible
1397 * in nonblock mode), or -1 if an error occurs.
1400 PQputCopyEnd(PGconn *conn, const char *errormsg)
1404 if (conn->asyncStatus != PGASYNC_COPY_IN)
1406 printfPQExpBuffer(&conn->errorMessage,
1407 libpq_gettext("no COPY in progress\n"));
1412 * Send the COPY END indicator. This is simple enough that we don't
1413 * bother delegating it to the fe-protocol files.
1415 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1419 /* Send COPY FAIL */
1420 if (pqPutMsgStart('f', false, conn) < 0 ||
1421 pqPuts(errormsg, conn) < 0 ||
1422 pqPutMsgEnd(conn) < 0)
1427 /* Send COPY DONE */
1428 if (pqPutMsgStart('c', false, conn) < 0 ||
1429 pqPutMsgEnd(conn) < 0)
1433 * If we sent the COPY command in extended-query mode, we must
1434 * issue a Sync as well.
1436 if (conn->ext_query)
1438 if (pqPutMsgStart('S', false, conn) < 0 ||
1439 pqPutMsgEnd(conn) < 0)
1447 /* Ooops, no way to do this in 2.0 */
1448 printfPQExpBuffer(&conn->errorMessage,
1449 libpq_gettext("function requires at least protocol version 3.0\n"));
1454 /* Send old-style end-of-data marker */
1455 if (pqPutMsgStart(0, false, conn) < 0 ||
1456 pqPuts("\\.\n", conn) < 0 ||
1457 pqPutMsgEnd(conn) < 0)
1462 /* Return to active duty */
1463 conn->asyncStatus = PGASYNC_BUSY;
1464 resetPQExpBuffer(&conn->errorMessage);
1466 /* Try to flush data */
1467 if (pqFlush(conn) < 0)
1474 * PQgetCopyData - read a row of data from the backend during COPY OUT
1476 * If successful, sets *buffer to point to a malloc'd row of data, and
1477 * returns row length (always > 0) as result.
1478 * Returns 0 if no row available yet (only possible if async is true),
1479 * -1 if end of copy (consult PQgetResult), or -2 if error (consult
1483 PQgetCopyData(PGconn *conn, char **buffer, int async)
1485 *buffer = NULL; /* for all failure cases */
1488 if (conn->asyncStatus != PGASYNC_COPY_OUT)
1490 printfPQExpBuffer(&conn->errorMessage,
1491 libpq_gettext("no COPY in progress\n"));
1494 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1495 return pqGetCopyData3(conn, buffer, async);
1497 return pqGetCopyData2(conn, buffer, async);
1501 * PQgetline - gets a newline-terminated string from the backend.
1503 * Chiefly here so that applications can use "COPY <rel> to stdout"
1504 * and read the output string. Returns a null-terminated string in s.
1506 * XXX this routine is now deprecated, because it can't handle binary data.
1507 * If called during a COPY BINARY we return EOF.
1509 * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
1510 * the terminating \n (like gets(3)).
1512 * CAUTION: the caller is responsible for detecting the end-of-copy signal
1513 * (a line containing just "\.") when using this routine.
1516 * EOF if error (eg, invalid arguments are given)
1517 * 0 if EOL is reached (i.e., \n has been read)
1518 * (this is required for backward-compatibility -- this
1519 * routine used to always return EOF or 0, assuming that
1520 * the line ended within maxlen bytes.)
1521 * 1 in other cases (i.e., the buffer was filled before \n is reached)
1524 PQgetline(PGconn *conn, char *s, int maxlen)
1526 if (!s || maxlen <= 0)
1529 /* maxlen must be at least 3 to hold the \. terminator! */
1536 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1537 return pqGetline3(conn, s, maxlen);
1539 return pqGetline2(conn, s, maxlen);
1543 * PQgetlineAsync - gets a COPY data row without blocking.
1545 * This routine is for applications that want to do "COPY <rel> to stdout"
1546 * asynchronously, that is without blocking. Having issued the COPY command
1547 * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
1548 * and this routine until the end-of-data signal is detected. Unlike
1549 * PQgetline, this routine takes responsibility for detecting end-of-data.
1551 * On each call, PQgetlineAsync will return data if a complete data row
1552 * is available in libpq's input buffer. Otherwise, no data is returned
1553 * until the rest of the row arrives.
1555 * If -1 is returned, the end-of-data signal has been recognized (and removed
1556 * from libpq's input buffer). The caller *must* next call PQendcopy and
1557 * then return to normal processing.
1560 * -1 if the end-of-copy-data marker has been recognized
1561 * 0 if no data is available
1562 * >0 the number of bytes returned.
1564 * The data returned will not extend beyond a data-row boundary. If possible
1565 * a whole row will be returned at one time. But if the buffer offered by
1566 * the caller is too small to hold a row sent by the backend, then a partial
1567 * data row will be returned. In text mode this can be detected by testing
1568 * whether the last returned byte is '\n' or not.
1570 * The returned data is *not* null-terminated.
1574 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
1579 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1580 return pqGetlineAsync3(conn, buffer, bufsize);
1582 return pqGetlineAsync2(conn, buffer, bufsize);
1586 * PQputline -- sends a string to the backend during COPY IN.
1587 * Returns 0 if OK, EOF if not.
1589 * This is deprecated primarily because the return convention doesn't allow
1590 * caller to tell the difference between a hard error and a nonblock-mode
1594 PQputline(PGconn *conn, const char *s)
1596 return PQputnbytes(conn, s, strlen(s));
1600 * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
1601 * Returns 0 if OK, EOF if not.
1604 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
1606 if (PQputCopyData(conn, buffer, nbytes) > 0)
1614 * After completing the data transfer portion of a copy in/out,
1615 * the application must call this routine to finish the command protocol.
1617 * When using protocol 3.0 this is deprecated; it's cleaner to use PQgetResult
1618 * to get the transfer status. Note however that when using 2.0 protocol,
1619 * recovering from a copy failure often requires a PQreset. PQendcopy will
1620 * take care of that, PQgetResult won't.
1627 PQendcopy(PGconn *conn)
1632 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1633 return pqEndcopy3(conn);
1635 return pqEndcopy2(conn);
1640 * PQfn - Send a function call to the POSTGRES backend.
1642 * conn : backend connection
1643 * fnid : function id
1644 * result_buf : pointer to result buffer (&int if integer)
1645 * result_len : length of return value.
1646 * actual_result_len: actual length returned. (differs from result_len
1647 * for varlena structures.)
1648 * result_type : If the result is an integer, this must be 1,
1649 * otherwise this should be 0
1650 * args : pointer to an array of function arguments.
1651 * (each has length, if integer, and value/pointer)
1652 * nargs : # of arguments in args array.
1655 * PGresult with status = PGRES_COMMAND_OK if successful.
1656 * *actual_result_len is > 0 if there is a return value, 0 if not.
1657 * PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
1658 * NULL on communications failure. conn->errorMessage will be set.
1666 int *actual_result_len,
1668 const PQArgBlock *args,
1671 *actual_result_len = 0;
1676 /* clear the error string */
1677 resetPQExpBuffer(&conn->errorMessage);
1679 if (conn->sock < 0 || conn->asyncStatus != PGASYNC_IDLE ||
1680 conn->result != NULL)
1682 printfPQExpBuffer(&conn->errorMessage,
1683 libpq_gettext("connection in wrong state\n"));
1687 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1688 return pqFunctionCall3(conn, fnid,
1689 result_buf, actual_result_len,
1693 return pqFunctionCall2(conn, fnid,
1694 result_buf, actual_result_len,
1700 /* ====== accessor funcs for PGresult ======== */
1703 PQresultStatus(const PGresult *res)
1706 return PGRES_FATAL_ERROR;
1707 return res->resultStatus;
1711 PQresStatus(ExecStatusType status)
1713 if (status < 0 || status >= sizeof pgresStatus / sizeof pgresStatus[0])
1714 return libpq_gettext("invalid ExecStatusType code");
1715 return pgresStatus[status];
1719 PQresultErrorMessage(const PGresult *res)
1721 if (!res || !res->errMsg)
1727 PQresultErrorField(const PGresult *res, int fieldcode)
1729 PGMessageField *pfield;
1733 for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
1735 if (pfield->code == fieldcode)
1736 return pfield->contents;
1742 PQntuples(const PGresult *res)
1750 PQnfields(const PGresult *res)
1754 return res->numAttributes;
1758 PQbinaryTuples(const PGresult *res)
1766 * Helper routines to range-check field numbers and tuple numbers.
1767 * Return TRUE if OK, FALSE if not
1771 check_field_number(const PGresult *res, int field_num)
1774 return FALSE; /* no way to display error message... */
1775 if (field_num < 0 || field_num >= res->numAttributes)
1777 pqInternalNotice(&res->noticeHooks,
1778 "column number %d is out of range 0..%d",
1779 field_num, res->numAttributes - 1);
1786 check_tuple_field_number(const PGresult *res,
1787 int tup_num, int field_num)
1790 return FALSE; /* no way to display error message... */
1791 if (tup_num < 0 || tup_num >= res->ntups)
1793 pqInternalNotice(&res->noticeHooks,
1794 "row number %d is out of range 0..%d",
1795 tup_num, res->ntups - 1);
1798 if (field_num < 0 || field_num >= res->numAttributes)
1800 pqInternalNotice(&res->noticeHooks,
1801 "column number %d is out of range 0..%d",
1802 field_num, res->numAttributes - 1);
1809 * returns NULL if the field_num is invalid
1812 PQfname(const PGresult *res, int field_num)
1814 if (!check_field_number(res, field_num))
1817 return res->attDescs[field_num].name;
1823 * PQfnumber: find column number given column name
1825 * The column name is parsed as if it were in a SQL statement, including
1826 * case-folding and double-quote processing. But note a possible gotcha:
1827 * downcasing in the frontend might follow different locale rules than
1828 * downcasing in the backend...
1830 * Returns -1 if no match. In the present backend it is also possible
1831 * to have multiple matches, in which case the first one is found.
1834 PQfnumber(const PGresult *res, const char *field_name)
1846 * Note: it is correct to reject a zero-length input string; the proper
1847 * input to match a zero-length field name would be "".
1849 if (field_name == NULL ||
1850 field_name[0] == '\0' ||
1851 res->attDescs == NULL)
1855 * Note: this code will not reject partially quoted strings, eg
1856 * foo"BAR"foo will become fooBARfoo when it probably ought to be
1857 * an error condition.
1859 field_case = strdup(field_name);
1860 if (field_case == NULL)
1861 return -1; /* grotty */
1865 for (iptr = field_case; *iptr; iptr++)
1875 /* doubled quotes become a single quote */
1891 if (isupper((unsigned char) c))
1892 c = tolower((unsigned char) c);
1898 for (i = 0; i < res->numAttributes; i++)
1900 if (strcmp(field_case, res->attDescs[i].name) == 0)
1911 PQftable(const PGresult *res, int field_num)
1913 if (!check_field_number(res, field_num))
1916 return res->attDescs[field_num].tableid;
1922 PQftablecol(const PGresult *res, int field_num)
1924 if (!check_field_number(res, field_num))
1927 return res->attDescs[field_num].columnid;
1933 PQfformat(const PGresult *res, int field_num)
1935 if (!check_field_number(res, field_num))
1938 return res->attDescs[field_num].format;
1944 PQftype(const PGresult *res, int field_num)
1946 if (!check_field_number(res, field_num))
1949 return res->attDescs[field_num].typid;
1955 PQfsize(const PGresult *res, int field_num)
1957 if (!check_field_number(res, field_num))
1960 return res->attDescs[field_num].typlen;
1966 PQfmod(const PGresult *res, int field_num)
1968 if (!check_field_number(res, field_num))
1971 return res->attDescs[field_num].atttypmod;
1977 PQcmdStatus(PGresult *res)
1981 return res->cmdStatus;
1986 * if the last command was an INSERT, return the oid string
1990 PQoidStatus(const PGresult *res)
1993 * This must be enough to hold the result. Don't laugh, this is better
1994 * than what this function used to do.
1996 static char buf[24];
2000 if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2003 len = strspn(res->cmdStatus + 7, "0123456789");
2006 strncpy(buf, res->cmdStatus + 7, len);
2014 * a perhaps preferable form of the above which just returns
2018 PQoidValue(const PGresult *res)
2020 char *endptr = NULL;
2021 unsigned long result;
2023 if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2031 result = strtoul(res->cmdStatus + 7, &endptr, 10);
2033 if (!endptr || (*endptr != ' ' && *endptr != '\0') || errno == ERANGE)
2036 return (Oid) result;
2042 * If the last command was an INSERT/UPDATE/DELETE/MOVE/FETCH, return a
2043 * string containing the number of inserted/affected tuples. If not,
2046 * XXX: this should probably return an int
2049 PQcmdTuples(PGresult *res)
2056 if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
2058 p = res->cmdStatus + 6;
2060 /* INSERT: skip oid */
2061 while (*p != ' ' && *p)
2064 else if (strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
2065 strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
2066 p = res->cmdStatus + 6;
2067 else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
2068 p = res->cmdStatus + 5;
2069 else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0)
2070 p = res->cmdStatus + 4;
2078 pqInternalNotice(&res->noticeHooks,
2079 "could not interpret result from server: %s",
2089 * return the value of field 'field_num' of row 'tup_num'
2092 PQgetvalue(const PGresult *res, int tup_num, int field_num)
2094 if (!check_tuple_field_number(res, tup_num, field_num))
2096 return res->tuples[tup_num][field_num].value;
2100 * returns the actual length of a field value in bytes.
2103 PQgetlength(const PGresult *res, int tup_num, int field_num)
2105 if (!check_tuple_field_number(res, tup_num, field_num))
2107 if (res->tuples[tup_num][field_num].len != NULL_LEN)
2108 return res->tuples[tup_num][field_num].len;
2114 * returns the null status of a field value.
2117 PQgetisnull(const PGresult *res, int tup_num, int field_num)
2119 if (!check_tuple_field_number(res, tup_num, field_num))
2120 return 1; /* pretend it is null */
2121 if (res->tuples[tup_num][field_num].len == NULL_LEN)
2127 /* PQsetnonblocking:
2128 * sets the PGconn's database connection non-blocking if the arg is TRUE
2129 * or makes it non-blocking if the arg is FALSE, this will not protect
2130 * you from PQexec(), you'll only be safe when using the non-blocking API.
2131 * Needs to be called only on a connected database connection.
2134 PQsetnonblocking(PGconn *conn, int arg)
2138 if (!conn || conn->status == CONNECTION_BAD)
2141 barg = (arg ? TRUE : FALSE);
2143 /* early out if the socket is already in the state requested */
2144 if (barg == conn->nonblocking)
2148 * to guarantee constancy for flushing/query/result-polling behavior
2149 * we need to flush the send queue at this point in order to guarantee
2150 * proper behavior. this is ok because either they are making a
2151 * transition _from_ or _to_ blocking mode, either way we can block
2154 /* if we are going from blocking to non-blocking flush here */
2158 conn->nonblocking = barg;
2164 * return the blocking status of the database connection
2165 * TRUE == nonblocking, FALSE == blocking
2168 PQisnonblocking(const PGconn *conn)
2170 return (pqIsnonblocking(conn));
2173 /* try to force data out, really only useful for non-blocking users */
2175 PQflush(PGconn *conn)
2177 return (pqFlush(conn));
2182 * PQfreemem - safely frees memory allocated
2184 * Needed mostly by Win32, unless multithreaded DLL (/MD in VC6)
2185 * Used for freeing memory from PQescapeByte()a/PQunescapeBytea()
2188 PQfreemem(void *ptr)
2194 * PQfreeNotify - free's the memory associated with a PGnotify
2196 * This function is here only for binary backward compatibility.
2197 * New code should use PQfreemem(). A macro will automatically map
2198 * calls to PQfreemem. It should be removed in the future. bjm 2003-03-24
2202 void PQfreeNotify(PGnotify *notify);
2205 PQfreeNotify(PGnotify *notify)
2212 * Escaping arbitrary strings to get valid SQL literal strings.
2214 * Replaces "\\" with "\\\\" and "'" with "''".
2216 * length is the length of the source string. (Note: if a terminating NUL
2217 * is encountered sooner, PQescapeString stops short of "length"; the behavior
2218 * is thus rather like strncpy.)
2220 * For safety the buffer at "to" must be at least 2*length + 1 bytes long.
2221 * A terminating NUL character is added to the output string, whether the
2222 * input is NUL-terminated or not.
2224 * Returns the actual length of the output (not counting the terminating NUL).
2227 PQescapeString(char *to, const char *from, size_t length)
2229 const char *source = from;
2231 size_t remaining = length;
2233 while (remaining > 0 && *source != '\0')
2248 *target++ = *source;
2255 /* Write the terminating NUL character. */
2262 * PQescapeBytea - converts from binary string to the
2263 * minimal encoding necessary to include the string in an SQL
2264 * INSERT statement with a bytea type column as the target.
2266 * The following transformations are applied
2267 * '\0' == ASCII 0 == \\000
2268 * '\'' == ASCII 39 == \'
2269 * '\\' == ASCII 92 == \\\\
2270 * anything < 0x20, or > 0x7e ---> \\ooo
2271 * (where ooo is an octal expression)
2274 PQescapeBytea(const unsigned char *bintext, size_t binlen, size_t *bytealen)
2276 const unsigned char *vp;
2278 unsigned char *result;
2283 * empty string has 1 char ('\0')
2288 for (i = binlen; i > 0; i--, vp++)
2290 if (*vp < 0x20 || *vp > 0x7e)
2291 len += 5; /* '5' is for '\\ooo' */
2292 else if (*vp == '\'')
2294 else if (*vp == '\\')
2300 rp = result = (unsigned char *) malloc(len);
2307 for (i = binlen; i > 0; i--, vp++)
2309 if (*vp < 0x20 || *vp > 0x7e)
2311 (void) sprintf(rp, "\\\\%03o", *vp);
2314 else if (*vp == '\'')
2320 else if (*vp == '\\')
2336 #define ISFIRSTOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '3')
2337 #define ISOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '7')
2338 #define OCTVAL(CH) ((CH) - '0')
2341 * PQunescapeBytea - converts the null terminated string representation
2342 * of a bytea, strtext, into binary, filling a buffer. It returns a
2343 * pointer to the buffer (or NULL on error), and the size of the
2344 * buffer in retbuflen. The pointer may subsequently be used as an
2345 * argument to the function free(3). It is the reverse of PQescapeBytea.
2347 * The following transformations are made:
2348 * \\ == ASCII 92 == \
2349 * \ooo == a byte whose value = ooo (ooo is an octal number)
2350 * \x == x (x is any character not matched by the above transformations)
2353 PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
2357 unsigned char *buffer,
2362 if (strtext == NULL)
2365 strtextlen = strlen(strtext);
2367 * Length of input is max length of output, but add one to avoid
2368 * unportable malloc(0) if input is zero-length.
2370 buffer = (unsigned char *) malloc(strtextlen + 1);
2374 for (i = j = 0; i < strtextlen; )
2380 if (strtext[i] == '\\')
2381 buffer[j++] = strtext[i++];
2384 if ((ISFIRSTOCTDIGIT(strtext[i])) &&
2385 (ISOCTDIGIT(strtext[i + 1])) &&
2386 (ISOCTDIGIT(strtext[i + 2])))
2390 byte = OCTVAL(strtext[i++]);
2391 byte = (byte << 3) + OCTVAL(strtext[i++]);
2392 byte = (byte << 3) + OCTVAL(strtext[i++]);
2397 * Note: if we see '\' followed by something that isn't
2398 * a recognized escape sequence, we loop around having
2399 * done nothing except advance i. Therefore the something
2400 * will be emitted as ordinary data on the next cycle.
2401 * Corner case: '\' at end of string will just be discarded.
2406 buffer[j++] = strtext[i++];
2410 buflen = j; /* buflen is the length of the dequoted
2413 /* Shrink the buffer to be no larger than necessary */
2414 /* +1 avoids unportable behavior when buflen==0 */
2415 tmpbuf = realloc(buffer, buflen + 1);
2417 /* It would only be a very brain-dead realloc that could fail, but... */
2424 *retbuflen = buflen;