1 /*-------------------------------------------------------------------------
4 * functions that are specific to frontend/backend protocol version 2
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/interfaces/libpq/fe-protocol2.c
13 *-------------------------------------------------------------------------
15 #include "postgres_fe.h"
21 #include "libpq-int.h"
28 #include <netinet/in.h>
29 #ifdef HAVE_NETINET_TCP_H
30 #include <netinet/tcp.h>
32 #include <arpa/inet.h>
36 static int getRowDescriptions(PGconn *conn);
37 static int getAnotherTuple(PGconn *conn, bool binary);
38 static int pqGetErrorNotice2(PGconn *conn, bool isError);
39 static void checkXactStatus(PGconn *conn, const char *cmdTag);
40 static int getNotify(PGconn *conn);
46 * Polls the process of passing the values of a standard set of environment
47 * variables to the backend.
49 PostgresPollingStatusType
50 pqSetenvPoll(PGconn *conn)
54 if (conn == NULL || conn->status == CONNECTION_BAD)
55 return PGRES_POLLING_FAILED;
57 /* Check whether there are any data for us */
58 switch (conn->setenv_state)
60 /* These are reading states */
61 case SETENV_STATE_OPTION_WAIT:
62 case SETENV_STATE_QUERY1_WAIT:
63 case SETENV_STATE_QUERY2_WAIT:
65 /* Load waiting data */
66 int n = pqReadData(conn);
71 return PGRES_POLLING_READING;
76 /* These are writing states, so we just proceed. */
77 case SETENV_STATE_OPTION_SEND:
78 case SETENV_STATE_QUERY1_SEND:
79 case SETENV_STATE_QUERY2_SEND:
82 /* Should we raise an error if called when not active? */
83 case SETENV_STATE_IDLE:
84 return PGRES_POLLING_OK;
87 printfPQExpBuffer(&conn->errorMessage,
89 "invalid setenv state %c, "
90 "probably indicative of memory corruption\n"
96 /* We will loop here until there is nothing left to do in this call. */
99 switch (conn->setenv_state)
101 case SETENV_STATE_OPTION_SEND:
104 * Send SET commands for stuff directed by Environment
105 * Options. Note: we assume that SET commands won't start
106 * transaction blocks, even in a 7.3 server with
109 char setQuery[100]; /* note length limit in
112 if (conn->next_eo->envName)
116 if ((val = getenv(conn->next_eo->envName)))
118 if (pg_strcasecmp(val, "default") == 0)
119 sprintf(setQuery, "SET %s = DEFAULT",
120 conn->next_eo->pgName);
122 sprintf(setQuery, "SET %s = '%.60s'",
123 conn->next_eo->pgName, val);
126 "Use environment variable %s to send %s\n",
127 conn->next_eo->envName, setQuery);
129 if (!PQsendQuery(conn, setQuery))
132 conn->setenv_state = SETENV_STATE_OPTION_WAIT;
139 /* No more options to send, so move on to querying */
140 conn->setenv_state = SETENV_STATE_QUERY1_SEND;
145 case SETENV_STATE_OPTION_WAIT:
148 return PGRES_POLLING_READING;
150 res = PQgetResult(conn);
154 if (PQresultStatus(res) != PGRES_COMMAND_OK)
160 /* Keep reading until PQgetResult returns NULL */
164 /* Query finished, so send the next option */
166 conn->setenv_state = SETENV_STATE_OPTION_SEND;
171 case SETENV_STATE_QUERY1_SEND:
174 * Issue query to get information we need. Here we must
175 * use begin/commit in case autocommit is off by default
178 * Note: version() exists in all protocol-2.0-supporting
179 * backends. In 7.3 it would be safer to write
180 * pg_catalog.version(), but we can't do that without
181 * causing problems on older versions.
183 if (!PQsendQuery(conn, "begin; select version(); end"))
186 conn->setenv_state = SETENV_STATE_QUERY1_WAIT;
187 return PGRES_POLLING_READING;
190 case SETENV_STATE_QUERY1_WAIT:
193 return PGRES_POLLING_READING;
195 res = PQgetResult(conn);
201 if (PQresultStatus(res) == PGRES_COMMAND_OK)
203 /* ignore begin/commit command results */
208 if (PQresultStatus(res) != PGRES_TUPLES_OK ||
216 * Extract server version and save as if
219 val = PQgetvalue(res, 0, 0);
220 if (val && strncmp(val, "PostgreSQL ", 11) == 0)
224 /* strip off PostgreSQL part */
228 * strip off platform part (scribbles on result,
231 ptr = strchr(val, ' ');
235 pqSaveParameterStatus(conn, "server_version",
240 /* Keep reading until PQgetResult returns NULL */
244 /* Query finished, move to next */
245 conn->setenv_state = SETENV_STATE_QUERY2_SEND;
250 case SETENV_STATE_QUERY2_SEND:
255 * pg_client_encoding does not exist in pre-7.2 servers.
256 * So we need to be prepared for an error here. Do *not*
257 * start a transaction block, except in 7.3 servers where
258 * we need to prevent autocommit-off from starting a
259 * transaction anyway.
261 if (conn->sversion >= 70300 &&
262 conn->sversion < 70400)
263 query = "begin; select pg_catalog.pg_client_encoding(); end";
265 query = "select pg_client_encoding()";
266 if (!PQsendQuery(conn, query))
269 conn->setenv_state = SETENV_STATE_QUERY2_WAIT;
270 return PGRES_POLLING_READING;
273 case SETENV_STATE_QUERY2_WAIT:
276 return PGRES_POLLING_READING;
278 res = PQgetResult(conn);
284 if (PQresultStatus(res) == PGRES_COMMAND_OK)
286 /* ignore begin/commit command results */
291 if (PQresultStatus(res) == PGRES_TUPLES_OK &&
294 /* Extract client encoding and save it */
295 val = PQgetvalue(res, 0, 0);
296 if (val && *val) /* null should not happen, but */
297 pqSaveParameterStatus(conn, "client_encoding",
303 * Error: presumably function not available, so
304 * use PGCLIENTENCODING or SQL_ASCII as the
307 val = getenv("PGCLIENTENCODING");
309 pqSaveParameterStatus(conn, "client_encoding",
312 pqSaveParameterStatus(conn, "client_encoding",
317 /* Keep reading until PQgetResult returns NULL */
321 /* Query finished, so we're done */
322 conn->setenv_state = SETENV_STATE_IDLE;
323 return PGRES_POLLING_OK;
329 printfPQExpBuffer(&conn->errorMessage,
330 libpq_gettext("invalid state %c, "
331 "probably indicative of memory corruption\n"),
340 conn->setenv_state = SETENV_STATE_IDLE;
341 return PGRES_POLLING_FAILED;
346 * parseInput: if appropriate, parse input data from backend
347 * until input is exhausted or a stopping state is reached.
348 * Note that this function will NOT attempt to read more data from the backend.
351 pqParseInput2(PGconn *conn)
356 * Loop to parse successive complete messages available in the buffer.
361 * Quit if in COPY_OUT state: we expect raw data from the server until
362 * PQendcopy is called. Don't try to parse it according to the normal
363 * protocol. (This is bogus. The data lines ought to be part of the
364 * protocol and have identifying leading characters.)
366 if (conn->asyncStatus == PGASYNC_COPY_OUT)
370 * OK to try to read a message type code.
372 conn->inCursor = conn->inStart;
373 if (pqGetc(&id, conn))
377 * NOTIFY and NOTICE messages can happen in any state besides COPY
378 * OUT; always process them right away.
380 * Most other messages should only be processed while in BUSY state.
381 * (In particular, in READY state we hold off further parsing until
382 * the application collects the current PGresult.)
384 * However, if the state is IDLE then we got trouble; we need to deal
385 * with the unexpected message somehow.
394 if (pqGetErrorNotice2(conn, false))
397 else if (conn->asyncStatus != PGASYNC_BUSY)
399 /* If not IDLE state, just wait ... */
400 if (conn->asyncStatus != PGASYNC_IDLE)
404 * Unexpected message in IDLE state; need to recover somehow.
405 * ERROR messages are displayed using the notice processor;
406 * anything else is just dropped on the floor after displaying a
407 * suitable warning notice. (An ERROR is very possibly the
408 * backend telling us why it is about to close the connection, so
409 * we don't want to just discard it...)
413 if (pqGetErrorNotice2(conn, false /* treat as notice */ ))
418 pqInternalNotice(&conn->noticeHooks,
419 "message type 0x%02x arrived from server while idle",
421 /* Discard the unexpected message; good idea?? */
422 conn->inStart = conn->inEnd;
429 * In BUSY state, we can process everything.
433 case 'C': /* command complete */
434 if (pqGets(&conn->workBuffer, conn))
436 if (conn->result == NULL)
438 conn->result = PQmakeEmptyPGresult(conn,
443 strncpy(conn->result->cmdStatus, conn->workBuffer.data,
445 checkXactStatus(conn, conn->workBuffer.data);
446 conn->asyncStatus = PGASYNC_READY;
448 case 'E': /* error return */
449 if (pqGetErrorNotice2(conn, true))
451 conn->asyncStatus = PGASYNC_READY;
453 case 'Z': /* backend is ready for new query */
454 conn->asyncStatus = PGASYNC_IDLE;
456 case 'I': /* empty query */
457 /* read and throw away the closing '\0' */
458 if (pqGetc(&id, conn))
461 pqInternalNotice(&conn->noticeHooks,
462 "unexpected character %c following empty query response (\"I\" message)",
464 if (conn->result == NULL)
465 conn->result = PQmakeEmptyPGresult(conn,
467 conn->asyncStatus = PGASYNC_READY;
469 case 'K': /* secret key data from the backend */
472 * This is expected only during backend startup, but it's
473 * just as easy to handle it as part of the main loop.
474 * Save the data and continue processing.
476 if (pqGetInt(&(conn->be_pid), 4, conn))
478 if (pqGetInt(&(conn->be_key), 4, conn))
481 case 'P': /* synchronous (normal) portal */
482 if (pqGets(&conn->workBuffer, conn))
484 /* We pretty much ignore this message type... */
486 case 'T': /* row descriptions (start of query results) */
487 if (conn->result == NULL)
489 /* First 'T' in a query sequence */
490 if (getRowDescriptions(conn))
496 * A new 'T' message is treated as the start of
497 * another PGresult. (It is not clear that this is
498 * really possible with the current backend.) We stop
499 * parsing until the application accepts the current
502 conn->asyncStatus = PGASYNC_READY;
506 case 'D': /* ASCII data tuple */
507 if (conn->result != NULL)
509 /* Read another tuple of a normal query response */
510 if (getAnotherTuple(conn, FALSE))
515 pqInternalNotice(&conn->noticeHooks,
516 "server sent data (\"D\" message) without prior row description (\"T\" message)");
517 /* Discard the unexpected message; good idea?? */
518 conn->inStart = conn->inEnd;
522 case 'B': /* Binary data tuple */
523 if (conn->result != NULL)
525 /* Read another tuple of a normal query response */
526 if (getAnotherTuple(conn, TRUE))
531 pqInternalNotice(&conn->noticeHooks,
532 "server sent binary data (\"B\" message) without prior row description (\"T\" message)");
533 /* Discard the unexpected message; good idea?? */
534 conn->inStart = conn->inEnd;
538 case 'G': /* Start Copy In */
539 conn->asyncStatus = PGASYNC_COPY_IN;
541 case 'H': /* Start Copy Out */
542 conn->asyncStatus = PGASYNC_COPY_OUT;
545 * Don't need to process CopyBothResponse here because
546 * it never arrives from the server during protocol 2.0.
549 printfPQExpBuffer(&conn->errorMessage,
551 "unexpected response from server; first received character was \"%c\"\n"),
553 /* build an error result holding the error message */
554 pqSaveErrorResult(conn);
555 /* Discard the unexpected message; good idea?? */
556 conn->inStart = conn->inEnd;
557 conn->asyncStatus = PGASYNC_READY;
559 } /* switch on protocol character */
561 /* Successfully consumed this message */
562 conn->inStart = conn->inCursor;
567 * parseInput subroutine to read a 'T' (row descriptions) message.
568 * We build a PGresult structure containing the attribute data.
569 * Returns: 0 if completed message, EOF if not enough data yet.
571 * Note that if we run out of data, we have to release the partially
572 * constructed PGresult, and rebuild it again next time. Fortunately,
573 * that shouldn't happen often, since 'T' messages usually fit in a packet.
576 getRowDescriptions(PGconn *conn)
578 PGresult *result = NULL;
582 result = PQmakeEmptyPGresult(conn, PGRES_TUPLES_OK);
586 /* parseInput already read the 'T' label. */
587 /* the next two bytes are the number of fields */
588 if (pqGetInt(&(result->numAttributes), 2, conn))
590 nfields = result->numAttributes;
592 /* allocate space for the attribute descriptors */
595 result->attDescs = (PGresAttDesc *)
596 pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
597 if (!result->attDescs)
599 MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
603 for (i = 0; i < nfields; i++)
609 if (pqGets(&conn->workBuffer, conn) ||
610 pqGetInt(&typid, 4, conn) ||
611 pqGetInt(&typlen, 2, conn) ||
612 pqGetInt(&atttypmod, 4, conn))
616 * Since pqGetInt treats 2-byte integers as unsigned, we need to
617 * coerce the result to signed form.
619 typlen = (int) ((int16) typlen);
621 result->attDescs[i].name = pqResultStrdup(result,
622 conn->workBuffer.data);
623 if (!result->attDescs[i].name)
625 result->attDescs[i].tableid = 0;
626 result->attDescs[i].columnid = 0;
627 result->attDescs[i].format = 0;
628 result->attDescs[i].typid = typid;
629 result->attDescs[i].typlen = typlen;
630 result->attDescs[i].atttypmod = atttypmod;
634 conn->result = result;
644 * parseInput subroutine to read a 'B' or 'D' (row data) message.
645 * We add another tuple to the existing PGresult structure.
646 * Returns: 0 if completed message, EOF if error or not enough data yet.
648 * Note that if we run out of data, we have to suspend and reprocess
649 * the message after more data is received. We keep a partially constructed
650 * tuple in conn->curTuple, and avoid reallocating already-allocated storage.
653 getAnotherTuple(PGconn *conn, bool binary)
655 PGresult *result = conn->result;
656 int nfields = result->numAttributes;
659 /* the backend sends us a bitmap of which attributes are null */
660 char std_bitmap[64]; /* used unless it doesn't fit */
661 char *bitmap = std_bitmap;
663 size_t nbytes; /* the number of bytes in bitmap */
664 char bmap; /* One byte of the bitmap */
665 int bitmap_index; /* Its index */
666 int bitcnt; /* number of bits examined in current byte */
667 int vlen; /* length of the current field value */
669 result->binary = binary;
671 /* Allocate tuple space if first time for this data message */
672 if (conn->curTuple == NULL)
674 conn->curTuple = (PGresAttValue *)
675 pqResultAlloc(result, nfields * sizeof(PGresAttValue), TRUE);
676 if (conn->curTuple == NULL)
678 MemSet(conn->curTuple, 0, nfields * sizeof(PGresAttValue));
681 * If it's binary, fix the column format indicators. We assume the
682 * backend will consistently send either B or D, not a mix.
686 for (i = 0; i < nfields; i++)
687 result->attDescs[i].format = 1;
690 tup = conn->curTuple;
692 /* Get the null-value bitmap */
693 nbytes = (nfields + BITS_PER_BYTE - 1) / BITS_PER_BYTE;
694 /* malloc() only for unusually large field counts... */
695 if (nbytes > sizeof(std_bitmap))
697 bitmap = (char *) malloc(nbytes);
702 if (pqGetnchar(bitmap, nbytes, conn))
705 /* Scan the fields */
707 bmap = bitmap[bitmap_index];
710 for (i = 0; i < nfields; i++)
714 /* if the field value is absent, make it a null string */
715 tup[i].value = result->null_field;
716 tup[i].len = NULL_LEN;
720 /* get the value length (the first four bytes are for length) */
721 if (pqGetInt(&vlen, 4, conn))
727 if (tup[i].value == NULL)
729 tup[i].value = (char *) pqResultAlloc(result, vlen + 1, binary);
730 if (tup[i].value == NULL)
734 /* read in the value */
736 if (pqGetnchar((char *) (tup[i].value), vlen, conn))
738 /* we have to terminate this ourselves */
739 tup[i].value[vlen] = '\0';
741 /* advance the bitmap stuff */
743 if (bitcnt == BITS_PER_BYTE)
746 bmap = bitmap[bitmap_index];
753 /* Success! Store the completed tuple in the result */
754 if (!pqAddTuple(result, tup))
756 /* and reset for a new message */
757 conn->curTuple = NULL;
759 if (bitmap != std_bitmap)
764 /* Replace partially constructed result with an error result */
767 * we do NOT use pqSaveErrorResult() here, because of the likelihood that
768 * there's not enough memory to concatenate messages...
770 pqClearAsyncResult(conn);
771 printfPQExpBuffer(&conn->errorMessage,
772 libpq_gettext("out of memory for query result\n"));
775 * XXX: if PQmakeEmptyPGresult() fails, there's probably not much we can
778 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
779 conn->asyncStatus = PGASYNC_READY;
780 /* Discard the failed message --- good idea? */
781 conn->inStart = conn->inEnd;
784 if (bitmap != NULL && bitmap != std_bitmap)
791 * Attempt to read an Error or Notice response message.
792 * This is possible in several places, so we break it out as a subroutine.
793 * Entry: 'E' or 'N' message type has already been consumed.
794 * Exit: returns 0 if successfully consumed message.
795 * returns EOF if not enough data.
798 pqGetErrorNotice2(PGconn *conn, bool isError)
800 PGresult *res = NULL;
801 PQExpBufferData workBuf;
806 * Since the message might be pretty long, we create a temporary
807 * PQExpBuffer rather than using conn->workBuffer. workBuffer is intended
808 * for stuff that is expected to be short.
810 initPQExpBuffer(&workBuf);
811 if (pqGets(&workBuf, conn))
815 * Make a PGresult to hold the message. We temporarily lie about the
816 * result status, so that PQmakeEmptyPGresult doesn't uselessly copy
817 * conn->errorMessage.
819 res = PQmakeEmptyPGresult(conn, PGRES_EMPTY_QUERY);
822 res->resultStatus = isError ? PGRES_FATAL_ERROR : PGRES_NONFATAL_ERROR;
823 res->errMsg = pqResultStrdup(res, workBuf.data);
828 * Break the message into fields. We can't do very much here, but we can
829 * split the severity code off, and remove trailing newlines. Also, we use
830 * the heuristic that the primary message extends only to the first
831 * newline --- anything after that is detail message. (In some cases it'd
832 * be better classed as hint, but we can hardly be expected to guess that
835 while (workBuf.len > 0 && workBuf.data[workBuf.len - 1] == '\n')
836 workBuf.data[--workBuf.len] = '\0';
837 splitp = strstr(workBuf.data, ": ");
840 /* what comes before the colon is severity */
842 pqSaveMessageField(res, PG_DIAG_SEVERITY, workBuf.data);
847 /* can't find a colon? oh well... */
848 startp = workBuf.data;
850 splitp = strchr(startp, '\n');
853 /* what comes before the newline is primary message */
855 pqSaveMessageField(res, PG_DIAG_MESSAGE_PRIMARY, startp);
856 /* the rest is detail; strip any leading whitespace */
857 while (*splitp && isspace((unsigned char) *splitp))
859 pqSaveMessageField(res, PG_DIAG_MESSAGE_DETAIL, splitp);
863 /* single-line message, so all primary */
864 pqSaveMessageField(res, PG_DIAG_MESSAGE_PRIMARY, startp);
868 * Either save error as current async result, or just emit the notice.
869 * Also, if it's an error and we were in a transaction block, assume the
870 * server has now gone to error-in-transaction state.
874 pqClearAsyncResult(conn);
876 resetPQExpBuffer(&conn->errorMessage);
877 appendPQExpBufferStr(&conn->errorMessage, res->errMsg);
878 if (conn->xactStatus == PQTRANS_INTRANS)
879 conn->xactStatus = PQTRANS_INERROR;
883 if (res->noticeHooks.noticeRec != NULL)
884 (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
888 termPQExpBuffer(&workBuf);
894 termPQExpBuffer(&workBuf);
899 * checkXactStatus - attempt to track transaction-block status of server
901 * This is called each time we receive a command-complete message. By
902 * watching for messages from BEGIN/COMMIT/ROLLBACK commands, we can do
903 * a passable job of tracking the server's xact status. BUT: this does
904 * not work at all on 7.3 servers with AUTOCOMMIT OFF. (Man, was that
905 * feature ever a mistake.) Caveat user.
907 * The tags known here are all those used as far back as 7.0; is it worth
908 * adding those from even-older servers?
911 checkXactStatus(PGconn *conn, const char *cmdTag)
913 if (strcmp(cmdTag, "BEGIN") == 0)
914 conn->xactStatus = PQTRANS_INTRANS;
915 else if (strcmp(cmdTag, "COMMIT") == 0)
916 conn->xactStatus = PQTRANS_IDLE;
917 else if (strcmp(cmdTag, "ROLLBACK") == 0)
918 conn->xactStatus = PQTRANS_IDLE;
919 else if (strcmp(cmdTag, "START TRANSACTION") == 0) /* 7.3 only */
920 conn->xactStatus = PQTRANS_INTRANS;
923 * Normally we get into INERROR state by detecting an Error message.
924 * However, if we see one of these tags then we know for sure the server
925 * is in abort state ...
927 else if (strcmp(cmdTag, "*ABORT STATE*") == 0) /* pre-7.3 only */
928 conn->xactStatus = PQTRANS_INERROR;
932 * Attempt to read a Notify response message.
933 * This is possible in several places, so we break it out as a subroutine.
934 * Entry: 'A' message type and length have already been consumed.
935 * Exit: returns 0 if successfully consumed Notify message.
936 * returns EOF if not enough data.
939 getNotify(PGconn *conn)
945 if (pqGetInt(&be_pid, 4, conn))
947 if (pqGets(&conn->workBuffer, conn))
951 * Store the relation name right after the PQnotify structure so it can
952 * all be freed at once. We don't use NAMEDATALEN because we don't want
953 * to tie this interface to a specific server name length.
955 nmlen = strlen(conn->workBuffer.data);
956 newNotify = (PGnotify *) malloc(sizeof(PGnotify) + nmlen + 1);
959 newNotify->relname = (char *) newNotify + sizeof(PGnotify);
960 strcpy(newNotify->relname, conn->workBuffer.data);
961 /* fake up an empty-string extra field */
962 newNotify->extra = newNotify->relname + nmlen;
963 newNotify->be_pid = be_pid;
964 newNotify->next = NULL;
965 if (conn->notifyTail)
966 conn->notifyTail->next = newNotify;
968 conn->notifyHead = newNotify;
969 conn->notifyTail = newNotify;
977 * PQgetCopyData - read a row of data from the backend during COPY OUT
979 * If successful, sets *buffer to point to a malloc'd row of data, and
980 * returns row length (always > 0) as result.
981 * Returns 0 if no row available yet (only possible if async is true),
982 * -1 if end of copy (consult PQgetResult), or -2 if error (consult
986 pqGetCopyData2(PGconn *conn, char **buffer, int async)
994 * Do we have a complete line of data?
996 conn->inCursor = conn->inStart;
998 while (conn->inCursor < conn->inEnd)
1000 char c = conn->inBuffer[conn->inCursor++];
1010 msgLength = conn->inCursor - conn->inStart;
1013 * If it's the end-of-data marker, consume it, exit COPY_OUT mode, and
1014 * let caller read status with PQgetResult().
1016 if (msgLength == 3 &&
1017 strncmp(&conn->inBuffer[conn->inStart], "\\.\n", 3) == 0)
1019 conn->inStart = conn->inCursor;
1020 conn->asyncStatus = PGASYNC_BUSY;
1025 * Pass the line back to the caller.
1027 *buffer = (char *) malloc(msgLength + 1);
1028 if (*buffer == NULL)
1030 printfPQExpBuffer(&conn->errorMessage,
1031 libpq_gettext("out of memory\n"));
1034 memcpy(*buffer, &conn->inBuffer[conn->inStart], msgLength);
1035 (*buffer)[msgLength] = '\0'; /* Add terminating null */
1037 /* Mark message consumed */
1038 conn->inStart = conn->inCursor;
1043 /* Don't block if async read requested */
1046 /* Need to load more data */
1047 if (pqWait(TRUE, FALSE, conn) ||
1048 pqReadData(conn) < 0)
1055 * PQgetline - gets a newline-terminated string from the backend.
1057 * See fe-exec.c for documentation.
1060 pqGetline2(PGconn *conn, char *s, int maxlen)
1062 int result = 1; /* return value if buffer overflows */
1071 * Since this is a purely synchronous routine, we don't bother to maintain
1072 * conn->inCursor; there is no need to back up.
1076 if (conn->inStart < conn->inEnd)
1078 char c = conn->inBuffer[conn->inStart++];
1082 result = 0; /* success exit */
1090 /* need to load more data */
1091 if (pqWait(TRUE, FALSE, conn) ||
1092 pqReadData(conn) < 0)
1105 * PQgetlineAsync - gets a COPY data row without blocking.
1107 * See fe-exec.c for documentation.
1110 pqGetlineAsync2(PGconn *conn, char *buffer, int bufsize)
1114 if (conn->asyncStatus != PGASYNC_COPY_OUT)
1115 return -1; /* we are not doing a copy... */
1118 * Move data from libpq's buffer to the caller's. We want to accept data
1119 * only in units of whole lines, not partial lines. This ensures that we
1120 * can recognize the terminator line "\\.\n". (Otherwise, if it happened
1121 * to cross a packet/buffer boundary, we might hand the first one or two
1122 * characters off to the caller, which we shouldn't.)
1125 conn->inCursor = conn->inStart;
1128 while (avail > 0 && conn->inCursor < conn->inEnd)
1130 char c = conn->inBuffer[conn->inCursor++];
1136 /* Got a complete line; mark the data removed from libpq */
1137 conn->inStart = conn->inCursor;
1138 /* Is it the endmarker line? */
1139 if (bufsize - avail == 3 && buffer[-3] == '\\' && buffer[-2] == '.')
1141 /* No, return the data line to the caller */
1142 return bufsize - avail;
1147 * We don't have a complete line. We'd prefer to leave it in libpq's
1148 * buffer until the rest arrives, but there is a special case: what if the
1149 * line is longer than the buffer the caller is offering us? In that case
1150 * we'd better hand over a partial line, else we'd get into an infinite
1151 * loop. Do this in a way that ensures we can't misrecognize a terminator
1152 * line later: leave last 3 characters in libpq buffer.
1154 if (avail == 0 && bufsize > 3)
1156 conn->inStart = conn->inCursor - 3;
1165 * See fe-exec.c for documentation.
1168 pqEndcopy2(PGconn *conn)
1172 if (conn->asyncStatus != PGASYNC_COPY_IN &&
1173 conn->asyncStatus != PGASYNC_COPY_OUT)
1175 printfPQExpBuffer(&conn->errorMessage,
1176 libpq_gettext("no COPY in progress\n"));
1181 * make sure no data is waiting to be sent, abort if we are non-blocking
1182 * and the flush fails
1184 if (pqFlush(conn) && pqIsnonblocking(conn))
1187 /* non blocking connections may have to abort at this point. */
1188 if (pqIsnonblocking(conn) && PQisBusy(conn))
1191 /* Return to active duty */
1192 conn->asyncStatus = PGASYNC_BUSY;
1193 resetPQExpBuffer(&conn->errorMessage);
1195 /* Wait for the completion response */
1196 result = PQgetResult(conn);
1198 /* Expecting a successful result */
1199 if (result && result->resultStatus == PGRES_COMMAND_OK)
1206 * Trouble. For backwards-compatibility reasons, we issue the error
1207 * message as if it were a notice (would be nice to get rid of this
1208 * silliness, but too many apps probably don't handle errors from
1209 * PQendcopy reasonably). Note that the app can still obtain the error
1210 * status from the PGconn object.
1212 if (conn->errorMessage.len > 0)
1214 /* We have to strip the trailing newline ... pain in neck... */
1215 char svLast = conn->errorMessage.data[conn->errorMessage.len - 1];
1218 conn->errorMessage.data[conn->errorMessage.len - 1] = '\0';
1219 pqInternalNotice(&conn->noticeHooks, "%s", conn->errorMessage.data);
1220 conn->errorMessage.data[conn->errorMessage.len - 1] = svLast;
1226 * The worst case is that we've lost sync with the backend entirely due to
1227 * application screwup of the copy in/out protocol. To recover, reset the
1228 * connection (talk about using a sledgehammer...)
1230 pqInternalNotice(&conn->noticeHooks,
1231 "lost synchronization with server, resetting connection");
1234 * Users doing non-blocking connections need to handle the reset
1235 * themselves, they'll need to check the connection status if we return an
1238 if (pqIsnonblocking(conn))
1248 * PQfn - Send a function call to the POSTGRES backend.
1250 * See fe-exec.c for documentation.
1253 pqFunctionCall2(PGconn *conn, Oid fnid,
1254 int *result_buf, int *actual_result_len,
1256 const PQArgBlock *args, int nargs)
1258 bool needInput = false;
1259 ExecStatusType status = PGRES_FATAL_ERROR;
1263 /* PQfn already validated connection state */
1265 if (pqPutMsgStart('F', false, conn) < 0 || /* function call msg */
1266 pqPuts(" ", conn) < 0 || /* dummy string */
1267 pqPutInt(fnid, 4, conn) != 0 || /* function id */
1268 pqPutInt(nargs, 4, conn) != 0) /* # of args */
1270 pqHandleSendFailure(conn);
1274 for (i = 0; i < nargs; ++i)
1275 { /* len.int4 + contents */
1276 if (pqPutInt(args[i].len, 4, conn))
1278 pqHandleSendFailure(conn);
1284 if (pqPutInt(args[i].u.integer, 4, conn))
1286 pqHandleSendFailure(conn);
1292 if (pqPutnchar((char *) args[i].u.ptr, args[i].len, conn))
1294 pqHandleSendFailure(conn);
1300 if (pqPutMsgEnd(conn) < 0 ||
1303 pqHandleSendFailure(conn);
1311 /* Wait for some data to arrive (or for the channel to close) */
1312 if (pqWait(TRUE, FALSE, conn) ||
1313 pqReadData(conn) < 0)
1318 * Scan the message. If we run out of data, loop around to try again.
1320 conn->inCursor = conn->inStart;
1323 if (pqGetc(&id, conn))
1327 * We should see V or E response to the command, but might get N
1328 * and/or A notices first. We also need to swallow the final Z before
1333 case 'V': /* function result */
1334 if (pqGetc(&id, conn))
1338 /* function returned nonempty value */
1339 if (pqGetInt(actual_result_len, 4, conn))
1343 if (pqGetInt(result_buf, 4, conn))
1348 if (pqGetnchar((char *) result_buf,
1353 if (pqGetc(&id, conn)) /* get the last '0' */
1358 /* correctly finished function result message */
1359 status = PGRES_COMMAND_OK;
1363 /* The backend violates the protocol. */
1364 printfPQExpBuffer(&conn->errorMessage,
1365 libpq_gettext("protocol error: id=0x%x\n"),
1367 pqSaveErrorResult(conn);
1368 conn->inStart = conn->inCursor;
1369 return pqPrepareAsyncResult(conn);
1372 case 'E': /* error return */
1373 if (pqGetErrorNotice2(conn, true))
1375 status = PGRES_FATAL_ERROR;
1377 case 'A': /* notify message */
1378 /* handle notify and go back to processing return values */
1379 if (getNotify(conn))
1382 case 'N': /* notice */
1383 /* handle notice and go back to processing return values */
1384 if (pqGetErrorNotice2(conn, false))
1387 case 'Z': /* backend is ready for new query */
1388 /* consume the message and exit */
1389 conn->inStart = conn->inCursor;
1390 /* if we saved a result object (probably an error), use it */
1392 return pqPrepareAsyncResult(conn);
1393 return PQmakeEmptyPGresult(conn, status);
1395 /* The backend violates the protocol. */
1396 printfPQExpBuffer(&conn->errorMessage,
1397 libpq_gettext("protocol error: id=0x%x\n"),
1399 pqSaveErrorResult(conn);
1400 conn->inStart = conn->inCursor;
1401 return pqPrepareAsyncResult(conn);
1403 /* Completed this message, keep going */
1404 conn->inStart = conn->inCursor;
1409 * We fall out of the loop only upon failing to read data.
1410 * conn->errorMessage has been set by pqWait or pqReadData. We want to
1411 * append it to any already-received error message.
1413 pqSaveErrorResult(conn);
1414 return pqPrepareAsyncResult(conn);
1419 * Construct startup packet
1421 * Returns a malloc'd packet buffer, or NULL if out of memory
1424 pqBuildStartupPacket2(PGconn *conn, int *packetlen,
1425 const PQEnvironmentOption *options)
1427 StartupPacket *startpacket;
1429 *packetlen = sizeof(StartupPacket);
1430 startpacket = (StartupPacket *) malloc(sizeof(StartupPacket));
1434 MemSet(startpacket, 0, sizeof(StartupPacket));
1436 startpacket->protoVersion = htonl(conn->pversion);
1438 strncpy(startpacket->user, conn->pguser, SM_USER);
1439 strncpy(startpacket->database, conn->dbName, SM_DATABASE);
1440 strncpy(startpacket->tty, conn->pgtty, SM_TTY);
1442 if (conn->pgoptions)
1443 strncpy(startpacket->options, conn->pgoptions, SM_OPTIONS);
1445 return (char *) startpacket;