1 /*-------------------------------------------------------------------------
4 * functions that are specific to frontend/backend protocol version 2
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/interfaces/libpq/fe-protocol2.c,v 1.5 2003/08/04 00:43:33 momjian Exp $
13 *-------------------------------------------------------------------------
15 #include "postgres_fe.h"
22 #include "libpq-int.h"
24 #include "mb/pg_wchar.h"
30 #include <netinet/in.h>
31 #ifdef HAVE_NETINET_TCP_H
32 #include <netinet/tcp.h>
34 #include <arpa/inet.h>
38 static int getRowDescriptions(PGconn *conn);
39 static int getAnotherTuple(PGconn *conn, bool binary);
40 static int pqGetErrorNotice2(PGconn *conn, bool isError);
41 static void checkXactStatus(PGconn *conn, const char *cmdTag);
42 static int getNotify(PGconn *conn);
48 * Polls the process of passing the values of a standard set of environment
49 * variables to the backend.
51 PostgresPollingStatusType
52 pqSetenvPoll(PGconn *conn)
56 if (conn == NULL || conn->status == CONNECTION_BAD)
57 return PGRES_POLLING_FAILED;
59 /* Check whether there are any data for us */
60 switch (conn->setenv_state)
62 /* These are reading states */
63 case SETENV_STATE_OPTION_WAIT:
64 case SETENV_STATE_QUERY1_WAIT:
65 case SETENV_STATE_QUERY2_WAIT:
67 /* Load waiting data */
68 int n = pqReadData(conn);
73 return PGRES_POLLING_READING;
78 /* These are writing states, so we just proceed. */
79 case SETENV_STATE_OPTION_SEND:
80 case SETENV_STATE_QUERY1_SEND:
81 case SETENV_STATE_QUERY2_SEND:
84 /* Should we raise an error if called when not active? */
85 case SETENV_STATE_IDLE:
86 return PGRES_POLLING_OK;
89 printfPQExpBuffer(&conn->errorMessage,
91 "invalid setenv state %c, "
92 "probably indicative of memory corruption\n"
98 /* We will loop here until there is nothing left to do in this call. */
101 switch (conn->setenv_state)
103 case SETENV_STATE_OPTION_SEND:
106 * Send SET commands for stuff directed by Environment
107 * Options. Note: we assume that SET commands won't
108 * start transaction blocks, even in a 7.3 server with
111 char setQuery[100]; /* note length limit in
114 if (conn->next_eo->envName)
118 if ((val = getenv(conn->next_eo->envName)))
120 if (strcasecmp(val, "default") == 0)
121 sprintf(setQuery, "SET %s = DEFAULT",
122 conn->next_eo->pgName);
124 sprintf(setQuery, "SET %s = '%.60s'",
125 conn->next_eo->pgName, val);
128 "Use environment variable %s to send %s\n",
129 conn->next_eo->envName, setQuery);
131 if (!PQsendQuery(conn, setQuery))
134 conn->setenv_state = SETENV_STATE_OPTION_WAIT;
141 /* No more options to send, so move on to querying */
142 conn->setenv_state = SETENV_STATE_QUERY1_SEND;
147 case SETENV_STATE_OPTION_WAIT:
150 return PGRES_POLLING_READING;
152 res = PQgetResult(conn);
156 if (PQresultStatus(res) != PGRES_COMMAND_OK)
162 /* Keep reading until PQgetResult returns NULL */
166 /* Query finished, so send the next option */
168 conn->setenv_state = SETENV_STATE_OPTION_SEND;
173 case SETENV_STATE_QUERY1_SEND:
176 * Issue query to get information we need. Here we
177 * must use begin/commit in case autocommit is off by
178 * default in a 7.3 server.
180 * Note: version() and getdatabaseencoding() exist in all
181 * protocol-2.0-supporting backends.
183 if (!PQsendQuery(conn, "begin; select version(), getdatabaseencoding(); 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 database encoding,
217 * and save as if ParameterStatus
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
229 * result, naughty naughty)
231 ptr = strchr(val, ' ');
235 pqSaveParameterStatus(conn, "server_version",
239 val = PQgetvalue(res, 0, 1);
240 if (val && *val) /* null should not happen,
242 pqSaveParameterStatus(conn, "server_encoding",
246 /* Keep reading until PQgetResult returns NULL */
250 /* Query finished, move to next */
251 conn->setenv_state = SETENV_STATE_QUERY2_SEND;
256 case SETENV_STATE_QUERY2_SEND:
261 * pg_client_encoding does not exist in pre-7.2
262 * servers. So we need to be prepared for an error
263 * here. Do *not* start a transaction block, except
264 * in 7.3 servers where we need to prevent
265 * autocommit-off from starting a transaction anyway.
267 if (strncmp(conn->sversion, "7.3", 3) == 0)
268 query = "begin; select pg_client_encoding(); end";
270 query = "select pg_client_encoding()";
271 if (!PQsendQuery(conn, query))
274 conn->setenv_state = SETENV_STATE_QUERY2_WAIT;
275 return PGRES_POLLING_READING;
278 case SETENV_STATE_QUERY2_WAIT:
281 return PGRES_POLLING_READING;
283 res = PQgetResult(conn);
289 if (PQresultStatus(res) == PGRES_COMMAND_OK)
291 /* ignore begin/commit command results */
296 if (PQresultStatus(res) == PGRES_TUPLES_OK &&
299 /* Extract client encoding and save it */
300 val = PQgetvalue(res, 0, 0);
301 if (val && *val) /* null should not happen,
303 pqSaveParameterStatus(conn, "client_encoding",
309 * Error: presumably function not available,
310 * so use PGCLIENTENCODING or database
311 * encoding as the fallback.
313 val = getenv("PGCLIENTENCODING");
315 pqSaveParameterStatus(conn, "client_encoding",
319 val = PQparameterStatus(conn, "server_encoding");
321 pqSaveParameterStatus(conn, "client_encoding",
327 /* Keep reading until PQgetResult returns NULL */
331 /* Query finished, so we're done */
332 conn->setenv_state = SETENV_STATE_IDLE;
333 return PGRES_POLLING_OK;
339 printfPQExpBuffer(&conn->errorMessage,
340 libpq_gettext("invalid state %c, "
341 "probably indicative of memory corruption\n"),
350 conn->setenv_state = SETENV_STATE_IDLE;
351 return PGRES_POLLING_FAILED;
356 * parseInput: if appropriate, parse input data from backend
357 * until input is exhausted or a stopping state is reached.
358 * Note that this function will NOT attempt to read more data from the backend.
361 pqParseInput2(PGconn *conn)
366 * Loop to parse successive complete messages available in the buffer.
371 * Quit if in COPY_OUT state: we expect raw data from the server
372 * until PQendcopy is called. Don't try to parse it according to
373 * the normal protocol. (This is bogus. The data lines ought to
374 * be part of the protocol and have identifying leading
377 if (conn->asyncStatus == PGASYNC_COPY_OUT)
381 * OK to try to read a message type code.
383 conn->inCursor = conn->inStart;
384 if (pqGetc(&id, conn))
388 * NOTIFY and NOTICE messages can happen in any state besides COPY
389 * OUT; always process them right away.
391 * Most other messages should only be processed while in BUSY state.
392 * (In particular, in READY state we hold off further parsing
393 * until the application collects the current PGresult.)
395 * However, if the state is IDLE then we got trouble; we need to deal
396 * with the unexpected message somehow.
405 if (pqGetErrorNotice2(conn, false))
408 else if (conn->asyncStatus != PGASYNC_BUSY)
410 /* If not IDLE state, just wait ... */
411 if (conn->asyncStatus != PGASYNC_IDLE)
415 * Unexpected message in IDLE state; need to recover somehow.
416 * ERROR messages are displayed using the notice processor;
417 * anything else is just dropped on the floor after displaying
418 * a suitable warning notice. (An ERROR is very possibly the
419 * backend telling us why it is about to close the connection,
420 * so we don't want to just discard it...)
424 if (pqGetErrorNotice2(conn, false /* treat as notice */ ))
429 pqInternalNotice(&conn->noticeHooks,
430 "message type 0x%02x arrived from server while idle",
432 /* Discard the unexpected message; good idea?? */
433 conn->inStart = conn->inEnd;
440 * In BUSY state, we can process everything.
444 case 'C': /* command complete */
445 if (pqGets(&conn->workBuffer, conn))
447 if (conn->result == NULL)
448 conn->result = PQmakeEmptyPGresult(conn,
450 strncpy(conn->result->cmdStatus, conn->workBuffer.data,
452 checkXactStatus(conn, conn->workBuffer.data);
453 conn->asyncStatus = PGASYNC_READY;
455 case 'E': /* error return */
456 if (pqGetErrorNotice2(conn, true))
458 conn->asyncStatus = PGASYNC_READY;
460 case 'Z': /* backend is ready for new query */
461 conn->asyncStatus = PGASYNC_IDLE;
463 case 'I': /* empty query */
464 /* read and throw away the closing '\0' */
465 if (pqGetc(&id, conn))
468 pqInternalNotice(&conn->noticeHooks,
469 "unexpected character %c following empty query response (\"I\" message)",
471 if (conn->result == NULL)
472 conn->result = PQmakeEmptyPGresult(conn,
474 conn->asyncStatus = PGASYNC_READY;
476 case 'K': /* secret key data from the backend */
479 * This is expected only during backend startup, but
480 * it's just as easy to handle it as part of the main
481 * loop. Save the data and continue processing.
483 if (pqGetInt(&(conn->be_pid), 4, conn))
485 if (pqGetInt(&(conn->be_key), 4, conn))
488 case 'P': /* synchronous (normal) portal */
489 if (pqGets(&conn->workBuffer, conn))
491 /* We pretty much ignore this message type... */
493 case 'T': /* row descriptions (start of query
495 if (conn->result == NULL)
497 /* First 'T' in a query sequence */
498 if (getRowDescriptions(conn))
504 * A new 'T' message is treated as the start of
505 * another PGresult. (It is not clear that this
506 * is really possible with the current backend.)
507 * We stop parsing until the application accepts
508 * the current result.
510 conn->asyncStatus = PGASYNC_READY;
514 case 'D': /* ASCII data tuple */
515 if (conn->result != NULL)
517 /* Read another tuple of a normal query response */
518 if (getAnotherTuple(conn, FALSE))
523 pqInternalNotice(&conn->noticeHooks,
524 "server sent data (\"D\" message) without prior row description (\"T\" message)");
525 /* Discard the unexpected message; good idea?? */
526 conn->inStart = conn->inEnd;
530 case 'B': /* Binary data tuple */
531 if (conn->result != NULL)
533 /* Read another tuple of a normal query response */
534 if (getAnotherTuple(conn, TRUE))
539 pqInternalNotice(&conn->noticeHooks,
540 "server sent binary data (\"B\" message) without prior row description (\"T\" message)");
541 /* Discard the unexpected message; good idea?? */
542 conn->inStart = conn->inEnd;
546 case 'G': /* Start Copy In */
547 conn->asyncStatus = PGASYNC_COPY_IN;
549 case 'H': /* Start Copy Out */
550 conn->asyncStatus = PGASYNC_COPY_OUT;
553 printfPQExpBuffer(&conn->errorMessage,
555 "unexpected response from server; first received character was \"%c\"\n"),
557 /* build an error result holding the error message */
558 pqSaveErrorResult(conn);
559 /* Discard the unexpected message; good idea?? */
560 conn->inStart = conn->inEnd;
561 conn->asyncStatus = PGASYNC_READY;
563 } /* switch on protocol character */
565 /* Successfully consumed this message */
566 conn->inStart = conn->inCursor;
571 * parseInput subroutine to read a 'T' (row descriptions) message.
572 * We build a PGresult structure containing the attribute data.
573 * Returns: 0 if completed message, EOF if not enough data yet.
575 * Note that if we run out of data, we have to release the partially
576 * constructed PGresult, and rebuild it again next time. Fortunately,
577 * that shouldn't happen often, since 'T' messages usually fit in a packet.
580 getRowDescriptions(PGconn *conn)
586 result = PQmakeEmptyPGresult(conn, PGRES_TUPLES_OK);
588 /* parseInput already read the 'T' label. */
589 /* the next two bytes are the number of fields */
590 if (pqGetInt(&(result->numAttributes), 2, conn))
595 nfields = result->numAttributes;
597 /* allocate space for the attribute descriptors */
600 result->attDescs = (PGresAttDesc *)
601 pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
602 MemSet((char *) result->attDescs, 0, nfields * sizeof(PGresAttDesc));
606 for (i = 0; i < nfields; i++)
612 if (pqGets(&conn->workBuffer, conn) ||
613 pqGetInt(&typid, 4, conn) ||
614 pqGetInt(&typlen, 2, conn) ||
615 pqGetInt(&atttypmod, 4, conn))
622 * Since pqGetInt treats 2-byte integers as unsigned, we need to
623 * coerce the result to signed form.
625 typlen = (int) ((int16) typlen);
627 result->attDescs[i].name = pqResultStrdup(result,
628 conn->workBuffer.data);
629 result->attDescs[i].tableid = 0;
630 result->attDescs[i].columnid = 0;
631 result->attDescs[i].format = 0;
632 result->attDescs[i].typid = typid;
633 result->attDescs[i].typlen = typlen;
634 result->attDescs[i].atttypmod = atttypmod;
638 conn->result = result;
643 * parseInput subroutine to read a 'B' or 'D' (row data) message.
644 * We add another tuple to the existing PGresult structure.
645 * Returns: 0 if completed message, EOF if error or not enough data yet.
647 * Note that if we run out of data, we have to suspend and reprocess
648 * the message after more data is received. We keep a partially constructed
649 * tuple in conn->curTuple, and avoid reallocating already-allocated storage.
652 getAnotherTuple(PGconn *conn, bool binary)
654 PGresult *result = conn->result;
655 int nfields = result->numAttributes;
658 /* the backend sends us a bitmap of which attributes are null */
659 char std_bitmap[64]; /* used unless it doesn't fit */
660 char *bitmap = std_bitmap;
662 size_t nbytes; /* the number of bytes in bitmap */
663 char bmap; /* One byte of the bitmap */
664 int bitmap_index; /* Its index */
665 int bitcnt; /* number of bits examined in current byte */
666 int vlen; /* length of the current field value */
668 result->binary = binary;
670 /* Allocate tuple space if first time for this data message */
671 if (conn->curTuple == NULL)
673 conn->curTuple = (PGresAttValue *)
674 pqResultAlloc(result, nfields * sizeof(PGresAttValue), TRUE);
675 if (conn->curTuple == NULL)
677 MemSet((char *) conn->curTuple, 0, nfields * sizeof(PGresAttValue));
680 * If it's binary, fix the column format indicators. We assume
681 * the backend will consistently send either B or D, not a mix.
685 for (i = 0; i < nfields; i++)
686 result->attDescs[i].format = 1;
689 tup = conn->curTuple;
691 /* Get the null-value bitmap */
692 nbytes = (nfields + BITS_PER_BYTE - 1) / BITS_PER_BYTE;
693 /* malloc() only for unusually large field counts... */
694 if (nbytes > sizeof(std_bitmap))
695 bitmap = (char *) malloc(nbytes);
697 if (pqGetnchar(bitmap, nbytes, conn))
700 /* Scan the fields */
702 bmap = bitmap[bitmap_index];
705 for (i = 0; i < nfields; i++)
709 /* if the field value is absent, make it a null string */
710 tup[i].value = result->null_field;
711 tup[i].len = NULL_LEN;
715 /* get the value length (the first four bytes are for length) */
716 if (pqGetInt(&vlen, 4, conn))
722 if (tup[i].value == NULL)
724 tup[i].value = (char *) pqResultAlloc(result, vlen + 1, binary);
725 if (tup[i].value == NULL)
729 /* read in the value */
731 if (pqGetnchar((char *) (tup[i].value), vlen, conn))
733 /* we have to terminate this ourselves */
734 tup[i].value[vlen] = '\0';
736 /* advance the bitmap stuff */
738 if (bitcnt == BITS_PER_BYTE)
741 bmap = bitmap[bitmap_index];
748 /* Success! Store the completed tuple in the result */
749 if (!pqAddTuple(result, tup))
751 /* and reset for a new message */
752 conn->curTuple = NULL;
754 if (bitmap != std_bitmap)
759 /* Replace partially constructed result with an error result */
762 * we do NOT use pqSaveErrorResult() here, because of the likelihood
763 * that there's not enough memory to concatenate messages...
765 pqClearAsyncResult(conn);
766 printfPQExpBuffer(&conn->errorMessage,
767 libpq_gettext("out of memory for query result\n"));
768 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
769 conn->asyncStatus = PGASYNC_READY;
770 /* Discard the failed message --- good idea? */
771 conn->inStart = conn->inEnd;
774 if (bitmap != std_bitmap)
781 * Attempt to read an Error or Notice response message.
782 * This is possible in several places, so we break it out as a subroutine.
783 * Entry: 'E' or 'N' message type has already been consumed.
784 * Exit: returns 0 if successfully consumed message.
785 * returns EOF if not enough data.
788 pqGetErrorNotice2(PGconn *conn, bool isError)
791 PQExpBufferData workBuf;
796 * Since the message might be pretty long, we create a temporary
797 * PQExpBuffer rather than using conn->workBuffer. workBuffer is
798 * intended for stuff that is expected to be short.
800 initPQExpBuffer(&workBuf);
801 if (pqGets(&workBuf, conn))
803 termPQExpBuffer(&workBuf);
808 * Make a PGresult to hold the message. We temporarily lie about the
809 * result status, so that PQmakeEmptyPGresult doesn't uselessly copy
810 * conn->errorMessage.
812 res = PQmakeEmptyPGresult(conn, PGRES_EMPTY_QUERY);
813 res->resultStatus = isError ? PGRES_FATAL_ERROR : PGRES_NONFATAL_ERROR;
814 res->errMsg = pqResultStrdup(res, workBuf.data);
817 * Break the message into fields. We can't do very much here, but we
818 * can split the severity code off, and remove trailing newlines.
819 * Also, we use the heuristic that the primary message extends only to
820 * the first newline --- anything after that is detail message. (In
821 * some cases it'd be better classed as hint, but we can hardly be
822 * expected to guess that here.)
824 while (workBuf.len > 0 && workBuf.data[workBuf.len - 1] == '\n')
825 workBuf.data[--workBuf.len] = '\0';
826 splitp = strstr(workBuf.data, ": ");
829 /* what comes before the colon is severity */
831 pqSaveMessageField(res, 'S', workBuf.data);
836 /* can't find a colon? oh well... */
837 startp = workBuf.data;
839 splitp = strchr(startp, '\n');
842 /* what comes before the newline is primary message */
844 pqSaveMessageField(res, 'M', startp);
845 /* the rest is detail; strip any leading whitespace */
846 while (*splitp && isspace((unsigned char) *splitp))
848 pqSaveMessageField(res, 'D', splitp);
852 /* single-line message, so all primary */
853 pqSaveMessageField(res, 'M', startp);
857 * Either save error as current async result, or just emit the notice.
858 * Also, if it's an error and we were in a transaction block, assume
859 * the server has now gone to error-in-transaction state.
863 pqClearAsyncResult(conn);
865 resetPQExpBuffer(&conn->errorMessage);
866 appendPQExpBufferStr(&conn->errorMessage, res->errMsg);
867 if (conn->xactStatus == PQTRANS_INTRANS)
868 conn->xactStatus = PQTRANS_INERROR;
872 if (res->noticeHooks.noticeRec != NULL)
873 (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
877 termPQExpBuffer(&workBuf);
882 * checkXactStatus - attempt to track transaction-block status of server
884 * This is called each time we receive a command-complete message. By
885 * watching for messages from BEGIN/COMMIT/ROLLBACK commands, we can do
886 * a passable job of tracking the server's xact status. BUT: this does
887 * not work at all on 7.3 servers with AUTOCOMMIT OFF. (Man, was that
888 * feature ever a mistake.) Caveat user.
890 * The tags known here are all those used as far back as 7.0; is it worth
891 * adding those from even-older servers?
894 checkXactStatus(PGconn *conn, const char *cmdTag)
896 if (strcmp(cmdTag, "BEGIN") == 0)
897 conn->xactStatus = PQTRANS_INTRANS;
898 else if (strcmp(cmdTag, "COMMIT") == 0)
899 conn->xactStatus = PQTRANS_IDLE;
900 else if (strcmp(cmdTag, "ROLLBACK") == 0)
901 conn->xactStatus = PQTRANS_IDLE;
902 else if (strcmp(cmdTag, "START TRANSACTION") == 0) /* 7.3 only */
903 conn->xactStatus = PQTRANS_INTRANS;
906 * Normally we get into INERROR state by detecting an Error message.
907 * However, if we see one of these tags then we know for sure the
908 * server is in abort state ...
910 else if (strcmp(cmdTag, "*ABORT STATE*") == 0) /* pre-7.3 only */
911 conn->xactStatus = PQTRANS_INERROR;
915 * Attempt to read a Notify response message.
916 * This is possible in several places, so we break it out as a subroutine.
917 * Entry: 'A' message type and length have already been consumed.
918 * Exit: returns 0 if successfully consumed Notify message.
919 * returns EOF if not enough data.
922 getNotify(PGconn *conn)
928 if (pqGetInt(&be_pid, 4, conn))
930 if (pqGets(&conn->workBuffer, conn))
934 * Store the relation name right after the PQnotify structure so it
935 * can all be freed at once. We don't use NAMEDATALEN because we
936 * don't want to tie this interface to a specific server name length.
938 nmlen = strlen(conn->workBuffer.data);
939 newNotify = (PGnotify *) malloc(sizeof(PGnotify) + nmlen + 1);
942 newNotify->relname = (char *) newNotify + sizeof(PGnotify);
943 strcpy(newNotify->relname, conn->workBuffer.data);
944 /* fake up an empty-string extra field */
945 newNotify->extra = newNotify->relname + nmlen;
946 newNotify->be_pid = be_pid;
947 DLAddTail(conn->notifyList, DLNewElem(newNotify));
955 * PQgetCopyData - read a row of data from the backend during COPY OUT
957 * If successful, sets *buffer to point to a malloc'd row of data, and
958 * returns row length (always > 0) as result.
959 * Returns 0 if no row available yet (only possible if async is true),
960 * -1 if end of copy (consult PQgetResult), or -2 if error (consult
964 pqGetCopyData2(PGconn *conn, char **buffer, int async)
972 * Do we have a complete line of data?
974 conn->inCursor = conn->inStart;
976 while (conn->inCursor < conn->inEnd)
978 char c = conn->inBuffer[conn->inCursor++];
988 msgLength = conn->inCursor - conn->inStart;
991 * If it's the end-of-data marker, consume it, exit COPY_OUT mode,
992 * and let caller read status with PQgetResult().
994 if (msgLength == 3 &&
995 strncmp(&conn->inBuffer[conn->inStart], "\\.\n", 3) == 0)
997 conn->inStart = conn->inCursor;
998 conn->asyncStatus = PGASYNC_BUSY;
1003 * Pass the line back to the caller.
1005 *buffer = (char *) malloc(msgLength + 1);
1006 if (*buffer == NULL)
1008 printfPQExpBuffer(&conn->errorMessage,
1009 libpq_gettext("out of memory\n"));
1012 memcpy(*buffer, &conn->inBuffer[conn->inStart], msgLength);
1013 (*buffer)[msgLength] = '\0'; /* Add terminating null */
1015 /* Mark message consumed */
1016 conn->inStart = conn->inCursor;
1021 /* Don't block if async read requested */
1024 /* Need to load more data */
1025 if (pqWait(TRUE, FALSE, conn) ||
1026 pqReadData(conn) < 0)
1033 * PQgetline - gets a newline-terminated string from the backend.
1035 * See fe-exec.c for documentation.
1038 pqGetline2(PGconn *conn, char *s, int maxlen)
1040 int result = 1; /* return value if buffer overflows */
1049 * Since this is a purely synchronous routine, we don't bother to
1050 * maintain conn->inCursor; there is no need to back up.
1054 if (conn->inStart < conn->inEnd)
1056 char c = conn->inBuffer[conn->inStart++];
1060 result = 0; /* success exit */
1068 /* need to load more data */
1069 if (pqWait(TRUE, FALSE, conn) ||
1070 pqReadData(conn) < 0)
1083 * PQgetlineAsync - gets a COPY data row without blocking.
1085 * See fe-exec.c for documentation.
1088 pqGetlineAsync2(PGconn *conn, char *buffer, int bufsize)
1092 if (conn->asyncStatus != PGASYNC_COPY_OUT)
1093 return -1; /* we are not doing a copy... */
1096 * Move data from libpq's buffer to the caller's. We want to accept
1097 * data only in units of whole lines, not partial lines. This ensures
1098 * that we can recognize the terminator line "\\.\n". (Otherwise, if
1099 * it happened to cross a packet/buffer boundary, we might hand the
1100 * first one or two characters off to the caller, which we shouldn't.)
1103 conn->inCursor = conn->inStart;
1106 while (avail > 0 && conn->inCursor < conn->inEnd)
1108 char c = conn->inBuffer[conn->inCursor++];
1114 /* Got a complete line; mark the data removed from libpq */
1115 conn->inStart = conn->inCursor;
1116 /* Is it the endmarker line? */
1117 if (bufsize - avail == 3 && buffer[-3] == '\\' && buffer[-2] == '.')
1119 /* No, return the data line to the caller */
1120 return bufsize - avail;
1125 * We don't have a complete line. We'd prefer to leave it in libpq's
1126 * buffer until the rest arrives, but there is a special case: what if
1127 * the line is longer than the buffer the caller is offering us? In
1128 * that case we'd better hand over a partial line, else we'd get into
1129 * an infinite loop. Do this in a way that ensures we can't
1130 * misrecognize a terminator line later: leave last 3 characters in
1133 if (avail == 0 && bufsize > 3)
1135 conn->inStart = conn->inCursor - 3;
1144 * See fe-exec.c for documentation.
1147 pqEndcopy2(PGconn *conn)
1151 if (conn->asyncStatus != PGASYNC_COPY_IN &&
1152 conn->asyncStatus != PGASYNC_COPY_OUT)
1154 printfPQExpBuffer(&conn->errorMessage,
1155 libpq_gettext("no COPY in progress\n"));
1160 * make sure no data is waiting to be sent, abort if we are
1161 * non-blocking and the flush fails
1163 if (pqFlush(conn) && pqIsnonblocking(conn))
1166 /* non blocking connections may have to abort at this point. */
1167 if (pqIsnonblocking(conn) && PQisBusy(conn))
1170 /* Return to active duty */
1171 conn->asyncStatus = PGASYNC_BUSY;
1172 resetPQExpBuffer(&conn->errorMessage);
1174 /* Wait for the completion response */
1175 result = PQgetResult(conn);
1177 /* Expecting a successful result */
1178 if (result && result->resultStatus == PGRES_COMMAND_OK)
1185 * Trouble. For backwards-compatibility reasons, we issue the error
1186 * message as if it were a notice (would be nice to get rid of this
1187 * silliness, but too many apps probably don't handle errors from
1188 * PQendcopy reasonably). Note that the app can still obtain the
1189 * error status from the PGconn object.
1191 if (conn->errorMessage.len > 0)
1193 /* We have to strip the trailing newline ... pain in neck... */
1194 char svLast = conn->errorMessage.data[conn->errorMessage.len - 1];
1197 conn->errorMessage.data[conn->errorMessage.len - 1] = '\0';
1198 pqInternalNotice(&conn->noticeHooks, "%s", conn->errorMessage.data);
1199 conn->errorMessage.data[conn->errorMessage.len - 1] = svLast;
1205 * The worst case is that we've lost sync with the backend entirely
1206 * due to application screwup of the copy in/out protocol. To recover,
1207 * reset the connection (talk about using a sledgehammer...)
1209 pqInternalNotice(&conn->noticeHooks,
1210 "lost synchronization with server, resetting connection");
1213 * Users doing non-blocking connections need to handle the reset
1214 * themselves, they'll need to check the connection status if we
1217 if (pqIsnonblocking(conn))
1227 * PQfn - Send a function call to the POSTGRES backend.
1229 * See fe-exec.c for documentation.
1232 pqFunctionCall2(PGconn *conn, Oid fnid,
1233 int *result_buf, int *actual_result_len,
1235 const PQArgBlock *args, int nargs)
1237 bool needInput = false;
1238 ExecStatusType status = PGRES_FATAL_ERROR;
1242 /* PQfn already validated connection state */
1244 if (pqPutMsgStart('F', false, conn) < 0 || /* function call msg */
1245 pqPuts(" ", conn) < 0 || /* dummy string */
1246 pqPutInt(fnid, 4, conn) != 0 || /* function id */
1247 pqPutInt(nargs, 4, conn) != 0) /* # of args */
1249 pqHandleSendFailure(conn);
1253 for (i = 0; i < nargs; ++i)
1254 { /* len.int4 + contents */
1255 if (pqPutInt(args[i].len, 4, conn))
1257 pqHandleSendFailure(conn);
1263 if (pqPutInt(args[i].u.integer, 4, conn))
1265 pqHandleSendFailure(conn);
1271 if (pqPutnchar((char *) args[i].u.ptr, args[i].len, conn))
1273 pqHandleSendFailure(conn);
1279 if (pqPutMsgEnd(conn) < 0 ||
1282 pqHandleSendFailure(conn);
1290 /* Wait for some data to arrive (or for the channel to close) */
1291 if (pqWait(TRUE, FALSE, conn) ||
1292 pqReadData(conn) < 0)
1297 * Scan the message. If we run out of data, loop around to try
1300 conn->inCursor = conn->inStart;
1303 if (pqGetc(&id, conn))
1307 * We should see V or E response to the command, but might get N
1308 * and/or A notices first. We also need to swallow the final Z
1313 case 'V': /* function result */
1314 if (pqGetc(&id, conn))
1318 /* function returned nonempty value */
1319 if (pqGetInt(actual_result_len, 4, conn))
1323 if (pqGetInt(result_buf, 4, conn))
1328 if (pqGetnchar((char *) result_buf,
1333 if (pqGetc(&id, conn)) /* get the last '0' */
1338 /* correctly finished function result message */
1339 status = PGRES_COMMAND_OK;
1343 /* The backend violates the protocol. */
1344 printfPQExpBuffer(&conn->errorMessage,
1345 libpq_gettext("protocol error: id=0x%x\n"),
1347 pqSaveErrorResult(conn);
1348 conn->inStart = conn->inCursor;
1349 return pqPrepareAsyncResult(conn);
1352 case 'E': /* error return */
1353 if (pqGetErrorNotice2(conn, true))
1355 status = PGRES_FATAL_ERROR;
1357 case 'A': /* notify message */
1358 /* handle notify and go back to processing return values */
1359 if (getNotify(conn))
1362 case 'N': /* notice */
1363 /* handle notice and go back to processing return values */
1364 if (pqGetErrorNotice2(conn, false))
1367 case 'Z': /* backend is ready for new query */
1368 /* consume the message and exit */
1369 conn->inStart = conn->inCursor;
1370 /* if we saved a result object (probably an error), use it */
1372 return pqPrepareAsyncResult(conn);
1373 return PQmakeEmptyPGresult(conn, status);
1375 /* The backend violates the protocol. */
1376 printfPQExpBuffer(&conn->errorMessage,
1377 libpq_gettext("protocol error: id=0x%x\n"),
1379 pqSaveErrorResult(conn);
1380 conn->inStart = conn->inCursor;
1381 return pqPrepareAsyncResult(conn);
1383 /* Completed this message, keep going */
1384 conn->inStart = conn->inCursor;
1389 * We fall out of the loop only upon failing to read data.
1390 * conn->errorMessage has been set by pqWait or pqReadData. We want to
1391 * append it to any already-received error message.
1393 pqSaveErrorResult(conn);
1394 return pqPrepareAsyncResult(conn);
1399 * Construct startup packet
1401 * Returns a malloc'd packet buffer, or NULL if out of memory
1404 pqBuildStartupPacket2(PGconn *conn, int *packetlen,
1405 const PQEnvironmentOption * options)
1407 StartupPacket *startpacket;
1409 *packetlen = sizeof(StartupPacket);
1410 startpacket = (StartupPacket *) malloc(sizeof(StartupPacket));
1414 MemSet((char *) startpacket, 0, sizeof(StartupPacket));
1416 startpacket->protoVersion = htonl(conn->pversion);
1418 strncpy(startpacket->user, conn->pguser, SM_USER);
1419 strncpy(startpacket->database, conn->dbName, SM_DATABASE);
1420 strncpy(startpacket->tty, conn->pgtty, SM_TTY);
1422 if (conn->pgoptions)
1423 strncpy(startpacket->options, conn->pgoptions, SM_OPTIONS);
1425 return (char *) startpacket;