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.95 2000/05/25 19:09:55 momjian 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 /* copy connection data we might need for operations on PGresult */
157 result->noticeHook = conn->noticeHook;
158 result->noticeArg = conn->noticeArg;
159 result->client_encoding = conn->client_encoding;
161 /* consider copying conn's errorMessage */
164 case PGRES_EMPTY_QUERY:
165 case PGRES_COMMAND_OK:
166 case PGRES_TUPLES_OK:
169 /* non-error cases */
172 pqSetResultError(result, conn->errorMessage.data);
179 result->noticeHook = NULL;
180 result->noticeArg = NULL;
181 result->client_encoding = 0; /* should be SQL_ASCII */
189 * Allocate subsidiary storage for a PGresult.
191 * nBytes is the amount of space needed for the object.
192 * If isBinary is true, we assume that we need to align the object on
193 * a machine allocation boundary.
194 * If isBinary is false, we assume the object is a char string and can
195 * be allocated on any byte boundary.
198 pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
201 PGresult_data *block;
207 return res->null_field;
210 * If alignment is needed, round up the current position to an
211 * alignment boundary.
215 int offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
219 res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
220 res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
224 /* If there's enough space in the current block, no problem. */
225 if (nBytes <= res->spaceLeft)
227 space = res->curBlock->space + res->curOffset;
228 res->curOffset += nBytes;
229 res->spaceLeft -= nBytes;
234 * If the requested object is very large, give it its own block; this
235 * avoids wasting what might be most of the current block to start a
236 * new block. (We'd have to special-case requests bigger than the
237 * block size anyway.) The object is always given binary alignment in
240 if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
242 block = (PGresult_data *) malloc(nBytes + PGRESULT_BLOCK_OVERHEAD);
245 space = block->space + PGRESULT_BLOCK_OVERHEAD;
250 * Tuck special block below the active block, so that we don't
251 * have to waste the free space in the active block.
253 block->next = res->curBlock->next;
254 res->curBlock->next = block;
258 /* Must set up the new block as the first active block. */
260 res->curBlock = block;
261 res->spaceLeft = 0; /* be sure it's marked full */
266 /* Otherwise, start a new block. */
267 block = (PGresult_data *) malloc(PGRESULT_DATA_BLOCKSIZE);
270 block->next = res->curBlock;
271 res->curBlock = block;
274 /* object needs full alignment */
275 res->curOffset = PGRESULT_BLOCK_OVERHEAD;
276 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - PGRESULT_BLOCK_OVERHEAD;
280 /* we can cram it right after the overhead pointer */
281 res->curOffset = sizeof(PGresult_data);
282 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - sizeof(PGresult_data);
285 space = block->space + res->curOffset;
286 res->curOffset += nBytes;
287 res->spaceLeft -= nBytes;
293 * Like strdup, but the space is subsidiary PGresult space.
296 pqResultStrdup(PGresult *res, const char *str)
298 char *space = (char *) pqResultAlloc(res, strlen(str) + 1, FALSE);
307 * assign a new error message to a PGresult
310 pqSetResultError(PGresult *res, const char *msg)
315 res->errMsg = pqResultStrdup(res, msg);
321 * pqCatenateResultError -
322 * concatenate a new error message to the one already in a PGresult
325 pqCatenateResultError(PGresult *res, const char *msg)
327 PQExpBufferData errorBuf;
331 initPQExpBuffer(&errorBuf);
333 appendPQExpBufferStr(&errorBuf, res->errMsg);
334 appendPQExpBufferStr(&errorBuf, msg);
335 pqSetResultError(res, errorBuf.data);
336 termPQExpBuffer(&errorBuf);
341 * free's the memory associated with a PGresult
344 PQclear(PGresult *res)
346 PGresult_data *block;
351 /* Free all the subsidiary blocks */
352 while ((block = res->curBlock) != NULL)
354 res->curBlock = block->next;
358 /* Free the top-level tuple pointer array */
362 /* Free the PGresult structure itself */
367 * Handy subroutine to deallocate any partially constructed async result.
371 pqClearAsyncResult(PGconn *conn)
374 PQclear(conn->result);
376 conn->curTuple = NULL;
380 * This subroutine deletes any existing async result, sets conn->result
381 * to a PGresult with status PGRES_FATAL_ERROR, and stores the current
382 * contents of conn->errorMessage into that result. It differs from a
383 * plain call on PQmakeEmptyPGresult() in that if there is already an
384 * async result with status PGRES_FATAL_ERROR, the current error message
385 * is APPENDED to the old error message instead of replacing it. This
386 * behavior lets us report multiple error conditions properly, if necessary.
387 * (An example where this is needed is when the backend sends an 'E' message
388 * and immediately closes the connection --- we want to report both the
389 * backend error and the connection closure error.)
392 saveErrorResult(PGconn *conn)
396 * If no old async result, just let PQmakeEmptyPGresult make one.
397 * Likewise if old result is not an error message.
399 if (conn->result == NULL ||
400 conn->result->resultStatus != PGRES_FATAL_ERROR ||
401 conn->result->errMsg == NULL)
403 pqClearAsyncResult(conn);
404 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
408 /* Else, concatenate error message to existing async result. */
409 pqCatenateResultError(conn->result, conn->errorMessage.data);
414 * This subroutine prepares an async result object for return to the caller.
415 * If there is not already an async result object, build an error object
416 * using whatever is in conn->errorMessage. In any case, clear the async
417 * result storage and make sure PQerrorMessage will agree with the result's
421 prepareAsyncResult(PGconn *conn)
426 * conn->result is the PGresult to return. If it is NULL (which
427 * probably shouldn't happen) we assume there is an appropriate error
428 * message in conn->errorMessage.
431 conn->result = NULL; /* handing over ownership to caller */
432 conn->curTuple = NULL; /* just in case */
434 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
439 * Make sure PQerrorMessage agrees with result; it could be
440 * different if we have concatenated messages.
442 resetPQExpBuffer(&conn->errorMessage);
443 appendPQExpBufferStr(&conn->errorMessage,
444 PQresultErrorMessage(res));
451 * add a row pointer to the PGresult structure, growing it if necessary
452 * Returns TRUE if OK, FALSE if not enough memory to add the row
455 addTuple(PGresult *res, PGresAttValue * tup)
457 if (res->ntups >= res->tupArrSize)
461 * Try to grow the array.
463 * We can use realloc because shallow copying of the structure is
464 * okay. Note that the first time through, res->tuples is NULL.
465 * While ANSI says that realloc() should act like malloc() in that
466 * case, some old C libraries (like SunOS 4.1.x) coredump instead.
467 * On failure realloc is supposed to return NULL without damaging
468 * the existing allocation. Note that the positions beyond
469 * res->ntups are garbage, not necessarily NULL.
471 int newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
472 PGresAttValue **newTuples;
474 if (res->tuples == NULL)
475 newTuples = (PGresAttValue **)
476 malloc(newSize * sizeof(PGresAttValue *));
478 newTuples = (PGresAttValue **)
479 realloc(res->tuples, newSize * sizeof(PGresAttValue *));
481 return FALSE; /* malloc or realloc failed */
482 res->tupArrSize = newSize;
483 res->tuples = newTuples;
485 res->tuples[res->ntups] = tup;
493 * Submit a query, but don't wait for it to finish
495 * Returns: 1 if successfully submitted
496 * 0 if error (conn->errorMessage is set)
500 PQsendQuery(PGconn *conn, const char *query)
505 /* clear the error string */
506 resetPQExpBuffer(&conn->errorMessage);
510 printfPQExpBuffer(&conn->errorMessage,
511 "PQsendQuery() -- query pointer is null.\n");
515 /* Don't try to send if we know there's no live connection. */
516 if (conn->status != CONNECTION_OK)
518 printfPQExpBuffer(&conn->errorMessage,
519 "PQsendQuery() -- There is no connection "
520 "to the backend.\n");
523 /* Can't send while already busy, either. */
524 if (conn->asyncStatus != PGASYNC_IDLE)
526 printfPQExpBuffer(&conn->errorMessage,
527 "PQsendQuery() -- another query already in progress.\n");
531 /* initialize async result-accumulation state */
533 conn->curTuple = NULL;
535 /* send the query to the backend; */
538 * in order to guarantee that we don't send a partial query where we
539 * would become out of sync with the backend and/or block during a
540 * non-blocking connection we must first flush the send buffer before
543 * an alternative is to implement 'queue reservations' where we are able
544 * to roll up a transaction (the 'Q' along with our query) and make
545 * sure we have enough space for it all in the send buffer.
547 if (pqIsnonblocking(conn))
551 * the buffer must have emptied completely before we allow a new
552 * query to be buffered
557 /* XXX: if we fail here we really ought to not block */
558 if (pqPutnchar("Q", 1, conn) ||
561 handleSendFailure(conn);
566 * give the data a push, ignore the return value as ConsumeInput()
567 * will do any aditional flushing if needed
569 (void) pqFlush(conn);
575 * the frontend-backend protocol uses 'Q' to designate queries
577 if (pqPutnchar("Q", 1, conn) ||
578 pqPuts(query, conn) ||
581 handleSendFailure(conn);
586 /* OK, it's launched! */
587 conn->asyncStatus = PGASYNC_BUSY;
592 * handleSendFailure: try to clean up after failure to send command.
594 * Primarily, what we want to accomplish here is to process an async
595 * NOTICE message that the backend might have sent just before it died.
597 * NOTE: this routine should only be called in PGASYNC_IDLE state.
601 handleSendFailure(PGconn *conn)
605 * Accept any available input data, ignoring errors. Note that if
606 * pqReadData decides the backend has closed the channel, it will
607 * close our side of the socket --- that's just what we want here.
609 while (pqReadData(conn) > 0)
610 /* loop until no more data readable */ ;
613 * Parse any available input messages. Since we are in PGASYNC_IDLE
614 * state, only NOTICE and NOTIFY messages will be eaten.
620 * Consume any available input from the backend
621 * 0 return: some kind of trouble
622 * 1 return: no problem
626 PQconsumeInput(PGconn *conn)
632 * Load more data, if available. We do this no matter what state we
633 * are in, since we are probably getting called because the
634 * application wants to get rid of a read-select condition. Note that
635 * we will NOT block waiting for more input.
637 if (pqReadData(conn) < 0)
641 * for non-blocking connections try to flush the send-queue
642 * otherwise we may never get a responce for something that may
643 * not have already been sent because it's in our write buffer!
645 if (pqIsnonblocking(conn))
646 (void) pqFlush(conn);
649 /* Parsing of the data waits till later. */
655 * parseInput: if appropriate, parse input data from backend
656 * until input is exhausted or a stopping state is reached.
657 * Note that this function will NOT attempt to read more data from the backend.
661 parseInput(PGconn *conn)
664 char noticeWorkspace[128];
667 * Loop to parse successive complete messages available in the buffer.
673 * Quit if in COPY_OUT state: we expect raw data from the server
674 * until PQendcopy is called. Don't try to parse it according to
675 * the normal protocol. (This is bogus. The data lines ought to
676 * be part of the protocol and have identifying leading
679 if (conn->asyncStatus == PGASYNC_COPY_OUT)
683 * OK to try to read a message type code.
685 conn->inCursor = conn->inStart;
686 if (pqGetc(&id, conn))
690 * NOTIFY and NOTICE messages can happen in any state besides COPY
691 * OUT; always process them right away.
693 * Most other messages should only be processed while in BUSY state.
694 * (In particular, in READY state we hold off further parsing
695 * until the application collects the current PGresult.)
697 * However, if the state is IDLE then we got trouble; we need to deal
698 * with the unexpected message somehow.
710 else if (conn->asyncStatus != PGASYNC_BUSY)
712 /* If not IDLE state, just wait ... */
713 if (conn->asyncStatus != PGASYNC_IDLE)
717 * Unexpected message in IDLE state; need to recover somehow.
718 * ERROR messages are displayed using the notice processor;
719 * anything else is just dropped on the floor after displaying
720 * a suitable warning notice. (An ERROR is very possibly the
721 * backend telling us why it is about to close the connection,
722 * so we don't want to just discard it...)
731 sprintf(noticeWorkspace,
732 "Backend message type 0x%02x arrived while idle\n",
734 DONOTICE(conn, noticeWorkspace);
735 /* Discard the unexpected message; good idea?? */
736 conn->inStart = conn->inEnd;
744 * In BUSY state, we can process everything.
748 case 'C': /* command complete */
749 if (pqGets(&conn->workBuffer, conn))
751 if (conn->result == NULL)
752 conn->result = PQmakeEmptyPGresult(conn,
754 strncpy(conn->result->cmdStatus, conn->workBuffer.data,
756 conn->asyncStatus = PGASYNC_READY;
758 case 'E': /* error return */
759 if (pqGets(&conn->errorMessage, conn))
761 /* build an error result holding the error message */
762 saveErrorResult(conn);
763 conn->asyncStatus = PGASYNC_READY;
765 case 'Z': /* backend is ready for new query */
766 conn->asyncStatus = PGASYNC_IDLE;
768 case 'I': /* empty query */
769 /* read and throw away the closing '\0' */
770 if (pqGetc(&id, conn))
774 sprintf(noticeWorkspace,
775 "unexpected character %c following 'I'\n",
777 DONOTICE(conn, noticeWorkspace);
779 if (conn->result == NULL)
780 conn->result = PQmakeEmptyPGresult(conn,
782 conn->asyncStatus = PGASYNC_READY;
784 case 'K': /* secret key data from the backend */
787 * This is expected only during backend startup, but
788 * it's just as easy to handle it as part of the main
789 * loop. Save the data and continue processing.
791 if (pqGetInt(&(conn->be_pid), 4, conn))
793 if (pqGetInt(&(conn->be_key), 4, conn))
796 case 'P': /* synchronous (normal) portal */
797 if (pqGets(&conn->workBuffer, conn))
799 /* We pretty much ignore this message type... */
801 case 'T': /* row descriptions (start of query
803 if (conn->result == NULL)
805 /* First 'T' in a query sequence */
806 if (getRowDescriptions(conn))
813 * A new 'T' message is treated as the start of
814 * another PGresult. (It is not clear that this
815 * is really possible with the current backend.)
816 * We stop parsing until the application accepts
817 * the current result.
819 conn->asyncStatus = PGASYNC_READY;
823 case 'D': /* ASCII data tuple */
824 if (conn->result != NULL)
826 /* Read another tuple of a normal query response */
827 if (getAnotherTuple(conn, FALSE))
832 sprintf(noticeWorkspace,
833 "Backend sent D message without prior T\n");
834 DONOTICE(conn, noticeWorkspace);
835 /* Discard the unexpected message; good idea?? */
836 conn->inStart = conn->inEnd;
840 case 'B': /* Binary data tuple */
841 if (conn->result != NULL)
843 /* Read another tuple of a normal query response */
844 if (getAnotherTuple(conn, TRUE))
849 sprintf(noticeWorkspace,
850 "Backend sent B message without prior T\n");
851 DONOTICE(conn, noticeWorkspace);
852 /* Discard the unexpected message; good idea?? */
853 conn->inStart = conn->inEnd;
857 case 'G': /* Start Copy In */
858 conn->asyncStatus = PGASYNC_COPY_IN;
860 case 'H': /* Start Copy Out */
861 conn->asyncStatus = PGASYNC_COPY_OUT;
864 printfPQExpBuffer(&conn->errorMessage,
865 "Unknown protocol character '%c' read from backend. "
866 "(The protocol character is the first character the "
867 "backend sends in response to a query it receives).\n",
869 /* build an error result holding the error message */
870 saveErrorResult(conn);
871 /* Discard the unexpected message; good idea?? */
872 conn->inStart = conn->inEnd;
873 conn->asyncStatus = PGASYNC_READY;
875 } /* switch on protocol character */
877 /* Successfully consumed this message */
878 conn->inStart = conn->inCursor;
884 * parseInput subroutine to read a 'T' (row descriptions) message.
885 * We build a PGresult structure containing the attribute data.
886 * Returns: 0 if completed message, EOF if not enough data yet.
888 * Note that if we run out of data, we have to release the partially
889 * constructed PGresult, and rebuild it again next time. Fortunately,
890 * that shouldn't happen often, since 'T' messages usually fit in a packet.
894 getRowDescriptions(PGconn *conn)
900 result = PQmakeEmptyPGresult(conn, PGRES_TUPLES_OK);
902 /* parseInput already read the 'T' label. */
903 /* the next two bytes are the number of fields */
904 if (pqGetInt(&(result->numAttributes), 2, conn))
909 nfields = result->numAttributes;
911 /* allocate space for the attribute descriptors */
914 result->attDescs = (PGresAttDesc *)
915 pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
916 MemSet((char *) result->attDescs, 0, nfields * sizeof(PGresAttDesc));
920 for (i = 0; i < nfields; i++)
926 if (pqGets(&conn->workBuffer, conn) ||
927 pqGetInt(&typid, 4, conn) ||
928 pqGetInt(&typlen, 2, conn) ||
929 pqGetInt(&atttypmod, 4, conn))
936 * Since pqGetInt treats 2-byte integers as unsigned, we need to
937 * coerce the special value "-1" to signed form. (-1 is sent for
938 * variable-length fields.) Formerly, libpq effectively did a
939 * sign-extension on the 2-byte value by storing it in a signed
940 * short. Now we only coerce the single value 65535 == -1; values
941 * 32768..65534 are taken as valid field lengths.
943 if (typlen == 0xFFFF)
945 result->attDescs[i].name = pqResultStrdup(result,
946 conn->workBuffer.data);
947 result->attDescs[i].typid = typid;
948 result->attDescs[i].typlen = typlen;
949 result->attDescs[i].atttypmod = atttypmod;
953 conn->result = result;
958 * parseInput subroutine to read a 'B' or 'D' (row data) message.
959 * We add another tuple to the existing PGresult structure.
960 * Returns: 0 if completed message, EOF if error or not enough data yet.
962 * Note that if we run out of data, we have to suspend and reprocess
963 * the message after more data is received. We keep a partially constructed
964 * tuple in conn->curTuple, and avoid reallocating already-allocated storage.
968 getAnotherTuple(PGconn *conn, int binary)
970 PGresult *result = conn->result;
971 int nfields = result->numAttributes;
974 /* the backend sends us a bitmap of which attributes are null */
975 char std_bitmap[64]; /* used unless it doesn't fit */
976 char *bitmap = std_bitmap;
978 size_t nbytes; /* the number of bytes in bitmap */
979 char bmap; /* One byte of the bitmap */
980 int bitmap_index; /* Its index */
981 int bitcnt; /* number of bits examined in current byte */
982 int vlen; /* length of the current field value */
984 result->binary = binary;
986 /* Allocate tuple space if first time for this data message */
987 if (conn->curTuple == NULL)
989 conn->curTuple = (PGresAttValue *)
990 pqResultAlloc(result, nfields * sizeof(PGresAttValue), TRUE);
991 if (conn->curTuple == NULL)
993 MemSet((char *) conn->curTuple, 0, nfields * sizeof(PGresAttValue));
995 tup = conn->curTuple;
997 /* Get the null-value bitmap */
998 nbytes = (nfields + BYTELEN - 1) / BYTELEN;
999 /* malloc() only for unusually large field counts... */
1000 if (nbytes > sizeof(std_bitmap))
1001 bitmap = (char *) malloc(nbytes);
1003 if (pqGetnchar(bitmap, nbytes, conn))
1006 /* Scan the fields */
1008 bmap = bitmap[bitmap_index];
1011 for (i = 0; i < nfields; i++)
1015 /* if the field value is absent, make it a null string */
1016 tup[i].value = result->null_field;
1017 tup[i].len = NULL_LEN;
1021 /* get the value length (the first four bytes are for length) */
1022 if (pqGetInt(&vlen, 4, conn))
1028 if (tup[i].value == NULL)
1030 tup[i].value = (char *) pqResultAlloc(result, vlen + 1, binary);
1031 if (tup[i].value == NULL)
1035 /* read in the value */
1037 if (pqGetnchar((char *) (tup[i].value), vlen, conn))
1039 /* we have to terminate this ourselves */
1040 tup[i].value[vlen] = '\0';
1042 /* advance the bitmap stuff */
1044 if (bitcnt == BYTELEN)
1047 bmap = bitmap[bitmap_index];
1054 /* Success! Store the completed tuple in the result */
1055 if (!addTuple(result, tup))
1057 /* and reset for a new message */
1058 conn->curTuple = NULL;
1060 if (bitmap != std_bitmap)
1065 /* Replace partially constructed result with an error result */
1068 * we do NOT use saveErrorResult() here, because of the likelihood
1069 * that there's not enough memory to concatenate messages...
1071 pqClearAsyncResult(conn);
1072 printfPQExpBuffer(&conn->errorMessage,
1073 "getAnotherTuple() -- out of memory for result\n");
1074 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1075 conn->asyncStatus = PGASYNC_READY;
1076 /* Discard the failed message --- good idea? */
1077 conn->inStart = conn->inEnd;
1080 if (bitmap != std_bitmap)
1088 * Return TRUE if PQgetResult would block waiting for input.
1092 PQisBusy(PGconn *conn)
1097 /* Parse any available data, if our state permits. */
1100 /* PQgetResult will return immediately in all states except BUSY. */
1101 return conn->asyncStatus == PGASYNC_BUSY;
1107 * Get the next PGresult produced by a query.
1108 * Returns NULL if and only if no query work remains.
1112 PQgetResult(PGconn *conn)
1119 /* Parse any available data, if our state permits. */
1122 /* If not ready to return something, block until we are. */
1123 while (conn->asyncStatus == PGASYNC_BUSY)
1125 /* Wait for some more data, and load it. */
1126 if (pqWait(TRUE, FALSE, conn) ||
1127 pqReadData(conn) < 0)
1131 * conn->errorMessage has been set by pqWait or pqReadData. We
1132 * want to append it to any already-received error message.
1134 saveErrorResult(conn);
1135 conn->asyncStatus = PGASYNC_IDLE;
1136 return prepareAsyncResult(conn);
1142 /* Return the appropriate thing. */
1143 switch (conn->asyncStatus)
1146 res = NULL; /* query is complete */
1149 res = prepareAsyncResult(conn);
1150 /* Set the state back to BUSY, allowing parsing to proceed. */
1151 conn->asyncStatus = PGASYNC_BUSY;
1153 case PGASYNC_COPY_IN:
1154 res = PQmakeEmptyPGresult(conn, PGRES_COPY_IN);
1156 case PGASYNC_COPY_OUT:
1157 res = PQmakeEmptyPGresult(conn, PGRES_COPY_OUT);
1160 printfPQExpBuffer(&conn->errorMessage,
1161 "PQgetResult: Unexpected asyncStatus %d\n",
1162 (int) conn->asyncStatus);
1163 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1173 * send a query to the backend and package up the result in a PGresult
1175 * If the query was not even sent, return NULL; conn->errorMessage is set to
1176 * a relevant message.
1177 * If the query was sent, a new PGresult is returned (which could indicate
1178 * either success or failure).
1179 * The user is responsible for freeing the PGresult via PQclear()
1180 * when done with it.
1184 PQexec(PGconn *conn, const char *query)
1187 PGresult *lastResult;
1191 * we assume anyone calling PQexec wants blocking behaviour, we force
1192 * the blocking status of the connection to blocking for the duration
1193 * of this function and restore it on return
1195 savedblocking = pqIsnonblocking(conn);
1196 if (PQsetnonblocking(conn, FALSE) == -1)
1200 * Silently discard any prior query result that application didn't
1201 * eat. This is probably poor design, but it's here for backward
1204 while ((result = PQgetResult(conn)) != NULL)
1206 if (result->resultStatus == PGRES_COPY_IN ||
1207 result->resultStatus == PGRES_COPY_OUT)
1210 printfPQExpBuffer(&conn->errorMessage,
1211 "PQexec: you gotta get out of a COPY state yourself.\n");
1212 /* restore blocking status */
1218 /* OK to send the message */
1219 if (!PQsendQuery(conn, query))
1220 goto errout; /* restore blocking status */
1223 * For backwards compatibility, return the last result if there are
1224 * more than one --- but merge error messages if we get more than one
1227 * We have to stop if we see copy in/out, however. We will resume parsing
1228 * when application calls PQendcopy.
1231 while ((result = PQgetResult(conn)) != NULL)
1235 if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
1236 result->resultStatus == PGRES_FATAL_ERROR)
1238 pqCatenateResultError(lastResult, result->errMsg);
1240 result = lastResult;
1241 /* Make sure PQerrorMessage agrees with catenated result */
1242 resetPQExpBuffer(&conn->errorMessage);
1243 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
1246 PQclear(lastResult);
1248 lastResult = result;
1249 if (result->resultStatus == PGRES_COPY_IN ||
1250 result->resultStatus == PGRES_COPY_OUT)
1254 if (PQsetnonblocking(conn, savedblocking) == -1)
1259 if (PQsetnonblocking(conn, savedblocking) == -1)
1266 * Attempt to read a Notice response message.
1267 * This is possible in several places, so we break it out as a subroutine.
1268 * Entry: 'N' flag character has already been consumed.
1269 * Exit: returns 0 if successfully consumed Notice message.
1270 * returns EOF if not enough data.
1273 getNotice(PGconn *conn)
1277 * Since the Notice might be pretty long, we create a temporary
1278 * PQExpBuffer rather than using conn->workBuffer. workBuffer is
1279 * intended for stuff that is expected to be short.
1281 PQExpBufferData noticeBuf;
1283 initPQExpBuffer(¬iceBuf);
1284 if (pqGets(¬iceBuf, conn))
1286 termPQExpBuffer(¬iceBuf);
1289 DONOTICE(conn, noticeBuf.data);
1290 termPQExpBuffer(¬iceBuf);
1295 * Attempt to read a Notify response message.
1296 * This is possible in several places, so we break it out as a subroutine.
1297 * Entry: 'A' flag character has already been consumed.
1298 * Exit: returns 0 if successfully consumed Notify message.
1299 * returns EOF if not enough data.
1302 getNotify(PGconn *conn)
1305 PGnotify *newNotify;
1307 if (pqGetInt(&be_pid, 4, conn))
1309 if (pqGets(&conn->workBuffer, conn))
1311 newNotify = (PGnotify *) malloc(sizeof(PGnotify));
1312 strncpy(newNotify->relname, conn->workBuffer.data, NAMEDATALEN);
1313 newNotify->be_pid = be_pid;
1314 DLAddTail(conn->notifyList, DLNewElem(newNotify));
1320 * returns a PGnotify* structure of the latest async notification
1321 * that has not yet been handled
1323 * returns NULL, if there is currently
1324 * no unhandled async notification from the backend
1326 * the CALLER is responsible for FREE'ing the structure returned
1330 PQnotifies(PGconn *conn)
1338 /* Parse any available data to see if we can extract NOTIFY messages. */
1341 /* RemHead returns NULL if list is empty */
1342 e = DLRemHead(conn->notifyList);
1345 event = (PGnotify *) DLE_VAL(e);
1351 * PQgetline - gets a newline-terminated string from the backend.
1353 * Chiefly here so that applications can use "COPY <rel> to stdout"
1354 * and read the output string. Returns a null-terminated string in s.
1356 * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
1357 * the terminating \n (like gets(3)).
1359 * CAUTION: the caller is responsible for detecting the end-of-copy signal
1360 * (a line containing just "\.") when using this routine.
1363 * EOF if it is detected or invalid arguments are given
1364 * 0 if EOL is reached (i.e., \n has been read)
1365 * (this is required for backward-compatibility -- this
1366 * routine used to always return EOF or 0, assuming that
1367 * the line ended within maxlen bytes.)
1368 * 1 in other cases (i.e., the buffer was filled before \n is reached)
1371 PQgetline(PGconn *conn, char *s, int maxlen)
1373 int result = 1; /* return value if buffer overflows */
1375 if (!s || maxlen <= 0)
1378 if (!conn || conn->sock < 0)
1385 * Since this is a purely synchronous routine, we don't bother to
1386 * maintain conn->inCursor; there is no need to back up.
1390 if (conn->inStart < conn->inEnd)
1392 char c = conn->inBuffer[conn->inStart++];
1396 result = 0; /* success exit */
1404 /* need to load more data */
1405 if (pqWait(TRUE, FALSE, conn) ||
1406 pqReadData(conn) < 0)
1419 * PQgetlineAsync - gets a newline-terminated string without blocking.
1421 * This routine is for applications that want to do "COPY <rel> to stdout"
1422 * asynchronously, that is without blocking. Having issued the COPY command
1423 * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
1424 * and this routine until the end-of-data signal is detected. Unlike
1425 * PQgetline, this routine takes responsibility for detecting end-of-data.
1427 * On each call, PQgetlineAsync will return data if a complete newline-
1428 * terminated data line is available in libpq's input buffer, or if the
1429 * incoming data line is too long to fit in the buffer offered by the caller.
1430 * Otherwise, no data is returned until the rest of the line arrives.
1432 * If -1 is returned, the end-of-data signal has been recognized (and removed
1433 * from libpq's input buffer). The caller *must* next call PQendcopy and
1434 * then return to normal processing.
1437 * -1 if the end-of-copy-data marker has been recognized
1438 * 0 if no data is available
1439 * >0 the number of bytes returned.
1440 * The data returned will not extend beyond a newline character. If possible
1441 * a whole line will be returned at one time. But if the buffer offered by
1442 * the caller is too small to hold a line sent by the backend, then a partial
1443 * data line will be returned. This can be detected by testing whether the
1444 * last returned byte is '\n' or not.
1445 * The returned string is *not* null-terminated.
1449 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
1453 if (!conn || conn->asyncStatus != PGASYNC_COPY_OUT)
1454 return -1; /* we are not doing a copy... */
1457 * Move data from libpq's buffer to the caller's. We want to accept
1458 * data only in units of whole lines, not partial lines. This ensures
1459 * that we can recognize the terminator line "\\.\n". (Otherwise, if
1460 * it happened to cross a packet/buffer boundary, we might hand the
1461 * first one or two characters off to the caller, which we shouldn't.)
1464 conn->inCursor = conn->inStart;
1467 while (avail > 0 && conn->inCursor < conn->inEnd)
1469 char c = conn->inBuffer[conn->inCursor++];
1475 /* Got a complete line; mark the data removed from libpq */
1476 conn->inStart = conn->inCursor;
1477 /* Is it the endmarker line? */
1478 if (bufsize - avail == 3 && buffer[-3] == '\\' && buffer[-2] == '.')
1480 /* No, return the data line to the caller */
1481 return bufsize - avail;
1486 * We don't have a complete line. We'd prefer to leave it in libpq's
1487 * buffer until the rest arrives, but there is a special case: what if
1488 * the line is longer than the buffer the caller is offering us? In
1489 * that case we'd better hand over a partial line, else we'd get into
1490 * an infinite loop. Do this in a way that ensures we can't
1491 * misrecognize a terminator line later: leave last 3 characters in
1494 if (avail == 0 && bufsize > 3)
1496 conn->inStart = conn->inCursor - 3;
1503 * PQputline -- sends a string to the backend.
1504 * Returns 0 if OK, EOF if not.
1506 * Chiefly here so that applications can use "COPY <rel> from stdin".
1509 PQputline(PGconn *conn, const char *s)
1511 if (!conn || conn->sock < 0)
1513 return pqPutnchar(s, strlen(s), conn);
1517 * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
1518 * Returns 0 if OK, EOF if not.
1521 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
1523 if (!conn || conn->sock < 0)
1525 return pqPutnchar(buffer, nbytes, conn);
1530 * After completing the data transfer portion of a copy in/out,
1531 * the application must call this routine to finish the command protocol.
1538 PQendcopy(PGconn *conn)
1545 if (conn->asyncStatus != PGASYNC_COPY_IN &&
1546 conn->asyncStatus != PGASYNC_COPY_OUT)
1548 printfPQExpBuffer(&conn->errorMessage,
1549 "PQendcopy() -- I don't think there's a copy in progress.\n");
1554 * make sure no data is waiting to be sent, abort if we are
1555 * non-blocking and the flush fails
1557 if (pqFlush(conn) && pqIsnonblocking(conn))
1560 /* non blocking connections may have to abort at this point. */
1561 if (pqIsnonblocking(conn) && PQisBusy(conn))
1564 /* Return to active duty */
1565 conn->asyncStatus = PGASYNC_BUSY;
1566 resetPQExpBuffer(&conn->errorMessage);
1568 /* Wait for the completion response */
1569 result = PQgetResult(conn);
1571 /* Expecting a successful result */
1572 if (result && result->resultStatus == PGRES_COMMAND_OK)
1579 * Trouble. The worst case is that we've lost sync with the backend
1580 * entirely due to application screwup of the copy in/out protocol. To
1581 * recover, reset the connection (talk about using a sledgehammer...)
1585 if (conn->errorMessage.len > 0)
1586 DONOTICE(conn, conn->errorMessage.data);
1588 DONOTICE(conn, "PQendcopy: resetting connection\n");
1591 * Users doing non-blocking connections need to handle the reset
1592 * themselves, they'll need to check the connection status if we
1595 if (pqIsnonblocking(conn))
1605 * PQfn - Send a function call to the POSTGRES backend.
1607 * conn : backend connection
1608 * fnid : function id
1609 * result_buf : pointer to result buffer (&int if integer)
1610 * result_len : length of return value.
1611 * actual_result_len: actual length returned. (differs from result_len
1612 * for varlena structures.)
1613 * result_type : If the result is an integer, this must be 1,
1614 * otherwise this should be 0
1615 * args : pointer to an array of function arguments.
1616 * (each has length, if integer, and value/pointer)
1617 * nargs : # of arguments in args array.
1620 * PGresult with status = PGRES_COMMAND_OK if successful.
1621 * *actual_result_len is > 0 if there is a return value, 0 if not.
1622 * PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
1623 * NULL on communications failure. conn->errorMessage will be set.
1631 int *actual_result_len,
1633 const PQArgBlock *args,
1636 bool needInput = false;
1637 ExecStatusType status = PGRES_FATAL_ERROR;
1641 *actual_result_len = 0;
1646 /* clear the error string */
1647 resetPQExpBuffer(&conn->errorMessage);
1649 if (conn->sock < 0 || conn->asyncStatus != PGASYNC_IDLE ||
1650 conn->result != NULL)
1652 printfPQExpBuffer(&conn->errorMessage,
1653 "PQfn() -- connection in wrong state\n");
1657 if (pqPuts("F ", conn) || /* function */
1658 pqPutInt(fnid, 4, conn) || /* function id */
1659 pqPutInt(nargs, 4, conn)) /* # of args */
1661 handleSendFailure(conn);
1665 for (i = 0; i < nargs; ++i)
1666 { /* len.int4 + contents */
1667 if (pqPutInt(args[i].len, 4, conn))
1669 handleSendFailure(conn);
1675 if (pqPutInt(args[i].u.integer, 4, conn))
1677 handleSendFailure(conn);
1683 if (pqPutnchar((char *) args[i].u.ptr, args[i].len, conn))
1685 handleSendFailure(conn);
1692 handleSendFailure(conn);
1700 /* Wait for some data to arrive (or for the channel to close) */
1701 if (pqWait(TRUE, FALSE, conn) ||
1702 pqReadData(conn) < 0)
1707 * Scan the message. If we run out of data, loop around to try
1710 conn->inCursor = conn->inStart;
1713 if (pqGetc(&id, conn))
1717 * We should see V or E response to the command, but might get N
1718 * and/or A notices first. We also need to swallow the final Z
1723 case 'V': /* function result */
1724 if (pqGetc(&id, conn))
1728 /* function returned nonempty value */
1729 if (pqGetInt(actual_result_len, 4, conn))
1733 if (pqGetInt(result_buf, 4, conn))
1738 if (pqGetnchar((char *) result_buf,
1743 if (pqGetc(&id, conn)) /* get the last '0' */
1748 /* correctly finished function result message */
1749 status = PGRES_COMMAND_OK;
1753 /* The backend violates the protocol. */
1754 printfPQExpBuffer(&conn->errorMessage,
1755 "FATAL: PQfn: protocol error: id=0x%x\n",
1757 saveErrorResult(conn);
1758 conn->inStart = conn->inCursor;
1759 return prepareAsyncResult(conn);
1762 case 'E': /* error return */
1763 if (pqGets(&conn->errorMessage, conn))
1765 /* build an error result holding the error message */
1766 saveErrorResult(conn);
1767 status = PGRES_FATAL_ERROR;
1769 case 'A': /* notify message */
1770 /* handle notify and go back to processing return values */
1771 if (getNotify(conn))
1774 case 'N': /* notice */
1775 /* handle notice and go back to processing return values */
1776 if (getNotice(conn))
1779 case 'Z': /* backend is ready for new query */
1780 /* consume the message and exit */
1781 conn->inStart = conn->inCursor;
1782 /* if we saved a result object (probably an error), use it */
1784 return prepareAsyncResult(conn);
1785 return PQmakeEmptyPGresult(conn, status);
1787 /* The backend violates the protocol. */
1788 printfPQExpBuffer(&conn->errorMessage,
1789 "FATAL: PQfn: protocol error: id=0x%x\n",
1791 saveErrorResult(conn);
1792 conn->inStart = conn->inCursor;
1793 return prepareAsyncResult(conn);
1795 /* Completed this message, keep going */
1796 conn->inStart = conn->inCursor;
1801 * We fall out of the loop only upon failing to read data.
1802 * conn->errorMessage has been set by pqWait or pqReadData. We want to
1803 * append it to any already-received error message.
1805 saveErrorResult(conn);
1806 return prepareAsyncResult(conn);
1810 /* ====== accessor funcs for PGresult ======== */
1813 PQresultStatus(const PGresult *res)
1816 return PGRES_NONFATAL_ERROR;
1817 return res->resultStatus;
1821 PQresStatus(ExecStatusType status)
1823 if (status < 0 || status >= sizeof pgresStatus / sizeof pgresStatus[0])
1824 return "Invalid ExecStatusType code";
1825 return pgresStatus[status];
1829 PQresultErrorMessage(const PGresult *res)
1831 if (!res || !res->errMsg)
1837 PQntuples(const PGresult *res)
1845 PQnfields(const PGresult *res)
1849 return res->numAttributes;
1853 PQbinaryTuples(const PGresult *res)
1861 * Helper routines to range-check field numbers and tuple numbers.
1862 * Return TRUE if OK, FALSE if not
1866 check_field_number(const char *routineName, const PGresult *res, int field_num)
1868 char noticeBuf[128];
1871 return FALSE; /* no way to display error message... */
1872 if (field_num < 0 || field_num >= res->numAttributes)
1874 if (res->noticeHook)
1877 "%s: ERROR! field number %d is out of range 0..%d\n",
1878 routineName, field_num, res->numAttributes - 1);
1879 DONOTICE(res, noticeBuf);
1887 check_tuple_field_number(const char *routineName, const PGresult *res,
1888 int tup_num, int field_num)
1890 char noticeBuf[128];
1893 return FALSE; /* no way to display error message... */
1894 if (tup_num < 0 || tup_num >= res->ntups)
1896 if (res->noticeHook)
1899 "%s: ERROR! tuple number %d is out of range 0..%d\n",
1900 routineName, tup_num, res->ntups - 1);
1901 DONOTICE(res, noticeBuf);
1905 if (field_num < 0 || field_num >= res->numAttributes)
1907 if (res->noticeHook)
1910 "%s: ERROR! field number %d is out of range 0..%d\n",
1911 routineName, field_num, res->numAttributes - 1);
1912 DONOTICE(res, noticeBuf);
1920 returns NULL if the field_num is invalid
1923 PQfname(const PGresult *res, int field_num)
1925 if (!check_field_number("PQfname", res, field_num))
1928 return res->attDescs[field_num].name;
1934 returns -1 on a bad field name
1937 PQfnumber(const PGresult *res, const char *field_name)
1945 if (field_name == NULL ||
1946 field_name[0] == '\0' ||
1947 res->attDescs == NULL)
1950 field_case = strdup(field_name);
1951 if (*field_case == '"')
1953 strcpy(field_case, field_case + 1);
1954 *(field_case + strlen(field_case) - 1) = '\0';
1957 for (i = 0; field_case[i]; i++)
1958 if (isascii((unsigned char) field_case[i]) &&
1959 isupper(field_case[i]))
1960 field_case[i] = tolower(field_case[i]);
1962 for (i = 0; i < res->numAttributes; i++)
1964 if (strcmp(field_case, res->attDescs[i].name) == 0)
1975 PQftype(const PGresult *res, int field_num)
1977 if (!check_field_number("PQftype", res, field_num))
1980 return res->attDescs[field_num].typid;
1986 PQfsize(const PGresult *res, int field_num)
1988 if (!check_field_number("PQfsize", res, field_num))
1991 return res->attDescs[field_num].typlen;
1997 PQfmod(const PGresult *res, int field_num)
1999 if (!check_field_number("PQfmod", res, field_num))
2002 return res->attDescs[field_num].atttypmod;
2008 PQcmdStatus(PGresult *res)
2012 return res->cmdStatus;
2017 if the last command was an INSERT, return the oid string
2021 PQoidStatus(const PGresult *res)
2025 * This must be enough to hold the result. Don't laugh, this is better
2026 * than what this function used to do.
2028 static char buf[24];
2032 if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2035 len = strspn(res->cmdStatus + 7, "0123456789");
2038 strncpy(buf, res->cmdStatus + 7, len);
2046 a perhaps preferable form of the above which just returns
2050 PQoidValue(const PGresult *res)
2052 char *endptr = NULL;
2055 if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2059 result = strtoul(res->cmdStatus + 7, &endptr, 10);
2061 if (!endptr || (*endptr != ' ' && *endptr != '\0') || errno == ERANGE)
2064 return (Oid) result;
2069 if the last command was an INSERT/UPDATE/DELETE, return number
2070 of inserted/affected tuples, if not, return ""
2073 PQcmdTuples(PGresult *res)
2075 char noticeBuf[128];
2080 if (strncmp(res->cmdStatus, "INSERT", 6) == 0 ||
2081 strncmp(res->cmdStatus, "DELETE", 6) == 0 ||
2082 strncmp(res->cmdStatus, "UPDATE", 6) == 0)
2084 char *p = res->cmdStatus + 6;
2088 if (res->noticeHook)
2091 "PQcmdTuples (%s) -- bad input from server\n",
2093 DONOTICE(res, noticeBuf);
2098 if (*(res->cmdStatus) != 'I') /* UPDATE/DELETE */
2100 while (*p != ' ' && *p)
2101 p++; /* INSERT: skip oid */
2104 if (res->noticeHook)
2107 "PQcmdTuples (INSERT) -- there's no # of tuples\n");
2108 DONOTICE(res, noticeBuf);
2120 return the value of field 'field_num' of row 'tup_num'
2122 If res is binary, then the value returned is NOT a null-terminated
2123 ASCII string, but the binary representation in the server's native
2126 if res is not binary, a null-terminated ASCII string is returned.
2129 PQgetvalue(const PGresult *res, int tup_num, int field_num)
2131 if (!check_tuple_field_number("PQgetvalue", res, tup_num, field_num))
2133 return res->tuples[tup_num][field_num].value;
2137 returns the length of a field value in bytes. If res is binary,
2138 i.e. a result of a binary portal, then the length returned does
2139 NOT include the size field of the varlena. (The data returned
2140 by PQgetvalue doesn't either.)
2143 PQgetlength(const PGresult *res, int tup_num, int field_num)
2145 if (!check_tuple_field_number("PQgetlength", res, tup_num, field_num))
2147 if (res->tuples[tup_num][field_num].len != NULL_LEN)
2148 return res->tuples[tup_num][field_num].len;
2154 returns the null status of a field value.
2157 PQgetisnull(const PGresult *res, int tup_num, int field_num)
2159 if (!check_tuple_field_number("PQgetisnull", res, tup_num, field_num))
2160 return 1; /* pretend it is null */
2161 if (res->tuples[tup_num][field_num].len == NULL_LEN)
2167 /* PQsetnonblocking:
2168 sets the PGconn's database connection non-blocking if the arg is TRUE
2169 or makes it non-blocking if the arg is FALSE, this will not protect
2170 you from PQexec(), you'll only be safe when using the non-blocking
2172 Needs to be called only on a connected database connection.
2176 PQsetnonblocking(PGconn *conn, int arg)
2179 arg = (arg == TRUE) ? 1 : 0;
2180 /* early out if the socket is already in the state requested */
2181 if (arg == conn->nonblocking)
2185 * to guarantee constancy for flushing/query/result-polling behavior
2186 * we need to flush the send queue at this point in order to guarantee
2187 * proper behavior. this is ok because either they are making a
2188 * transition _from_ or _to_ blocking mode, either way we can block
2191 /* if we are going from blocking to non-blocking flush here */
2195 conn->nonblocking = arg;
2200 /* return the blocking status of the database connection, TRUE == nonblocking,
2204 PQisnonblocking(const PGconn *conn)
2207 return (pqIsnonblocking(conn));
2210 /* try to force data out, really only useful for non-blocking users */
2212 PQflush(PGconn *conn)
2215 return (pqFlush(conn));