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.163 2004/10/16 22:52:53 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 * convert server version to a numeric form as well.
614 if (strcmp(name, "client_encoding") == 0)
615 conn->client_encoding = pg_char_to_encoding(value);
616 else if (strcmp(name, "server_version") == 0)
623 cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
626 conn->sversion = 0; /* unknown */
631 conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
639 * Submit a query, but don't wait for it to finish
641 * Returns: 1 if successfully submitted
642 * 0 if error (conn->errorMessage is set)
645 PQsendQuery(PGconn *conn, const char *query)
647 if (!PQsendQueryStart(conn))
652 printfPQExpBuffer(&conn->errorMessage,
653 libpq_gettext("command string is a null pointer\n"));
657 /* construct the outgoing Query message */
658 if (pqPutMsgStart('Q', false, conn) < 0 ||
659 pqPuts(query, conn) < 0 ||
660 pqPutMsgEnd(conn) < 0)
662 pqHandleSendFailure(conn);
666 /* remember we are using simple query protocol */
667 conn->ext_query = false;
670 * Give the data a push. In nonblock mode, don't complain if we're
671 * unable to send it all; PQgetResult() will do any additional
674 if (pqFlush(conn) < 0)
676 pqHandleSendFailure(conn);
680 /* OK, it's launched! */
681 conn->asyncStatus = PGASYNC_BUSY;
687 * Like PQsendQuery, but use protocol 3.0 so we can pass parameters
690 PQsendQueryParams(PGconn *conn,
693 const Oid *paramTypes,
694 const char *const * paramValues,
695 const int *paramLengths,
696 const int *paramFormats,
699 if (!PQsendQueryStart(conn))
704 printfPQExpBuffer(&conn->errorMessage,
705 libpq_gettext("command string is a null pointer\n"));
709 return PQsendQueryGuts(conn,
711 "", /* use unnamed statement */
721 * PQsendQueryPrepared
722 * Like PQsendQuery, but execute a previously prepared statement,
723 * using protocol 3.0 so we can pass parameters
726 PQsendQueryPrepared(PGconn *conn,
727 const char *stmtName,
729 const char *const * paramValues,
730 const int *paramLengths,
731 const int *paramFormats,
734 if (!PQsendQueryStart(conn))
739 printfPQExpBuffer(&conn->errorMessage,
740 libpq_gettext("statement name is a null pointer\n"));
744 return PQsendQueryGuts(conn,
745 NULL, /* no command to parse */
748 NULL, /* no param types */
756 * Common startup code for PQsendQuery and sibling routines
759 PQsendQueryStart(PGconn *conn)
764 /* clear the error string */
765 resetPQExpBuffer(&conn->errorMessage);
767 /* Don't try to send if we know there's no live connection. */
768 if (conn->status != CONNECTION_OK)
770 printfPQExpBuffer(&conn->errorMessage,
771 libpq_gettext("no connection to the server\n"));
774 /* Can't send while already busy, either. */
775 if (conn->asyncStatus != PGASYNC_IDLE)
777 printfPQExpBuffer(&conn->errorMessage,
778 libpq_gettext("another command is already in progress\n"));
782 /* initialize async result-accumulation state */
784 conn->curTuple = NULL;
786 /* ready to send command message */
792 * Common code for protocol-3.0 query sending
793 * PQsendQueryStart should be done already
795 * command may be NULL to indicate we use an already-prepared statement
798 PQsendQueryGuts(PGconn *conn,
800 const char *stmtName,
802 const Oid *paramTypes,
803 const char *const * paramValues,
804 const int *paramLengths,
805 const int *paramFormats,
810 /* This isn't gonna work on a 2.0 server */
811 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
813 printfPQExpBuffer(&conn->errorMessage,
814 libpq_gettext("function requires at least protocol version 3.0\n"));
819 * We will send Parse (if needed), Bind, Describe Portal, Execute,
820 * Sync, using specified statement name and the unnamed portal.
825 /* construct the Parse message */
826 if (pqPutMsgStart('P', false, conn) < 0 ||
827 pqPuts(stmtName, conn) < 0 ||
828 pqPuts(command, conn) < 0)
830 if (nParams > 0 && paramTypes)
832 if (pqPutInt(nParams, 2, conn) < 0)
834 for (i = 0; i < nParams; i++)
836 if (pqPutInt(paramTypes[i], 4, conn) < 0)
842 if (pqPutInt(0, 2, conn) < 0)
845 if (pqPutMsgEnd(conn) < 0)
849 /* construct the Bind message */
850 if (pqPutMsgStart('B', false, conn) < 0 ||
851 pqPuts("", conn) < 0 ||
852 pqPuts(stmtName, conn) < 0)
854 if (nParams > 0 && paramFormats)
856 if (pqPutInt(nParams, 2, conn) < 0)
858 for (i = 0; i < nParams; i++)
860 if (pqPutInt(paramFormats[i], 2, conn) < 0)
866 if (pqPutInt(0, 2, conn) < 0)
869 if (pqPutInt(nParams, 2, conn) < 0)
871 for (i = 0; i < nParams; i++)
873 if (paramValues && paramValues[i])
877 if (paramFormats && paramFormats[i] != 0)
879 /* binary parameter */
880 nbytes = paramLengths[i];
884 /* text parameter, do not use paramLengths */
885 nbytes = strlen(paramValues[i]);
887 if (pqPutInt(nbytes, 4, conn) < 0 ||
888 pqPutnchar(paramValues[i], nbytes, conn) < 0)
893 /* take the param as NULL */
894 if (pqPutInt(-1, 4, conn) < 0)
898 if (pqPutInt(1, 2, conn) < 0 ||
899 pqPutInt(resultFormat, 2, conn))
901 if (pqPutMsgEnd(conn) < 0)
904 /* construct the Describe Portal message */
905 if (pqPutMsgStart('D', false, conn) < 0 ||
906 pqPutc('P', conn) < 0 ||
907 pqPuts("", conn) < 0 ||
908 pqPutMsgEnd(conn) < 0)
911 /* construct the Execute message */
912 if (pqPutMsgStart('E', false, conn) < 0 ||
913 pqPuts("", conn) < 0 ||
914 pqPutInt(0, 4, conn) < 0 ||
915 pqPutMsgEnd(conn) < 0)
918 /* construct the Sync message */
919 if (pqPutMsgStart('S', false, conn) < 0 ||
920 pqPutMsgEnd(conn) < 0)
923 /* remember we are using extended query protocol */
924 conn->ext_query = true;
927 * Give the data a push. In nonblock mode, don't complain if we're
928 * unable to send it all; PQgetResult() will do any additional
931 if (pqFlush(conn) < 0)
934 /* OK, it's launched! */
935 conn->asyncStatus = PGASYNC_BUSY;
939 pqHandleSendFailure(conn);
944 * pqHandleSendFailure: try to clean up after failure to send command.
946 * Primarily, what we want to accomplish here is to process an async
947 * NOTICE message that the backend might have sent just before it died.
949 * NOTE: this routine should only be called in PGASYNC_IDLE state.
952 pqHandleSendFailure(PGconn *conn)
955 * Accept any available input data, ignoring errors. Note that if
956 * pqReadData decides the backend has closed the channel, it will
957 * close our side of the socket --- that's just what we want here.
959 while (pqReadData(conn) > 0)
960 /* loop until no more data readable */ ;
963 * Parse any available input messages. Since we are in PGASYNC_IDLE
964 * state, only NOTICE and NOTIFY messages will be eaten.
970 * Consume any available input from the backend
971 * 0 return: some kind of trouble
972 * 1 return: no problem
975 PQconsumeInput(PGconn *conn)
981 * for non-blocking connections try to flush the send-queue, otherwise
982 * we may never get a response for something that may not have already
983 * been sent because it's in our write buffer!
985 if (pqIsnonblocking(conn))
987 if (pqFlush(conn) < 0)
992 * Load more data, if available. We do this no matter what state we
993 * are in, since we are probably getting called because the
994 * application wants to get rid of a read-select condition. Note that
995 * we will NOT block waiting for more input.
997 if (pqReadData(conn) < 0)
1000 /* Parsing of the data waits till later. */
1006 * parseInput: if appropriate, parse input data from backend
1007 * until input is exhausted or a stopping state is reached.
1008 * Note that this function will NOT attempt to read more data from the backend.
1011 parseInput(PGconn *conn)
1013 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1014 pqParseInput3(conn);
1016 pqParseInput2(conn);
1021 * Return TRUE if PQgetResult would block waiting for input.
1025 PQisBusy(PGconn *conn)
1030 /* Parse any available data, if our state permits. */
1033 /* PQgetResult will return immediately in all states except BUSY. */
1034 return conn->asyncStatus == PGASYNC_BUSY;
1040 * Get the next PGresult produced by a query.
1041 * Returns NULL if and only if no query work remains.
1045 PQgetResult(PGconn *conn)
1052 /* Parse any available data, if our state permits. */
1055 /* If not ready to return something, block until we are. */
1056 while (conn->asyncStatus == PGASYNC_BUSY)
1061 * If data remains unsent, send it. Else we might be waiting for
1062 * the result of a command the backend hasn't even got yet.
1064 while ((flushResult = pqFlush(conn)) > 0)
1066 if (pqWait(FALSE, TRUE, conn))
1073 /* Wait for some more data, and load it. */
1075 pqWait(TRUE, FALSE, conn) ||
1076 pqReadData(conn) < 0)
1079 * conn->errorMessage has been set by pqWait or pqReadData. We
1080 * want to append it to any already-received error message.
1082 pqSaveErrorResult(conn);
1083 conn->asyncStatus = PGASYNC_IDLE;
1084 return pqPrepareAsyncResult(conn);
1091 /* Return the appropriate thing. */
1092 switch (conn->asyncStatus)
1095 res = NULL; /* query is complete */
1098 res = pqPrepareAsyncResult(conn);
1099 /* Set the state back to BUSY, allowing parsing to proceed. */
1100 conn->asyncStatus = PGASYNC_BUSY;
1102 case PGASYNC_COPY_IN:
1103 if (conn->result && conn->result->resultStatus == PGRES_COPY_IN)
1104 res = pqPrepareAsyncResult(conn);
1106 res = PQmakeEmptyPGresult(conn, PGRES_COPY_IN);
1108 case PGASYNC_COPY_OUT:
1109 if (conn->result && conn->result->resultStatus == PGRES_COPY_OUT)
1110 res = pqPrepareAsyncResult(conn);
1112 res = PQmakeEmptyPGresult(conn, PGRES_COPY_OUT);
1115 printfPQExpBuffer(&conn->errorMessage,
1116 libpq_gettext("unexpected asyncStatus: %d\n"),
1117 (int) conn->asyncStatus);
1118 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1128 * send a query to the backend and package up the result in a PGresult
1130 * If the query was not even sent, return NULL; conn->errorMessage is set to
1131 * a relevant message.
1132 * If the query was sent, a new PGresult is returned (which could indicate
1133 * either success or failure).
1134 * The user is responsible for freeing the PGresult via PQclear()
1135 * when done with it.
1139 PQexec(PGconn *conn, const char *query)
1141 if (!PQexecStart(conn))
1143 if (!PQsendQuery(conn, query))
1145 return PQexecFinish(conn);
1150 * Like PQexec, but use protocol 3.0 so we can pass parameters
1153 PQexecParams(PGconn *conn,
1154 const char *command,
1156 const Oid *paramTypes,
1157 const char *const * paramValues,
1158 const int *paramLengths,
1159 const int *paramFormats,
1162 if (!PQexecStart(conn))
1164 if (!PQsendQueryParams(conn, command,
1165 nParams, paramTypes, paramValues, paramLengths,
1166 paramFormats, resultFormat))
1168 return PQexecFinish(conn);
1173 * Like PQexec, but execute a previously prepared statement,
1174 * using protocol 3.0 so we can pass parameters
1177 PQexecPrepared(PGconn *conn,
1178 const char *stmtName,
1180 const char *const * paramValues,
1181 const int *paramLengths,
1182 const int *paramFormats,
1185 if (!PQexecStart(conn))
1187 if (!PQsendQueryPrepared(conn, stmtName,
1188 nParams, paramValues, paramLengths,
1189 paramFormats, resultFormat))
1191 return PQexecFinish(conn);
1195 * Common code for PQexec and sibling routines: prepare to send command
1198 PQexecStart(PGconn *conn)
1206 * Silently discard any prior query result that application didn't
1207 * eat. This is probably poor design, but it's here for backward
1210 while ((result = PQgetResult(conn)) != NULL)
1212 ExecStatusType resultStatus = result->resultStatus;
1214 PQclear(result); /* only need its status */
1215 if (resultStatus == PGRES_COPY_IN)
1217 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1219 /* In protocol 3, we can get out of a COPY IN state */
1220 if (PQputCopyEnd(conn,
1221 libpq_gettext("COPY terminated by new PQexec")) < 0)
1223 /* keep waiting to swallow the copy's failure message */
1227 /* In older protocols we have to punt */
1228 printfPQExpBuffer(&conn->errorMessage,
1229 libpq_gettext("COPY IN state must be terminated first\n"));
1233 else if (resultStatus == PGRES_COPY_OUT)
1235 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1238 * In protocol 3, we can get out of a COPY OUT state: we
1239 * just switch back to BUSY and allow the remaining COPY
1240 * data to be dropped on the floor.
1242 conn->asyncStatus = PGASYNC_BUSY;
1243 /* keep waiting to swallow the copy's completion message */
1247 /* In older protocols we have to punt */
1248 printfPQExpBuffer(&conn->errorMessage,
1249 libpq_gettext("COPY OUT state must be terminated first\n"));
1253 /* check for loss of connection, too */
1254 if (conn->status == CONNECTION_BAD)
1258 /* OK to send a command */
1263 * Common code for PQexec and sibling routines: wait for command result
1266 PQexecFinish(PGconn *conn)
1269 PGresult *lastResult;
1272 * For backwards compatibility, return the last result if there are
1273 * more than one --- but merge error messages if we get more than one
1276 * We have to stop if we see copy in/out, however. We will resume parsing
1277 * after application performs the data transfer.
1279 * Also stop if the connection is lost (else we'll loop infinitely).
1282 while ((result = PQgetResult(conn)) != NULL)
1286 if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
1287 result->resultStatus == PGRES_FATAL_ERROR)
1289 pqCatenateResultError(lastResult, result->errMsg);
1291 result = lastResult;
1294 * Make sure PQerrorMessage agrees with concatenated
1297 resetPQExpBuffer(&conn->errorMessage);
1298 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
1301 PQclear(lastResult);
1303 lastResult = result;
1304 if (result->resultStatus == PGRES_COPY_IN ||
1305 result->resultStatus == PGRES_COPY_OUT ||
1306 conn->status == CONNECTION_BAD)
1315 * returns a PGnotify* structure of the latest async notification
1316 * that has not yet been handled
1318 * returns NULL, if there is currently
1319 * no unhandled async notification from the backend
1321 * the CALLER is responsible for FREE'ing the structure returned
1324 PQnotifies(PGconn *conn)
1331 /* Parse any available data to see if we can extract NOTIFY messages. */
1334 event = conn->notifyHead;
1337 conn->notifyHead = event->next;
1338 if (!conn->notifyHead)
1339 conn->notifyTail = NULL;
1340 event->next = NULL; /* don't let app see the internal state */
1346 * PQputCopyData - send some data to the backend during COPY IN
1348 * Returns 1 if successful, 0 if data could not be sent (only possible
1349 * in nonblock mode), or -1 if an error occurs.
1352 PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
1356 if (conn->asyncStatus != PGASYNC_COPY_IN)
1358 printfPQExpBuffer(&conn->errorMessage,
1359 libpq_gettext("no COPY in progress\n"));
1364 * Check for NOTICE messages coming back from the server. Since the
1365 * server might generate multiple notices during the COPY, we have to
1366 * consume those in a reasonably prompt fashion to prevent the comm
1367 * buffers from filling up and possibly blocking the server.
1369 if (!PQconsumeInput(conn))
1370 return -1; /* I/O failure */
1376 * Try to flush any previously sent data in preference to growing
1377 * the output buffer. If we can't enlarge the buffer enough to
1378 * hold the data, return 0 in the nonblock case, else hard error.
1379 * (For simplicity, always assume 5 bytes of overhead even in
1380 * protocol 2.0 case.)
1382 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
1384 if (pqFlush(conn) < 0)
1386 if (pqCheckOutBufferSpace(conn->outCount + 5 + nbytes, conn))
1387 return pqIsnonblocking(conn) ? 0 : -1;
1389 /* Send the data (too simple to delegate to fe-protocol files) */
1390 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1392 if (pqPutMsgStart('d', false, conn) < 0 ||
1393 pqPutnchar(buffer, nbytes, conn) < 0 ||
1394 pqPutMsgEnd(conn) < 0)
1399 if (pqPutMsgStart(0, false, conn) < 0 ||
1400 pqPutnchar(buffer, nbytes, conn) < 0 ||
1401 pqPutMsgEnd(conn) < 0)
1409 * PQputCopyEnd - send EOF indication to the backend during COPY IN
1411 * After calling this, use PQgetResult() to check command completion status.
1413 * Returns 1 if successful, 0 if data could not be sent (only possible
1414 * in nonblock mode), or -1 if an error occurs.
1417 PQputCopyEnd(PGconn *conn, const char *errormsg)
1421 if (conn->asyncStatus != PGASYNC_COPY_IN)
1423 printfPQExpBuffer(&conn->errorMessage,
1424 libpq_gettext("no COPY in progress\n"));
1429 * Send the COPY END indicator. This is simple enough that we don't
1430 * bother delegating it to the fe-protocol files.
1432 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1436 /* Send COPY FAIL */
1437 if (pqPutMsgStart('f', false, conn) < 0 ||
1438 pqPuts(errormsg, conn) < 0 ||
1439 pqPutMsgEnd(conn) < 0)
1444 /* Send COPY DONE */
1445 if (pqPutMsgStart('c', false, conn) < 0 ||
1446 pqPutMsgEnd(conn) < 0)
1451 * If we sent the COPY command in extended-query mode, we must
1452 * issue a Sync as well.
1454 if (conn->ext_query)
1456 if (pqPutMsgStart('S', false, conn) < 0 ||
1457 pqPutMsgEnd(conn) < 0)
1465 /* Ooops, no way to do this in 2.0 */
1466 printfPQExpBuffer(&conn->errorMessage,
1467 libpq_gettext("function requires at least protocol version 3.0\n"));
1472 /* Send old-style end-of-data marker */
1473 if (pqPutMsgStart(0, false, conn) < 0 ||
1474 pqPutnchar("\\.\n", 3, conn) < 0 ||
1475 pqPutMsgEnd(conn) < 0)
1480 /* Return to active duty */
1481 conn->asyncStatus = PGASYNC_BUSY;
1482 resetPQExpBuffer(&conn->errorMessage);
1484 /* Try to flush data */
1485 if (pqFlush(conn) < 0)
1492 * PQgetCopyData - read a row of data from the backend during COPY OUT
1494 * If successful, sets *buffer to point to a malloc'd row of data, and
1495 * returns row length (always > 0) as result.
1496 * Returns 0 if no row available yet (only possible if async is true),
1497 * -1 if end of copy (consult PQgetResult), or -2 if error (consult
1501 PQgetCopyData(PGconn *conn, char **buffer, int async)
1503 *buffer = NULL; /* for all failure cases */
1506 if (conn->asyncStatus != PGASYNC_COPY_OUT)
1508 printfPQExpBuffer(&conn->errorMessage,
1509 libpq_gettext("no COPY in progress\n"));
1512 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1513 return pqGetCopyData3(conn, buffer, async);
1515 return pqGetCopyData2(conn, buffer, async);
1519 * PQgetline - gets a newline-terminated string from the backend.
1521 * Chiefly here so that applications can use "COPY <rel> to stdout"
1522 * and read the output string. Returns a null-terminated string in s.
1524 * XXX this routine is now deprecated, because it can't handle binary data.
1525 * If called during a COPY BINARY we return EOF.
1527 * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
1528 * the terminating \n (like gets(3)).
1530 * CAUTION: the caller is responsible for detecting the end-of-copy signal
1531 * (a line containing just "\.") when using this routine.
1534 * EOF if error (eg, invalid arguments are given)
1535 * 0 if EOL is reached (i.e., \n has been read)
1536 * (this is required for backward-compatibility -- this
1537 * routine used to always return EOF or 0, assuming that
1538 * the line ended within maxlen bytes.)
1539 * 1 in other cases (i.e., the buffer was filled before \n is reached)
1542 PQgetline(PGconn *conn, char *s, int maxlen)
1544 if (!s || maxlen <= 0)
1547 /* maxlen must be at least 3 to hold the \. terminator! */
1554 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1555 return pqGetline3(conn, s, maxlen);
1557 return pqGetline2(conn, s, maxlen);
1561 * PQgetlineAsync - gets a COPY data row without blocking.
1563 * This routine is for applications that want to do "COPY <rel> to stdout"
1564 * asynchronously, that is without blocking. Having issued the COPY command
1565 * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
1566 * and this routine until the end-of-data signal is detected. Unlike
1567 * PQgetline, this routine takes responsibility for detecting end-of-data.
1569 * On each call, PQgetlineAsync will return data if a complete data row
1570 * is available in libpq's input buffer. Otherwise, no data is returned
1571 * until the rest of the row arrives.
1573 * If -1 is returned, the end-of-data signal has been recognized (and removed
1574 * from libpq's input buffer). The caller *must* next call PQendcopy and
1575 * then return to normal processing.
1578 * -1 if the end-of-copy-data marker has been recognized
1579 * 0 if no data is available
1580 * >0 the number of bytes returned.
1582 * The data returned will not extend beyond a data-row boundary. If possible
1583 * a whole row will be returned at one time. But if the buffer offered by
1584 * the caller is too small to hold a row sent by the backend, then a partial
1585 * data row will be returned. In text mode this can be detected by testing
1586 * whether the last returned byte is '\n' or not.
1588 * The returned data is *not* null-terminated.
1592 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
1597 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1598 return pqGetlineAsync3(conn, buffer, bufsize);
1600 return pqGetlineAsync2(conn, buffer, bufsize);
1604 * PQputline -- sends a string to the backend during COPY IN.
1605 * Returns 0 if OK, EOF if not.
1607 * This is deprecated primarily because the return convention doesn't allow
1608 * caller to tell the difference between a hard error and a nonblock-mode
1612 PQputline(PGconn *conn, const char *s)
1614 return PQputnbytes(conn, s, strlen(s));
1618 * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
1619 * Returns 0 if OK, EOF if not.
1622 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
1624 if (PQputCopyData(conn, buffer, nbytes) > 0)
1632 * After completing the data transfer portion of a copy in/out,
1633 * the application must call this routine to finish the command protocol.
1635 * When using protocol 3.0 this is deprecated; it's cleaner to use PQgetResult
1636 * to get the transfer status. Note however that when using 2.0 protocol,
1637 * recovering from a copy failure often requires a PQreset. PQendcopy will
1638 * take care of that, PQgetResult won't.
1645 PQendcopy(PGconn *conn)
1650 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1651 return pqEndcopy3(conn);
1653 return pqEndcopy2(conn);
1658 * PQfn - Send a function call to the POSTGRES backend.
1660 * conn : backend connection
1661 * fnid : function id
1662 * result_buf : pointer to result buffer (&int if integer)
1663 * result_len : length of return value.
1664 * actual_result_len: actual length returned. (differs from result_len
1665 * for varlena structures.)
1666 * result_type : If the result is an integer, this must be 1,
1667 * otherwise this should be 0
1668 * args : pointer to an array of function arguments.
1669 * (each has length, if integer, and value/pointer)
1670 * nargs : # of arguments in args array.
1673 * PGresult with status = PGRES_COMMAND_OK if successful.
1674 * *actual_result_len is > 0 if there is a return value, 0 if not.
1675 * PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
1676 * NULL on communications failure. conn->errorMessage will be set.
1684 int *actual_result_len,
1686 const PQArgBlock *args,
1689 *actual_result_len = 0;
1694 /* clear the error string */
1695 resetPQExpBuffer(&conn->errorMessage);
1697 if (conn->sock < 0 || conn->asyncStatus != PGASYNC_IDLE ||
1698 conn->result != NULL)
1700 printfPQExpBuffer(&conn->errorMessage,
1701 libpq_gettext("connection in wrong state\n"));
1705 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1706 return pqFunctionCall3(conn, fnid,
1707 result_buf, actual_result_len,
1711 return pqFunctionCall2(conn, fnid,
1712 result_buf, actual_result_len,
1718 /* ====== accessor funcs for PGresult ======== */
1721 PQresultStatus(const PGresult *res)
1724 return PGRES_FATAL_ERROR;
1725 return res->resultStatus;
1729 PQresStatus(ExecStatusType status)
1731 if (status < 0 || status >= sizeof pgresStatus / sizeof pgresStatus[0])
1732 return libpq_gettext("invalid ExecStatusType code");
1733 return pgresStatus[status];
1737 PQresultErrorMessage(const PGresult *res)
1739 if (!res || !res->errMsg)
1745 PQresultErrorField(const PGresult *res, int fieldcode)
1747 PGMessageField *pfield;
1751 for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
1753 if (pfield->code == fieldcode)
1754 return pfield->contents;
1760 PQntuples(const PGresult *res)
1768 PQnfields(const PGresult *res)
1772 return res->numAttributes;
1776 PQbinaryTuples(const PGresult *res)
1784 * Helper routines to range-check field numbers and tuple numbers.
1785 * Return TRUE if OK, FALSE if not
1789 check_field_number(const PGresult *res, int field_num)
1792 return FALSE; /* no way to display error message... */
1793 if (field_num < 0 || field_num >= res->numAttributes)
1795 pqInternalNotice(&res->noticeHooks,
1796 "column number %d is out of range 0..%d",
1797 field_num, res->numAttributes - 1);
1804 check_tuple_field_number(const PGresult *res,
1805 int tup_num, int field_num)
1808 return FALSE; /* no way to display error message... */
1809 if (tup_num < 0 || tup_num >= res->ntups)
1811 pqInternalNotice(&res->noticeHooks,
1812 "row number %d is out of range 0..%d",
1813 tup_num, res->ntups - 1);
1816 if (field_num < 0 || field_num >= res->numAttributes)
1818 pqInternalNotice(&res->noticeHooks,
1819 "column number %d is out of range 0..%d",
1820 field_num, res->numAttributes - 1);
1827 * returns NULL if the field_num is invalid
1830 PQfname(const PGresult *res, int field_num)
1832 if (!check_field_number(res, field_num))
1835 return res->attDescs[field_num].name;
1841 * PQfnumber: find column number given column name
1843 * The column name is parsed as if it were in a SQL statement, including
1844 * case-folding and double-quote processing. But note a possible gotcha:
1845 * downcasing in the frontend might follow different locale rules than
1846 * downcasing in the backend...
1848 * Returns -1 if no match. In the present backend it is also possible
1849 * to have multiple matches, in which case the first one is found.
1852 PQfnumber(const PGresult *res, const char *field_name)
1864 * Note: it is correct to reject a zero-length input string; the
1865 * proper input to match a zero-length field name would be "".
1867 if (field_name == NULL ||
1868 field_name[0] == '\0' ||
1869 res->attDescs == NULL)
1873 * Note: this code will not reject partially quoted strings, eg
1874 * foo"BAR"foo will become fooBARfoo when it probably ought to be an
1877 field_case = strdup(field_name);
1878 if (field_case == NULL)
1879 return -1; /* grotty */
1883 for (iptr = field_case; *iptr; iptr++)
1893 /* doubled quotes become a single quote */
1907 c = pg_tolower((unsigned char) c);
1913 for (i = 0; i < res->numAttributes; i++)
1915 if (strcmp(field_case, res->attDescs[i].name) == 0)
1926 PQftable(const PGresult *res, int field_num)
1928 if (!check_field_number(res, field_num))
1931 return res->attDescs[field_num].tableid;
1937 PQftablecol(const PGresult *res, int field_num)
1939 if (!check_field_number(res, field_num))
1942 return res->attDescs[field_num].columnid;
1948 PQfformat(const PGresult *res, int field_num)
1950 if (!check_field_number(res, field_num))
1953 return res->attDescs[field_num].format;
1959 PQftype(const PGresult *res, int field_num)
1961 if (!check_field_number(res, field_num))
1964 return res->attDescs[field_num].typid;
1970 PQfsize(const PGresult *res, int field_num)
1972 if (!check_field_number(res, field_num))
1975 return res->attDescs[field_num].typlen;
1981 PQfmod(const PGresult *res, int field_num)
1983 if (!check_field_number(res, field_num))
1986 return res->attDescs[field_num].atttypmod;
1992 PQcmdStatus(PGresult *res)
1996 return res->cmdStatus;
2001 * if the last command was an INSERT, return the oid string
2005 PQoidStatus(const PGresult *res)
2008 * This must be enough to hold the result. Don't laugh, this is better
2009 * than what this function used to do.
2011 static char buf[24];
2015 if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2018 len = strspn(res->cmdStatus + 7, "0123456789");
2021 strncpy(buf, res->cmdStatus + 7, len);
2029 * a perhaps preferable form of the above which just returns
2033 PQoidValue(const PGresult *res)
2035 char *endptr = NULL;
2036 unsigned long result;
2038 if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2046 result = strtoul(res->cmdStatus + 7, &endptr, 10);
2048 if (!endptr || (*endptr != ' ' && *endptr != '\0') || errno == ERANGE)
2051 return (Oid) result;
2057 * If the last command was an INSERT/UPDATE/DELETE/MOVE/FETCH, return a
2058 * string containing the number of inserted/affected tuples. If not,
2061 * XXX: this should probably return an int
2064 PQcmdTuples(PGresult *res)
2071 if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
2073 p = res->cmdStatus + 6;
2075 /* INSERT: skip oid */
2076 while (*p != ' ' && *p)
2079 else if (strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
2080 strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
2081 p = res->cmdStatus + 6;
2082 else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
2083 p = res->cmdStatus + 5;
2084 else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0)
2085 p = res->cmdStatus + 4;
2093 pqInternalNotice(&res->noticeHooks,
2094 "could not interpret result from server: %s",
2104 * return the value of field 'field_num' of row 'tup_num'
2107 PQgetvalue(const PGresult *res, int tup_num, int field_num)
2109 if (!check_tuple_field_number(res, tup_num, field_num))
2111 return res->tuples[tup_num][field_num].value;
2115 * returns the actual length of a field value in bytes.
2118 PQgetlength(const PGresult *res, int tup_num, int field_num)
2120 if (!check_tuple_field_number(res, tup_num, field_num))
2122 if (res->tuples[tup_num][field_num].len != NULL_LEN)
2123 return res->tuples[tup_num][field_num].len;
2129 * returns the null status of a field value.
2132 PQgetisnull(const PGresult *res, int tup_num, int field_num)
2134 if (!check_tuple_field_number(res, tup_num, field_num))
2135 return 1; /* pretend it is null */
2136 if (res->tuples[tup_num][field_num].len == NULL_LEN)
2142 /* PQsetnonblocking:
2143 * sets the PGconn's database connection non-blocking if the arg is TRUE
2144 * or makes it non-blocking if the arg is FALSE, this will not protect
2145 * you from PQexec(), you'll only be safe when using the non-blocking API.
2146 * Needs to be called only on a connected database connection.
2149 PQsetnonblocking(PGconn *conn, int arg)
2153 if (!conn || conn->status == CONNECTION_BAD)
2156 barg = (arg ? TRUE : FALSE);
2158 /* early out if the socket is already in the state requested */
2159 if (barg == conn->nonblocking)
2163 * to guarantee constancy for flushing/query/result-polling behavior
2164 * we need to flush the send queue at this point in order to guarantee
2165 * proper behavior. this is ok because either they are making a
2166 * transition _from_ or _to_ blocking mode, either way we can block
2169 /* if we are going from blocking to non-blocking flush here */
2173 conn->nonblocking = barg;
2179 * return the blocking status of the database connection
2180 * TRUE == nonblocking, FALSE == blocking
2183 PQisnonblocking(const PGconn *conn)
2185 return (pqIsnonblocking(conn));
2188 /* try to force data out, really only useful for non-blocking users */
2190 PQflush(PGconn *conn)
2192 return (pqFlush(conn));
2197 * PQfreemem - safely frees memory allocated
2199 * Needed mostly by Win32, unless multithreaded DLL (/MD in VC6)
2200 * Used for freeing memory from PQescapeByte()a/PQunescapeBytea()
2203 PQfreemem(void *ptr)
2209 * PQfreeNotify - free's the memory associated with a PGnotify
2211 * This function is here only for binary backward compatibility.
2212 * New code should use PQfreemem(). A macro will automatically map
2213 * calls to PQfreemem. It should be removed in the future. bjm 2003-03-24
2217 void PQfreeNotify(PGnotify *notify);
2220 PQfreeNotify(PGnotify *notify)
2227 * Escaping arbitrary strings to get valid SQL literal strings.
2229 * Replaces "\\" with "\\\\" and "'" with "''".
2231 * length is the length of the source string. (Note: if a terminating NUL
2232 * is encountered sooner, PQescapeString stops short of "length"; the behavior
2233 * is thus rather like strncpy.)
2235 * For safety the buffer at "to" must be at least 2*length + 1 bytes long.
2236 * A terminating NUL character is added to the output string, whether the
2237 * input is NUL-terminated or not.
2239 * Returns the actual length of the output (not counting the terminating NUL).
2242 PQescapeString(char *to, const char *from, size_t length)
2244 const char *source = from;
2246 size_t remaining = length;
2248 while (remaining > 0 && *source != '\0')
2263 *target++ = *source;
2270 /* Write the terminating NUL character. */
2277 * PQescapeBytea - converts from binary string to the
2278 * minimal encoding necessary to include the string in an SQL
2279 * INSERT statement with a bytea type column as the target.
2281 * The following transformations are applied
2282 * '\0' == ASCII 0 == \\000
2283 * '\'' == ASCII 39 == \'
2284 * '\\' == ASCII 92 == \\\\
2285 * anything < 0x20, or > 0x7e ---> \\ooo
2286 * (where ooo is an octal expression)
2289 PQescapeBytea(const unsigned char *bintext, size_t binlen, size_t *bytealen)
2291 const unsigned char *vp;
2293 unsigned char *result;
2298 * empty string has 1 char ('\0')
2303 for (i = binlen; i > 0; i--, vp++)
2305 if (*vp < 0x20 || *vp > 0x7e)
2306 len += 5; /* '5' is for '\\ooo' */
2307 else if (*vp == '\'')
2309 else if (*vp == '\\')
2315 rp = result = (unsigned char *) malloc(len);
2322 for (i = binlen; i > 0; i--, vp++)
2324 if (*vp < 0x20 || *vp > 0x7e)
2326 (void) sprintf(rp, "\\\\%03o", *vp);
2329 else if (*vp == '\'')
2335 else if (*vp == '\\')
2351 #define ISFIRSTOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '3')
2352 #define ISOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '7')
2353 #define OCTVAL(CH) ((CH) - '0')
2356 * PQunescapeBytea - converts the null terminated string representation
2357 * of a bytea, strtext, into binary, filling a buffer. It returns a
2358 * pointer to the buffer (or NULL on error), and the size of the
2359 * buffer in retbuflen. The pointer may subsequently be used as an
2360 * argument to the function free(3). It is the reverse of PQescapeBytea.
2362 * The following transformations are made:
2363 * \\ == ASCII 92 == \
2364 * \ooo == a byte whose value = ooo (ooo is an octal number)
2365 * \x == x (x is any character not matched by the above transformations)
2368 PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
2372 unsigned char *buffer,
2377 if (strtext == NULL)
2380 strtextlen = strlen(strtext);
2383 * Length of input is max length of output, but add one to avoid
2384 * unportable malloc(0) if input is zero-length.
2386 buffer = (unsigned char *) malloc(strtextlen + 1);
2390 for (i = j = 0; i < strtextlen;)
2396 if (strtext[i] == '\\')
2397 buffer[j++] = strtext[i++];
2400 if ((ISFIRSTOCTDIGIT(strtext[i])) &&
2401 (ISOCTDIGIT(strtext[i + 1])) &&
2402 (ISOCTDIGIT(strtext[i + 2])))
2406 byte = OCTVAL(strtext[i++]);
2407 byte = (byte << 3) + OCTVAL(strtext[i++]);
2408 byte = (byte << 3) + OCTVAL(strtext[i++]);
2414 * Note: if we see '\' followed by something that isn't a
2415 * recognized escape sequence, we loop around having done
2416 * nothing except advance i. Therefore the something will
2417 * be emitted as ordinary data on the next cycle. Corner
2418 * case: '\' at end of string will just be discarded.
2423 buffer[j++] = strtext[i++];
2427 buflen = j; /* buflen is the length of the dequoted
2430 /* Shrink the buffer to be no larger than necessary */
2431 /* +1 avoids unportable behavior when buflen==0 */
2432 tmpbuf = realloc(buffer, buflen + 1);
2434 /* It would only be a very brain-dead realloc that could fail, but... */
2441 *retbuflen = buflen;