1 /*-------------------------------------------------------------------------
4 * functions related to sending a query down to the backend
6 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/interfaces/libpq/fe-exec.c,v 1.92 2000/03/11 03:08:36 tgl Exp $
13 *-------------------------------------------------------------------------
21 #include "libpq-int.h"
29 /* keep this in same order as ExecStatusType in libpq-fe.h */
30 char * const pgresStatus[] = {
37 "PGRES_NONFATAL_ERROR",
42 /* Note: DONOTICE macro will work if applied to either PGconn or PGresult */
43 #define DONOTICE(conn,message) \
44 ((*(conn)->noticeHook) ((conn)->noticeArg, (message)))
47 static void pqCatenateResultError(PGresult *res, const char *msg);
48 static void saveErrorResult(PGconn *conn);
49 static PGresult *prepareAsyncResult(PGconn *conn);
50 static int addTuple(PGresult *res, PGresAttValue *tup);
51 static void parseInput(PGconn *conn);
52 static void handleSendFailure(PGconn *conn);
53 static int getRowDescriptions(PGconn *conn);
54 static int getAnotherTuple(PGconn *conn, int binary);
55 static int getNotify(PGconn *conn);
56 static int getNotice(PGconn *conn);
60 * Space management for PGresult.
62 * Formerly, libpq did a separate malloc() for each field of each tuple
63 * returned by a query. This was remarkably expensive --- malloc/free
64 * consumed a sizable part of the application's runtime. And there is
65 * no real need to keep track of the fields separately, since they will
66 * all be freed together when the PGresult is released. So now, we grab
67 * large blocks of storage from malloc and allocate space for query data
68 * within these blocks, using a trivially simple allocator. This reduces
69 * the number of malloc/free calls dramatically, and it also avoids
70 * fragmentation of the malloc storage arena.
71 * The PGresult structure itself is still malloc'd separately. We could
72 * combine it with the first allocation block, but that would waste space
73 * for the common case that no extra storage is actually needed (that is,
74 * the SQL command did not return tuples).
75 * We also malloc the top-level array of tuple pointers separately, because
76 * we need to be able to enlarge it via realloc, and our trivial space
77 * allocator doesn't handle that effectively. (Too bad the FE/BE protocol
78 * doesn't tell us up front how many tuples will be returned.)
79 * All other subsidiary storage for a PGresult is kept in PGresult_data blocks
80 * of size PGRESULT_DATA_BLOCKSIZE. The overhead at the start of each block
81 * is just a link to the next one, if any. Free-space management info is
82 * kept in the owning PGresult.
83 * A query returning a small amount of data will thus require three malloc
84 * calls: one for the PGresult, one for the tuples pointer array, and one
85 * PGresult_data block.
86 * Only the most recently allocated PGresult_data block is a candidate to
87 * have more stuff added to it --- any extra space left over in older blocks
88 * is wasted. We could be smarter and search the whole chain, but the point
89 * here is to be simple and fast. Typical applications do not keep a PGresult
90 * around very long anyway, so some wasted space within one is not a problem.
92 * Tuning constants for the space allocator are:
93 * PGRESULT_DATA_BLOCKSIZE: size of a standard allocation block, in bytes
94 * PGRESULT_ALIGN_BOUNDARY: assumed alignment requirement for binary data
95 * PGRESULT_SEP_ALLOC_THRESHOLD: objects bigger than this are given separate
96 * blocks, instead of being crammed into a regular allocation block.
97 * Requirements for correct function are:
98 * PGRESULT_ALIGN_BOUNDARY must be a multiple of the alignment requirements
99 * of all machine data types. (Currently this is set from configure
100 * tests, so it should be OK automatically.)
101 * PGRESULT_SEP_ALLOC_THRESHOLD + PGRESULT_BLOCK_OVERHEAD <=
102 * PGRESULT_DATA_BLOCKSIZE
103 * pqResultAlloc assumes an object smaller than the threshold will fit
105 * The amount of space wasted at the end of a block could be as much as
106 * PGRESULT_SEP_ALLOC_THRESHOLD, so it doesn't pay to make that too large.
113 #define MAX(a,b) ((a) > (b) ? (a) : (b))
115 #define PGRESULT_DATA_BLOCKSIZE 2048
116 #define PGRESULT_ALIGN_BOUNDARY MAXIMUM_ALIGNOF /* from configure */
117 #define PGRESULT_BLOCK_OVERHEAD MAX(sizeof(PGresult_data), PGRESULT_ALIGN_BOUNDARY)
118 #define PGRESULT_SEP_ALLOC_THRESHOLD (PGRESULT_DATA_BLOCKSIZE / 2)
122 * PQmakeEmptyPGresult
123 * returns a newly allocated, initialized PGresult with given status.
124 * If conn is not NULL and status indicates an error, the conn's
125 * errorMessage is copied.
127 * Note this is exported --- you wouldn't think an application would need
128 * to build its own PGresults, but this has proven useful in both libpgtcl
129 * and the Perl5 interface, so maybe it's not so unreasonable.
133 PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
137 result = (PGresult *) malloc(sizeof(PGresult));
139 result->xconn = conn; /* might be NULL */
141 result->numAttributes = 0;
142 result->attDescs = NULL;
143 result->tuples = NULL;
144 result->tupArrSize = 0;
145 result->resultStatus = status;
146 result->cmdStatus[0] = '\0';
148 result->errMsg = NULL;
149 result->null_field[0] = '\0';
150 result->curBlock = NULL;
151 result->curOffset = 0;
152 result->spaceLeft = 0;
156 result->noticeHook = conn->noticeHook;
157 result->noticeArg = conn->noticeArg;
158 /* consider copying conn's errorMessage */
161 case PGRES_EMPTY_QUERY:
162 case PGRES_COMMAND_OK:
163 case PGRES_TUPLES_OK:
166 /* non-error cases */
169 pqSetResultError(result, conn->errorMessage.data);
175 result->noticeHook = NULL;
176 result->noticeArg = NULL;
184 * Allocate subsidiary storage for a PGresult.
186 * nBytes is the amount of space needed for the object.
187 * If isBinary is true, we assume that we need to align the object on
188 * a machine allocation boundary.
189 * If isBinary is false, we assume the object is a char string and can
190 * be allocated on any byte boundary.
193 pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
196 PGresult_data *block;
202 return res->null_field;
205 * If alignment is needed, round up the current position to an
206 * alignment boundary.
210 int offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
214 res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
215 res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
219 /* If there's enough space in the current block, no problem. */
220 if (nBytes <= res->spaceLeft)
222 space = res->curBlock->space + res->curOffset;
223 res->curOffset += nBytes;
224 res->spaceLeft -= nBytes;
229 * If the requested object is very large, give it its own block; this
230 * avoids wasting what might be most of the current block to start a
231 * new block. (We'd have to special-case requests bigger than the
232 * block size anyway.) The object is always given binary alignment in
235 if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
237 block = (PGresult_data *) malloc(nBytes + PGRESULT_BLOCK_OVERHEAD);
240 space = block->space + PGRESULT_BLOCK_OVERHEAD;
245 * Tuck special block below the active block, so that we don't
246 * have to waste the free space in the active block.
248 block->next = res->curBlock->next;
249 res->curBlock->next = block;
253 /* Must set up the new block as the first active block. */
255 res->curBlock = block;
256 res->spaceLeft = 0; /* be sure it's marked full */
261 /* Otherwise, start a new block. */
262 block = (PGresult_data *) malloc(PGRESULT_DATA_BLOCKSIZE);
265 block->next = res->curBlock;
266 res->curBlock = block;
269 /* object needs full alignment */
270 res->curOffset = PGRESULT_BLOCK_OVERHEAD;
271 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - PGRESULT_BLOCK_OVERHEAD;
275 /* we can cram it right after the overhead pointer */
276 res->curOffset = sizeof(PGresult_data);
277 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - sizeof(PGresult_data);
280 space = block->space + res->curOffset;
281 res->curOffset += nBytes;
282 res->spaceLeft -= nBytes;
288 * Like strdup, but the space is subsidiary PGresult space.
291 pqResultStrdup(PGresult *res, const char *str)
293 char *space = (char *) pqResultAlloc(res, strlen(str) + 1, FALSE);
302 * assign a new error message to a PGresult
305 pqSetResultError(PGresult *res, const char *msg)
310 res->errMsg = pqResultStrdup(res, msg);
316 * pqCatenateResultError -
317 * concatenate a new error message to the one already in a PGresult
320 pqCatenateResultError(PGresult *res, const char *msg)
322 PQExpBufferData errorBuf;
326 initPQExpBuffer(&errorBuf);
328 appendPQExpBufferStr(&errorBuf, res->errMsg);
329 appendPQExpBufferStr(&errorBuf, msg);
330 pqSetResultError(res, errorBuf.data);
331 termPQExpBuffer(&errorBuf);
336 * free's the memory associated with a PGresult
339 PQclear(PGresult *res)
341 PGresult_data *block;
346 /* Free all the subsidiary blocks */
347 while ((block = res->curBlock) != NULL)
349 res->curBlock = block->next;
353 /* Free the top-level tuple pointer array */
357 /* Free the PGresult structure itself */
362 * Handy subroutine to deallocate any partially constructed async result.
366 pqClearAsyncResult(PGconn *conn)
369 PQclear(conn->result);
371 conn->curTuple = NULL;
375 * This subroutine deletes any existing async result, sets conn->result
376 * to a PGresult with status PGRES_FATAL_ERROR, and stores the current
377 * contents of conn->errorMessage into that result. It differs from a
378 * plain call on PQmakeEmptyPGresult() in that if there is already an
379 * async result with status PGRES_FATAL_ERROR, the current error message
380 * is APPENDED to the old error message instead of replacing it. This
381 * behavior lets us report multiple error conditions properly, if necessary.
382 * (An example where this is needed is when the backend sends an 'E' message
383 * and immediately closes the connection --- we want to report both the
384 * backend error and the connection closure error.)
387 saveErrorResult(PGconn *conn)
389 /* If no old async result, just let PQmakeEmptyPGresult make one.
390 * Likewise if old result is not an error message.
392 if (conn->result == NULL ||
393 conn->result->resultStatus != PGRES_FATAL_ERROR ||
394 conn->result->errMsg == NULL)
396 pqClearAsyncResult(conn);
397 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
401 /* Else, concatenate error message to existing async result. */
402 pqCatenateResultError(conn->result, conn->errorMessage.data);
407 * This subroutine prepares an async result object for return to the caller.
408 * If there is not already an async result object, build an error object
409 * using whatever is in conn->errorMessage. In any case, clear the async
410 * result storage and make sure PQerrorMessage will agree with the result's
414 prepareAsyncResult(PGconn *conn)
419 * conn->result is the PGresult to return. If it is NULL
420 * (which probably shouldn't happen) we assume there is an
421 * appropriate error message in conn->errorMessage.
424 conn->result = NULL; /* handing over ownership to caller */
425 conn->curTuple = NULL; /* just in case */
427 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
431 * Make sure PQerrorMessage agrees with result; it could
432 * be different if we have concatenated messages.
434 resetPQExpBuffer(&conn->errorMessage);
435 appendPQExpBufferStr(&conn->errorMessage,
436 PQresultErrorMessage(res));
443 * add a row pointer to the PGresult structure, growing it if necessary
444 * Returns TRUE if OK, FALSE if not enough memory to add the row
447 addTuple(PGresult *res, PGresAttValue *tup)
449 if (res->ntups >= res->tupArrSize)
453 * Try to grow the array.
455 * We can use realloc because shallow copying of the structure is
456 * okay. Note that the first time through, res->tuples is NULL.
457 * While ANSI says that realloc() should act like malloc() in that
458 * case, some old C libraries (like SunOS 4.1.x) coredump instead.
459 * On failure realloc is supposed to return NULL without damaging
460 * the existing allocation. Note that the positions beyond
461 * res->ntups are garbage, not necessarily NULL.
463 int newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
464 PGresAttValue **newTuples;
466 if (res->tuples == NULL)
467 newTuples = (PGresAttValue **)
468 malloc(newSize * sizeof(PGresAttValue *));
470 newTuples = (PGresAttValue **)
471 realloc(res->tuples, newSize * sizeof(PGresAttValue *));
473 return FALSE; /* malloc or realloc failed */
474 res->tupArrSize = newSize;
475 res->tuples = newTuples;
477 res->tuples[res->ntups] = tup;
485 * Submit a query, but don't wait for it to finish
487 * Returns: 1 if successfully submitted
488 * 0 if error (conn->errorMessage is set)
492 PQsendQuery(PGconn *conn, const char *query)
497 /* clear the error string */
498 resetPQExpBuffer(&conn->errorMessage);
502 printfPQExpBuffer(&conn->errorMessage,
503 "PQsendQuery() -- query pointer is null.\n");
507 /* Don't try to send if we know there's no live connection. */
508 if (conn->status != CONNECTION_OK)
510 printfPQExpBuffer(&conn->errorMessage,
511 "PQsendQuery() -- There is no connection "
512 "to the backend.\n");
515 /* Can't send while already busy, either. */
516 if (conn->asyncStatus != PGASYNC_IDLE)
518 printfPQExpBuffer(&conn->errorMessage,
519 "PQsendQuery() -- another query already in progress.\n");
523 /* initialize async result-accumulation state */
525 conn->curTuple = NULL;
527 /* send the query to the backend; */
530 * in order to guarantee that we don't send a partial query
531 * where we would become out of sync with the backend and/or
532 * block during a non-blocking connection we must first flush
533 * the send buffer before sending more data
535 * an alternative is to implement 'queue reservations' where
536 * we are able to roll up a transaction
537 * (the 'Q' along with our query) and make sure we have
538 * enough space for it all in the send buffer.
540 if (pqIsnonblocking(conn))
543 * the buffer must have emptied completely before we allow
544 * a new query to be buffered
549 /* XXX: if we fail here we really ought to not block */
550 if (pqPutnchar("Q", 1, conn) ||
553 handleSendFailure(conn);
557 * give the data a push, ignore the return value as
558 * ConsumeInput() will do any aditional flushing if needed
560 (void) pqFlush(conn);
565 * the frontend-backend protocol uses 'Q' to
568 if (pqPutnchar("Q", 1, conn) ||
569 pqPuts(query, conn) ||
572 handleSendFailure(conn);
577 /* OK, it's launched! */
578 conn->asyncStatus = PGASYNC_BUSY;
583 * handleSendFailure: try to clean up after failure to send command.
585 * Primarily, what we want to accomplish here is to process an async
586 * NOTICE message that the backend might have sent just before it died.
588 * NOTE: this routine should only be called in PGASYNC_IDLE state.
592 handleSendFailure(PGconn *conn)
595 * Accept any available input data, ignoring errors. Note that if
596 * pqReadData decides the backend has closed the channel, it will
597 * close our side of the socket --- that's just what we want here.
599 while (pqReadData(conn) > 0)
600 /* loop until no more data readable */ ;
603 * Parse any available input messages. Since we are in PGASYNC_IDLE
604 * state, only NOTICE and NOTIFY messages will be eaten.
610 * Consume any available input from the backend
611 * 0 return: some kind of trouble
612 * 1 return: no problem
616 PQconsumeInput(PGconn *conn)
622 * Load more data, if available. We do this no matter what state we
623 * are in, since we are probably getting called because the
624 * application wants to get rid of a read-select condition. Note that
625 * we will NOT block waiting for more input.
627 if (pqReadData(conn) < 0)
630 * for non-blocking connections
631 * try to flush the send-queue otherwise we may never get a
632 * responce for something that may not have already been sent
633 * because it's in our write buffer!
635 if (pqIsnonblocking(conn))
636 (void) pqFlush(conn);
639 /* Parsing of the data waits till later. */
645 * parseInput: if appropriate, parse input data from backend
646 * until input is exhausted or a stopping state is reached.
647 * Note that this function will NOT attempt to read more data from the backend.
651 parseInput(PGconn *conn)
654 char noticeWorkspace[128];
657 * Loop to parse successive complete messages available in the buffer.
663 * Quit if in COPY_OUT state: we expect raw data from the server
664 * until PQendcopy is called. Don't try to parse it according to
665 * the normal protocol. (This is bogus. The data lines ought to
666 * be part of the protocol and have identifying leading
669 if (conn->asyncStatus == PGASYNC_COPY_OUT)
673 * OK to try to read a message type code.
675 conn->inCursor = conn->inStart;
676 if (pqGetc(&id, conn))
680 * NOTIFY and NOTICE messages can happen in any state besides COPY
681 * OUT; always process them right away.
683 * Most other messages should only be processed while in BUSY state.
684 * (In particular, in READY state we hold off further parsing until
685 * the application collects the current PGresult.)
687 * However, if the state is IDLE then we got trouble; we need to
688 * deal with the unexpected message somehow.
700 else if (conn->asyncStatus != PGASYNC_BUSY)
702 /* If not IDLE state, just wait ... */
703 if (conn->asyncStatus != PGASYNC_IDLE)
706 * Unexpected message in IDLE state; need to recover somehow.
707 * ERROR messages are displayed using the notice processor;
708 * anything else is just dropped on the floor after displaying
709 * a suitable warning notice. (An ERROR is very possibly the
710 * backend telling us why it is about to close the connection,
711 * so we don't want to just discard it...)
720 sprintf(noticeWorkspace,
721 "Backend message type 0x%02x arrived while idle\n",
723 DONOTICE(conn, noticeWorkspace);
724 /* Discard the unexpected message; good idea?? */
725 conn->inStart = conn->inEnd;
732 * In BUSY state, we can process everything.
736 case 'C': /* command complete */
737 if (pqGets(&conn->workBuffer, conn))
739 if (conn->result == NULL)
740 conn->result = PQmakeEmptyPGresult(conn,
742 strncpy(conn->result->cmdStatus, conn->workBuffer.data,
744 conn->asyncStatus = PGASYNC_READY;
746 case 'E': /* error return */
747 if (pqGets(& conn->errorMessage, conn))
749 /* build an error result holding the error message */
750 saveErrorResult(conn);
751 conn->asyncStatus = PGASYNC_READY;
753 case 'Z': /* backend is ready for new query */
754 conn->asyncStatus = PGASYNC_IDLE;
756 case 'I': /* empty query */
757 /* read and throw away the closing '\0' */
758 if (pqGetc(&id, conn))
762 sprintf(noticeWorkspace,
763 "unexpected character %c following 'I'\n",
765 DONOTICE(conn, noticeWorkspace);
767 if (conn->result == NULL)
768 conn->result = PQmakeEmptyPGresult(conn,
770 conn->asyncStatus = PGASYNC_READY;
772 case 'K': /* secret key data from the backend */
775 * This is expected only during backend startup, but
776 * it's just as easy to handle it as part of the main
777 * loop. Save the data and continue processing.
779 if (pqGetInt(&(conn->be_pid), 4, conn))
781 if (pqGetInt(&(conn->be_key), 4, conn))
784 case 'P': /* synchronous (normal) portal */
785 if (pqGets(&conn->workBuffer, conn))
787 /* We pretty much ignore this message type... */
789 case 'T': /* row descriptions (start of query
791 if (conn->result == NULL)
793 /* First 'T' in a query sequence */
794 if (getRowDescriptions(conn))
801 * A new 'T' message is treated as the start of
802 * another PGresult. (It is not clear that this
803 * is really possible with the current backend.)
804 * We stop parsing until the application accepts
805 * the current result.
807 conn->asyncStatus = PGASYNC_READY;
811 case 'D': /* ASCII data tuple */
812 if (conn->result != NULL)
814 /* Read another tuple of a normal query response */
815 if (getAnotherTuple(conn, FALSE))
820 sprintf(noticeWorkspace,
821 "Backend sent D message without prior T\n");
822 DONOTICE(conn, noticeWorkspace);
823 /* Discard the unexpected message; good idea?? */
824 conn->inStart = conn->inEnd;
828 case 'B': /* Binary data tuple */
829 if (conn->result != NULL)
831 /* Read another tuple of a normal query response */
832 if (getAnotherTuple(conn, TRUE))
837 sprintf(noticeWorkspace,
838 "Backend sent B message without prior T\n");
839 DONOTICE(conn, noticeWorkspace);
840 /* Discard the unexpected message; good idea?? */
841 conn->inStart = conn->inEnd;
845 case 'G': /* Start Copy In */
846 conn->asyncStatus = PGASYNC_COPY_IN;
848 case 'H': /* Start Copy Out */
849 conn->asyncStatus = PGASYNC_COPY_OUT;
852 printfPQExpBuffer(&conn->errorMessage,
853 "Unknown protocol character '%c' read from backend. "
854 "(The protocol character is the first character the "
855 "backend sends in response to a query it receives).\n",
857 /* build an error result holding the error message */
858 saveErrorResult(conn);
859 /* Discard the unexpected message; good idea?? */
860 conn->inStart = conn->inEnd;
861 conn->asyncStatus = PGASYNC_READY;
863 } /* switch on protocol character */
865 /* Successfully consumed this message */
866 conn->inStart = conn->inCursor;
872 * parseInput subroutine to read a 'T' (row descriptions) message.
873 * We build a PGresult structure containing the attribute data.
874 * Returns: 0 if completed message, EOF if not enough data yet.
876 * Note that if we run out of data, we have to release the partially
877 * constructed PGresult, and rebuild it again next time. Fortunately,
878 * that shouldn't happen often, since 'T' messages usually fit in a packet.
882 getRowDescriptions(PGconn *conn)
888 result = PQmakeEmptyPGresult(conn, PGRES_TUPLES_OK);
890 /* parseInput already read the 'T' label. */
891 /* the next two bytes are the number of fields */
892 if (pqGetInt(&(result->numAttributes), 2, conn))
897 nfields = result->numAttributes;
899 /* allocate space for the attribute descriptors */
902 result->attDescs = (PGresAttDesc *)
903 pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
904 MemSet((char *) result->attDescs, 0, nfields * sizeof(PGresAttDesc));
908 for (i = 0; i < nfields; i++)
914 if (pqGets(&conn->workBuffer, conn) ||
915 pqGetInt(&typid, 4, conn) ||
916 pqGetInt(&typlen, 2, conn) ||
917 pqGetInt(&atttypmod, 4, conn))
924 * Since pqGetInt treats 2-byte integers as unsigned, we need to
925 * coerce the special value "-1" to signed form. (-1 is sent for
926 * variable-length fields.) Formerly, libpq effectively did a
927 * sign-extension on the 2-byte value by storing it in a signed
928 * short. Now we only coerce the single value 65535 == -1; values
929 * 32768..65534 are taken as valid field lengths.
931 if (typlen == 0xFFFF)
933 result->attDescs[i].name = pqResultStrdup(result,
934 conn->workBuffer.data);
935 result->attDescs[i].typid = typid;
936 result->attDescs[i].typlen = typlen;
937 result->attDescs[i].atttypmod = atttypmod;
941 conn->result = result;
946 * parseInput subroutine to read a 'B' or 'D' (row data) message.
947 * We add another tuple to the existing PGresult structure.
948 * Returns: 0 if completed message, EOF if error or not enough data yet.
950 * Note that if we run out of data, we have to suspend and reprocess
951 * the message after more data is received. We keep a partially constructed
952 * tuple in conn->curTuple, and avoid reallocating already-allocated storage.
956 getAnotherTuple(PGconn *conn, int binary)
958 PGresult *result = conn->result;
959 int nfields = result->numAttributes;
961 /* the backend sends us a bitmap of which attributes are null */
962 char std_bitmap[64]; /* used unless it doesn't fit */
963 char *bitmap = std_bitmap;
965 size_t nbytes; /* the number of bytes in bitmap */
966 char bmap; /* One byte of the bitmap */
967 int bitmap_index; /* Its index */
968 int bitcnt; /* number of bits examined in current byte */
969 int vlen; /* length of the current field value */
971 result->binary = binary;
973 /* Allocate tuple space if first time for this data message */
974 if (conn->curTuple == NULL)
976 conn->curTuple = (PGresAttValue *)
977 pqResultAlloc(result, nfields * sizeof(PGresAttValue), TRUE);
978 if (conn->curTuple == NULL)
980 MemSet((char *) conn->curTuple, 0, nfields * sizeof(PGresAttValue));
982 tup = conn->curTuple;
984 /* Get the null-value bitmap */
985 nbytes = (nfields + BYTELEN - 1) / BYTELEN;
986 /* malloc() only for unusually large field counts... */
987 if (nbytes > sizeof(std_bitmap))
988 bitmap = (char *) malloc(nbytes);
990 if (pqGetnchar(bitmap, nbytes, conn))
993 /* Scan the fields */
995 bmap = bitmap[bitmap_index];
998 for (i = 0; i < nfields; i++)
1002 /* if the field value is absent, make it a null string */
1003 tup[i].value = result->null_field;
1004 tup[i].len = NULL_LEN;
1008 /* get the value length (the first four bytes are for length) */
1009 if (pqGetInt(&vlen, 4, conn))
1015 if (tup[i].value == NULL)
1017 tup[i].value = (char *) pqResultAlloc(result, vlen + 1, binary);
1018 if (tup[i].value == NULL)
1022 /* read in the value */
1024 if (pqGetnchar((char *) (tup[i].value), vlen, conn))
1026 /* we have to terminate this ourselves */
1027 tup[i].value[vlen] = '\0';
1029 /* advance the bitmap stuff */
1031 if (bitcnt == BYTELEN)
1034 bmap = bitmap[bitmap_index];
1041 /* Success! Store the completed tuple in the result */
1042 if (!addTuple(result, tup))
1044 /* and reset for a new message */
1045 conn->curTuple = NULL;
1047 if (bitmap != std_bitmap)
1052 /* Replace partially constructed result with an error result */
1053 /* we do NOT use saveErrorResult() here, because of the likelihood
1054 * that there's not enough memory to concatenate messages...
1056 pqClearAsyncResult(conn);
1057 printfPQExpBuffer(&conn->errorMessage,
1058 "getAnotherTuple() -- out of memory for result\n");
1059 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1060 conn->asyncStatus = PGASYNC_READY;
1061 /* Discard the failed message --- good idea? */
1062 conn->inStart = conn->inEnd;
1065 if (bitmap != std_bitmap)
1073 * Return TRUE if PQgetResult would block waiting for input.
1077 PQisBusy(PGconn *conn)
1082 /* Parse any available data, if our state permits. */
1085 /* PQgetResult will return immediately in all states except BUSY. */
1086 return conn->asyncStatus == PGASYNC_BUSY;
1092 * Get the next PGresult produced by a query.
1093 * Returns NULL if and only if no query work remains.
1097 PQgetResult(PGconn *conn)
1104 /* Parse any available data, if our state permits. */
1107 /* If not ready to return something, block until we are. */
1108 while (conn->asyncStatus == PGASYNC_BUSY)
1110 /* Wait for some more data, and load it. */
1111 if (pqWait(TRUE, FALSE, conn) ||
1112 pqReadData(conn) < 0)
1114 /* conn->errorMessage has been set by pqWait or pqReadData.
1115 * We want to append it to any already-received error message.
1117 saveErrorResult(conn);
1118 conn->asyncStatus = PGASYNC_IDLE;
1119 return prepareAsyncResult(conn);
1125 /* Return the appropriate thing. */
1126 switch (conn->asyncStatus)
1129 res = NULL; /* query is complete */
1132 res = prepareAsyncResult(conn);
1133 /* Set the state back to BUSY, allowing parsing to proceed. */
1134 conn->asyncStatus = PGASYNC_BUSY;
1136 case PGASYNC_COPY_IN:
1137 res = PQmakeEmptyPGresult(conn, PGRES_COPY_IN);
1139 case PGASYNC_COPY_OUT:
1140 res = PQmakeEmptyPGresult(conn, PGRES_COPY_OUT);
1143 printfPQExpBuffer(&conn->errorMessage,
1144 "PQgetResult: Unexpected asyncStatus %d\n",
1145 (int) conn->asyncStatus);
1146 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1156 * send a query to the backend and package up the result in a PGresult
1158 * If the query was not even sent, return NULL; conn->errorMessage is set to
1159 * a relevant message.
1160 * If the query was sent, a new PGresult is returned (which could indicate
1161 * either success or failure).
1162 * The user is responsible for freeing the PGresult via PQclear()
1163 * when done with it.
1167 PQexec(PGconn *conn, const char *query)
1170 PGresult *lastResult;
1174 * we assume anyone calling PQexec wants blocking behaviour,
1175 * we force the blocking status of the connection to blocking
1176 * for the duration of this function and restore it on return
1178 savedblocking = pqIsnonblocking(conn);
1179 if (PQsetnonblocking(conn, FALSE) == -1)
1183 * Silently discard any prior query result that application didn't
1184 * eat. This is probably poor design, but it's here for backward
1187 while ((result = PQgetResult(conn)) != NULL)
1189 if (result->resultStatus == PGRES_COPY_IN ||
1190 result->resultStatus == PGRES_COPY_OUT)
1193 printfPQExpBuffer(&conn->errorMessage,
1194 "PQexec: you gotta get out of a COPY state yourself.\n");
1195 /* restore blocking status */
1201 /* OK to send the message */
1202 if (!PQsendQuery(conn, query))
1203 goto errout; /* restore blocking status */
1206 * For backwards compatibility, return the last result if there are
1207 * more than one --- but merge error messages if we get more than one
1210 * We have to stop if we see copy in/out, however.
1211 * We will resume parsing when application calls PQendcopy.
1214 while ((result = PQgetResult(conn)) != NULL)
1218 if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
1219 result->resultStatus == PGRES_FATAL_ERROR)
1221 pqCatenateResultError(lastResult, result->errMsg);
1223 result = lastResult;
1224 /* Make sure PQerrorMessage agrees with catenated result */
1225 resetPQExpBuffer(&conn->errorMessage);
1226 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
1229 PQclear(lastResult);
1231 lastResult = result;
1232 if (result->resultStatus == PGRES_COPY_IN ||
1233 result->resultStatus == PGRES_COPY_OUT)
1237 if (PQsetnonblocking(conn, savedblocking) == -1)
1242 if (PQsetnonblocking(conn, savedblocking) == -1)
1249 * Attempt to read a Notice response message.
1250 * This is possible in several places, so we break it out as a subroutine.
1251 * Entry: 'N' flag character has already been consumed.
1252 * Exit: returns 0 if successfully consumed Notice message.
1253 * returns EOF if not enough data.
1256 getNotice(PGconn *conn)
1258 /* Since the Notice might be pretty long, we create a temporary
1259 * PQExpBuffer rather than using conn->workBuffer. workBuffer is
1260 * intended for stuff that is expected to be short.
1262 PQExpBufferData noticeBuf;
1264 initPQExpBuffer(¬iceBuf);
1265 if (pqGets(¬iceBuf, conn))
1267 termPQExpBuffer(¬iceBuf);
1270 DONOTICE(conn, noticeBuf.data);
1271 termPQExpBuffer(¬iceBuf);
1276 * Attempt to read a Notify response message.
1277 * This is possible in several places, so we break it out as a subroutine.
1278 * Entry: 'A' flag character has already been consumed.
1279 * Exit: returns 0 if successfully consumed Notify message.
1280 * returns EOF if not enough data.
1283 getNotify(PGconn *conn)
1286 PGnotify *newNotify;
1288 if (pqGetInt(&be_pid, 4, conn))
1290 if (pqGets(&conn->workBuffer, conn))
1292 newNotify = (PGnotify *) malloc(sizeof(PGnotify));
1293 strncpy(newNotify->relname, conn->workBuffer.data, NAMEDATALEN);
1294 newNotify->be_pid = be_pid;
1295 DLAddTail(conn->notifyList, DLNewElem(newNotify));
1301 * returns a PGnotify* structure of the latest async notification
1302 * that has not yet been handled
1304 * returns NULL, if there is currently
1305 * no unhandled async notification from the backend
1307 * the CALLER is responsible for FREE'ing the structure returned
1311 PQnotifies(PGconn *conn)
1319 /* Parse any available data to see if we can extract NOTIFY messages. */
1322 /* RemHead returns NULL if list is empty */
1323 e = DLRemHead(conn->notifyList);
1326 event = (PGnotify *) DLE_VAL(e);
1332 * PQgetline - gets a newline-terminated string from the backend.
1334 * Chiefly here so that applications can use "COPY <rel> to stdout"
1335 * and read the output string. Returns a null-terminated string in s.
1337 * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
1338 * the terminating \n (like gets(3)).
1340 * CAUTION: the caller is responsible for detecting the end-of-copy signal
1341 * (a line containing just "\.") when using this routine.
1344 * EOF if it is detected or invalid arguments are given
1345 * 0 if EOL is reached (i.e., \n has been read)
1346 * (this is required for backward-compatibility -- this
1347 * routine used to always return EOF or 0, assuming that
1348 * the line ended within maxlen bytes.)
1349 * 1 in other cases (i.e., the buffer was filled before \n is reached)
1352 PQgetline(PGconn *conn, char *s, int maxlen)
1354 int result = 1; /* return value if buffer overflows */
1356 if (!s || maxlen <= 0)
1359 if (!conn || conn->sock < 0)
1366 * Since this is a purely synchronous routine, we don't bother to
1367 * maintain conn->inCursor; there is no need to back up.
1371 if (conn->inStart < conn->inEnd)
1373 char c = conn->inBuffer[conn->inStart++];
1377 result = 0; /* success exit */
1385 /* need to load more data */
1386 if (pqWait(TRUE, FALSE, conn) ||
1387 pqReadData(conn) < 0)
1400 * PQgetlineAsync - gets a newline-terminated string without blocking.
1402 * This routine is for applications that want to do "COPY <rel> to stdout"
1403 * asynchronously, that is without blocking. Having issued the COPY command
1404 * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
1405 * and this routine until the end-of-data signal is detected. Unlike
1406 * PQgetline, this routine takes responsibility for detecting end-of-data.
1408 * On each call, PQgetlineAsync will return data if a complete newline-
1409 * terminated data line is available in libpq's input buffer, or if the
1410 * incoming data line is too long to fit in the buffer offered by the caller.
1411 * Otherwise, no data is returned until the rest of the line arrives.
1413 * If -1 is returned, the end-of-data signal has been recognized (and removed
1414 * from libpq's input buffer). The caller *must* next call PQendcopy and
1415 * then return to normal processing.
1418 * -1 if the end-of-copy-data marker has been recognized
1419 * 0 if no data is available
1420 * >0 the number of bytes returned.
1421 * The data returned will not extend beyond a newline character. If possible
1422 * a whole line will be returned at one time. But if the buffer offered by
1423 * the caller is too small to hold a line sent by the backend, then a partial
1424 * data line will be returned. This can be detected by testing whether the
1425 * last returned byte is '\n' or not.
1426 * The returned string is *not* null-terminated.
1430 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
1434 if (!conn || conn->asyncStatus != PGASYNC_COPY_OUT)
1435 return -1; /* we are not doing a copy... */
1438 * Move data from libpq's buffer to the caller's. We want to accept
1439 * data only in units of whole lines, not partial lines. This ensures
1440 * that we can recognize the terminator line "\\.\n". (Otherwise, if
1441 * it happened to cross a packet/buffer boundary, we might hand the
1442 * first one or two characters off to the caller, which we shouldn't.)
1445 conn->inCursor = conn->inStart;
1448 while (avail > 0 && conn->inCursor < conn->inEnd)
1450 char c = conn->inBuffer[conn->inCursor++];
1456 /* Got a complete line; mark the data removed from libpq */
1457 conn->inStart = conn->inCursor;
1458 /* Is it the endmarker line? */
1459 if (bufsize - avail == 3 && buffer[-3] == '\\' && buffer[-2] == '.')
1461 /* No, return the data line to the caller */
1462 return bufsize - avail;
1467 * We don't have a complete line. We'd prefer to leave it in libpq's
1468 * buffer until the rest arrives, but there is a special case: what if
1469 * the line is longer than the buffer the caller is offering us? In
1470 * that case we'd better hand over a partial line, else we'd get into
1471 * an infinite loop. Do this in a way that ensures we can't
1472 * misrecognize a terminator line later: leave last 3 characters in
1475 if (avail == 0 && bufsize > 3)
1477 conn->inStart = conn->inCursor - 3;
1484 * PQputline -- sends a string to the backend.
1485 * Returns 0 if OK, EOF if not.
1487 * Chiefly here so that applications can use "COPY <rel> from stdin".
1490 PQputline(PGconn *conn, const char *s)
1492 if (!conn || conn->sock < 0)
1494 return pqPutnchar(s, strlen(s), conn);
1498 * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
1499 * Returns 0 if OK, EOF if not.
1502 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
1504 if (!conn || conn->sock < 0)
1506 return pqPutnchar(buffer, nbytes, conn);
1511 * After completing the data transfer portion of a copy in/out,
1512 * the application must call this routine to finish the command protocol.
1519 PQendcopy(PGconn *conn)
1526 if (conn->asyncStatus != PGASYNC_COPY_IN &&
1527 conn->asyncStatus != PGASYNC_COPY_OUT)
1529 printfPQExpBuffer(&conn->errorMessage,
1530 "PQendcopy() -- I don't think there's a copy in progress.\n");
1535 * make sure no data is waiting to be sent,
1536 * abort if we are non-blocking and the flush fails
1538 if (pqFlush(conn) && pqIsnonblocking(conn))
1541 /* non blocking connections may have to abort at this point. */
1542 if (pqIsnonblocking(conn) && PQisBusy(conn))
1545 /* Return to active duty */
1546 conn->asyncStatus = PGASYNC_BUSY;
1547 resetPQExpBuffer(&conn->errorMessage);
1549 /* Wait for the completion response */
1550 result = PQgetResult(conn);
1552 /* Expecting a successful result */
1553 if (result && result->resultStatus == PGRES_COMMAND_OK)
1560 * Trouble. The worst case is that we've lost sync with the backend
1561 * entirely due to application screwup of the copy in/out protocol. To
1562 * recover, reset the connection (talk about using a sledgehammer...)
1566 if (conn->errorMessage.len > 0)
1567 DONOTICE(conn, conn->errorMessage.data);
1569 DONOTICE(conn, "PQendcopy: resetting connection\n");
1578 * PQfn - Send a function call to the POSTGRES backend.
1580 * conn : backend connection
1581 * fnid : function id
1582 * result_buf : pointer to result buffer (&int if integer)
1583 * result_len : length of return value.
1584 * actual_result_len: actual length returned. (differs from result_len
1585 * for varlena structures.)
1586 * result_type : If the result is an integer, this must be 1,
1587 * otherwise this should be 0
1588 * args : pointer to an array of function arguments.
1589 * (each has length, if integer, and value/pointer)
1590 * nargs : # of arguments in args array.
1593 * PGresult with status = PGRES_COMMAND_OK if successful.
1594 * *actual_result_len is > 0 if there is a return value, 0 if not.
1595 * PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
1596 * NULL on communications failure. conn->errorMessage will be set.
1604 int *actual_result_len,
1606 const PQArgBlock *args,
1609 bool needInput = false;
1610 ExecStatusType status = PGRES_FATAL_ERROR;
1614 *actual_result_len = 0;
1619 /* clear the error string */
1620 resetPQExpBuffer(&conn->errorMessage);
1622 if (conn->sock < 0 || conn->asyncStatus != PGASYNC_IDLE ||
1623 conn->result != NULL)
1625 printfPQExpBuffer(&conn->errorMessage,
1626 "PQfn() -- connection in wrong state\n");
1630 if (pqPuts("F ", conn) || /* function */
1631 pqPutInt(fnid, 4, conn) || /* function id */
1632 pqPutInt(nargs, 4, conn)) /* # of args */
1634 handleSendFailure(conn);
1638 for (i = 0; i < nargs; ++i)
1639 { /* len.int4 + contents */
1640 if (pqPutInt(args[i].len, 4, conn))
1642 handleSendFailure(conn);
1648 if (pqPutInt(args[i].u.integer, 4, conn))
1650 handleSendFailure(conn);
1656 if (pqPutnchar((char *) args[i].u.ptr, args[i].len, conn))
1658 handleSendFailure(conn);
1665 handleSendFailure(conn);
1673 /* Wait for some data to arrive (or for the channel to close) */
1674 if (pqWait(TRUE, FALSE, conn) ||
1675 pqReadData(conn) < 0)
1680 * Scan the message. If we run out of data, loop around to try
1683 conn->inCursor = conn->inStart;
1686 if (pqGetc(&id, conn))
1690 * We should see V or E response to the command, but might get N
1691 * and/or A notices first. We also need to swallow the final Z
1696 case 'V': /* function result */
1697 if (pqGetc(&id, conn))
1701 /* function returned nonempty value */
1702 if (pqGetInt(actual_result_len, 4, conn))
1706 if (pqGetInt(result_buf, 4, conn))
1711 if (pqGetnchar((char *) result_buf,
1716 if (pqGetc(&id, conn)) /* get the last '0' */
1721 /* correctly finished function result message */
1722 status = PGRES_COMMAND_OK;
1726 /* The backend violates the protocol. */
1727 printfPQExpBuffer(&conn->errorMessage,
1728 "FATAL: PQfn: protocol error: id=0x%x\n",
1730 saveErrorResult(conn);
1731 conn->inStart = conn->inCursor;
1732 return prepareAsyncResult(conn);
1735 case 'E': /* error return */
1736 if (pqGets(&conn->errorMessage, conn))
1738 /* build an error result holding the error message */
1739 saveErrorResult(conn);
1740 status = PGRES_FATAL_ERROR;
1742 case 'A': /* notify message */
1743 /* handle notify and go back to processing return values */
1744 if (getNotify(conn))
1747 case 'N': /* notice */
1748 /* handle notice and go back to processing return values */
1749 if (getNotice(conn))
1752 case 'Z': /* backend is ready for new query */
1753 /* consume the message and exit */
1754 conn->inStart = conn->inCursor;
1755 /* if we saved a result object (probably an error), use it */
1757 return prepareAsyncResult(conn);
1758 return PQmakeEmptyPGresult(conn, status);
1760 /* The backend violates the protocol. */
1761 printfPQExpBuffer(&conn->errorMessage,
1762 "FATAL: PQfn: protocol error: id=0x%x\n",
1764 saveErrorResult(conn);
1765 conn->inStart = conn->inCursor;
1766 return prepareAsyncResult(conn);
1768 /* Completed this message, keep going */
1769 conn->inStart = conn->inCursor;
1773 /* We fall out of the loop only upon failing to read data.
1774 * conn->errorMessage has been set by pqWait or pqReadData.
1775 * We want to append it to any already-received error message.
1777 saveErrorResult(conn);
1778 return prepareAsyncResult(conn);
1782 /* ====== accessor funcs for PGresult ======== */
1785 PQresultStatus(const PGresult *res)
1788 return PGRES_NONFATAL_ERROR;
1789 return res->resultStatus;
1793 PQresStatus(ExecStatusType status)
1795 if (status < 0 || status >= sizeof pgresStatus / sizeof pgresStatus[0])
1796 return "Invalid ExecStatusType code";
1797 return pgresStatus[status];
1801 PQresultErrorMessage(const PGresult *res)
1803 if (!res || !res->errMsg)
1809 PQntuples(const PGresult *res)
1817 PQnfields(const PGresult *res)
1821 return res->numAttributes;
1825 PQbinaryTuples(const PGresult *res)
1833 * Helper routines to range-check field numbers and tuple numbers.
1834 * Return TRUE if OK, FALSE if not
1838 check_field_number(const char *routineName, const PGresult *res, int field_num)
1840 char noticeBuf[128];
1843 return FALSE; /* no way to display error message... */
1844 if (field_num < 0 || field_num >= res->numAttributes)
1846 if (res->noticeHook)
1849 "%s: ERROR! field number %d is out of range 0..%d\n",
1850 routineName, field_num, res->numAttributes - 1);
1851 DONOTICE(res, noticeBuf);
1859 check_tuple_field_number(const char *routineName, const PGresult *res,
1860 int tup_num, int field_num)
1862 char noticeBuf[128];
1865 return FALSE; /* no way to display error message... */
1866 if (tup_num < 0 || tup_num >= res->ntups)
1868 if (res->noticeHook)
1871 "%s: ERROR! tuple number %d is out of range 0..%d\n",
1872 routineName, tup_num, res->ntups - 1);
1873 DONOTICE(res, noticeBuf);
1877 if (field_num < 0 || field_num >= res->numAttributes)
1879 if (res->noticeHook)
1882 "%s: ERROR! field number %d is out of range 0..%d\n",
1883 routineName, field_num, res->numAttributes - 1);
1884 DONOTICE(res, noticeBuf);
1892 returns NULL if the field_num is invalid
1895 PQfname(const PGresult *res, int field_num)
1897 if (!check_field_number("PQfname", res, field_num))
1900 return res->attDescs[field_num].name;
1906 returns -1 on a bad field name
1909 PQfnumber(const PGresult *res, const char *field_name)
1917 if (field_name == NULL ||
1918 field_name[0] == '\0' ||
1919 res->attDescs == NULL)
1922 field_case = strdup(field_name);
1923 if (*field_case == '"')
1925 strcpy(field_case, field_case + 1);
1926 *(field_case + strlen(field_case) - 1) = '\0';
1929 for (i = 0; field_case[i]; i++)
1930 if (isascii((unsigned char) field_case[i]) &&
1931 isupper(field_case[i]))
1932 field_case[i] = tolower(field_case[i]);
1934 for (i = 0; i < res->numAttributes; i++)
1936 if (strcmp(field_case, res->attDescs[i].name) == 0)
1947 PQftype(const PGresult *res, int field_num)
1949 if (!check_field_number("PQftype", res, field_num))
1952 return res->attDescs[field_num].typid;
1958 PQfsize(const PGresult *res, int field_num)
1960 if (!check_field_number("PQfsize", res, field_num))
1963 return res->attDescs[field_num].typlen;
1969 PQfmod(const PGresult *res, int field_num)
1971 if (!check_field_number("PQfmod", res, field_num))
1974 return res->attDescs[field_num].atttypmod;
1980 PQcmdStatus(PGresult *res)
1984 return res->cmdStatus;
1989 if the last command was an INSERT, return the oid string
1993 PQoidStatus(const PGresult *res)
1996 * This must be enough to hold the result. Don't laugh, this is
1997 * better than what this function used to do.
1999 static char buf[24];
2003 if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2006 len = strspn(res->cmdStatus + 7, "0123456789");
2009 strncpy(buf, res->cmdStatus + 7, len);
2017 a perhaps preferable form of the above which just returns
2021 PQoidValue(const PGresult *res)
2023 char * endptr = NULL;
2026 if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2030 result = strtoul(res->cmdStatus + 7, &endptr, 10);
2032 if (!endptr || (*endptr != ' ' && *endptr != '\0') || errno == ERANGE)
2040 if the last command was an INSERT/UPDATE/DELETE, return number
2041 of inserted/affected tuples, if not, return ""
2044 PQcmdTuples(PGresult *res)
2046 char noticeBuf[128];
2051 if (strncmp(res->cmdStatus, "INSERT", 6) == 0 ||
2052 strncmp(res->cmdStatus, "DELETE", 6) == 0 ||
2053 strncmp(res->cmdStatus, "UPDATE", 6) == 0)
2055 char *p = res->cmdStatus + 6;
2059 if (res->noticeHook)
2062 "PQcmdTuples (%s) -- bad input from server\n",
2064 DONOTICE(res, noticeBuf);
2069 if (*(res->cmdStatus) != 'I') /* UPDATE/DELETE */
2071 while (*p != ' ' && *p)
2072 p++; /* INSERT: skip oid */
2075 if (res->noticeHook)
2078 "PQcmdTuples (INSERT) -- there's no # of tuples\n");
2079 DONOTICE(res, noticeBuf);
2091 return the value of field 'field_num' of row 'tup_num'
2093 If res is binary, then the value returned is NOT a null-terminated
2094 ASCII string, but the binary representation in the server's native
2097 if res is not binary, a null-terminated ASCII string is returned.
2100 PQgetvalue(const PGresult *res, int tup_num, int field_num)
2102 if (!check_tuple_field_number("PQgetvalue", res, tup_num, field_num))
2104 return res->tuples[tup_num][field_num].value;
2108 returns the length of a field value in bytes. If res is binary,
2109 i.e. a result of a binary portal, then the length returned does
2110 NOT include the size field of the varlena. (The data returned
2111 by PQgetvalue doesn't either.)
2114 PQgetlength(const PGresult *res, int tup_num, int field_num)
2116 if (!check_tuple_field_number("PQgetlength", res, tup_num, field_num))
2118 if (res->tuples[tup_num][field_num].len != NULL_LEN)
2119 return res->tuples[tup_num][field_num].len;
2125 returns the null status of a field value.
2128 PQgetisnull(const PGresult *res, int tup_num, int field_num)
2130 if (!check_tuple_field_number("PQgetisnull", res, tup_num, field_num))
2131 return 1; /* pretend it is null */
2132 if (res->tuples[tup_num][field_num].len == NULL_LEN)
2138 /* PQsetnonblocking:
2139 sets the PGconn's database connection non-blocking if the arg is TRUE
2140 or makes it non-blocking if the arg is FALSE, this will not protect
2141 you from PQexec(), you'll only be safe when using the non-blocking
2143 Needs to be called only on a connected database connection.
2147 PQsetnonblocking(PGconn *conn, int arg)
2150 arg = (arg == TRUE) ? 1 : 0;
2151 /* early out if the socket is already in the state requested */
2152 if (arg == conn->nonblocking)
2156 * to guarantee constancy for flushing/query/result-polling behavior
2157 * we need to flush the send queue at this point in order to guarantee
2159 * this is ok because either they are making a transition
2160 * _from_ or _to_ blocking mode, either way we can block them.
2162 /* if we are going from blocking to non-blocking flush here */
2166 conn->nonblocking = arg;
2171 /* return the blocking status of the database connection, TRUE == nonblocking,
2175 PQisnonblocking(const PGconn *conn)
2178 return (pqIsnonblocking(conn));
2181 /* try to force data out, really only useful for non-blocking users */
2183 PQflush(PGconn *conn)
2186 return (pqFlush(conn));