PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
fe-protocol3.c File Reference
#include "postgres_fe.h"
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
#include <netinet/tcp.h>
#include "libpq-fe.h"
#include "libpq-int.h"
#include "mb/pg_wchar.h"
#include "port/pg_bswap.h"
Include dependency graph for fe-protocol3.c:

Go to the source code of this file.

Macros

#define VALID_LONG_MESSAGE_TYPE(id)
 
#define DISPLAY_SIZE   60 /* screen width limit, in screen cols */
 
#define MIN_RIGHT_CUT   10 /* try to keep this far away from EOL */
 
#define ADD_STARTUP_OPTION(optname, optval)
 

Functions

static void handleSyncLoss (PGconn *conn, char id, int msgLength)
 
static int getRowDescriptions (PGconn *conn, int msgLength)
 
static int getParamDescriptions (PGconn *conn, int msgLength)
 
static int getAnotherTuple (PGconn *conn, int msgLength)
 
static int getParameterStatus (PGconn *conn)
 
static int getNotify (PGconn *conn)
 
static int getCopyStart (PGconn *conn, ExecStatusType copytype)
 
static int getReadyForQuery (PGconn *conn)
 
static void reportErrorPosition (PQExpBuffer msg, const char *query, int loc, int encoding)
 
static int build_startup_packet (const PGconn *conn, char *packet, const PQEnvironmentOption *options)
 
void pqParseInput3 (PGconn *conn)
 
int pqGetErrorNotice3 (PGconn *conn, bool isError)
 
void pqBuildErrorMessage3 (PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
 
int pqGetNegotiateProtocolVersion3 (PGconn *conn)
 
static int getCopyDataMessage (PGconn *conn)
 
int pqGetCopyData3 (PGconn *conn, char **buffer, int async)
 
int pqGetline3 (PGconn *conn, char *s, int maxlen)
 
int pqGetlineAsync3 (PGconn *conn, char *buffer, int bufsize)
 
int pqEndcopy3 (PGconn *conn)
 
PGresultpqFunctionCall3 (PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
 
char * pqBuildStartupPacket3 (PGconn *conn, int *packetlen, const PQEnvironmentOption *options)
 

Macro Definition Documentation

◆ ADD_STARTUP_OPTION

#define ADD_STARTUP_OPTION (   optname,
  optval 
)
Value:
do { \
if (packet) \
strcpy(packet + packet_len, optname); \
packet_len += strlen(optname) + 1; \
if (packet) \
strcpy(packet + packet_len, optval); \
packet_len += strlen(optval) + 1; \
} while(0)

◆ DISPLAY_SIZE

#define DISPLAY_SIZE   60 /* screen width limit, in screen cols */

◆ MIN_RIGHT_CUT

#define MIN_RIGHT_CUT   10 /* try to keep this far away from EOL */

◆ VALID_LONG_MESSAGE_TYPE

#define VALID_LONG_MESSAGE_TYPE (   id)
Value:
((id) == PqMsg_CopyData || \
(id) == PqMsg_DataRow || \
(id) == PqMsg_ErrorResponse || \
(id) == PqMsg_NoticeResponse || \
#define PqMsg_NotificationResponse
Definition: protocol.h:41
#define PqMsg_CopyData
Definition: protocol.h:65
#define PqMsg_FunctionCallResponse
Definition: protocol.h:53
#define PqMsg_RowDescription
Definition: protocol.h:52
#define PqMsg_ErrorResponse
Definition: protocol.h:44
#define PqMsg_DataRow
Definition: protocol.h:43
#define PqMsg_NoticeResponse
Definition: protocol.h:49

Definition at line 36 of file fe-protocol3.c.

Function Documentation

◆ build_startup_packet()

static int build_startup_packet ( const PGconn conn,
char *  packet,
const PQEnvironmentOption options 
)
static

Definition at line 2254 of file fe-protocol3.c.

2256{
2257 int packet_len = 0;
2258 const PQEnvironmentOption *next_eo;
2259 const char *val;
2260
2261 /* Protocol version comes first. */
2262 if (packet)
2263 {
2265
2266 memcpy(packet + packet_len, &pv, sizeof(ProtocolVersion));
2267 }
2268 packet_len += sizeof(ProtocolVersion);
2269
2270 /* Add user name, database name, options */
2271
2272#define ADD_STARTUP_OPTION(optname, optval) \
2273 do { \
2274 if (packet) \
2275 strcpy(packet + packet_len, optname); \
2276 packet_len += strlen(optname) + 1; \
2277 if (packet) \
2278 strcpy(packet + packet_len, optval); \
2279 packet_len += strlen(optval) + 1; \
2280 } while(0)
2281
2282 if (conn->pguser && conn->pguser[0])
2283 ADD_STARTUP_OPTION("user", conn->pguser);
2284 if (conn->dbName && conn->dbName[0])
2285 ADD_STARTUP_OPTION("database", conn->dbName);
2286 if (conn->replication && conn->replication[0])
2287 ADD_STARTUP_OPTION("replication", conn->replication);
2288 if (conn->pgoptions && conn->pgoptions[0])
2289 ADD_STARTUP_OPTION("options", conn->pgoptions);
2290 if (conn->send_appname)
2291 {
2292 /* Use appname if present, otherwise use fallback */
2294 if (val && val[0])
2295 ADD_STARTUP_OPTION("application_name", val);
2296 }
2297
2299 ADD_STARTUP_OPTION("client_encoding", conn->client_encoding_initial);
2300
2301 /* Add any environment-driven GUC settings needed */
2302 for (next_eo = options; next_eo->envName; next_eo++)
2303 {
2304 if ((val = getenv(next_eo->envName)) != NULL)
2305 {
2306 if (pg_strcasecmp(val, "default") != 0)
2307 ADD_STARTUP_OPTION(next_eo->pgName, val);
2308 }
2309 }
2310
2311 /* Add trailing terminator */
2312 if (packet)
2313 packet[packet_len] = '\0';
2314 packet_len++;
2315
2316 return packet_len;
2317}
#define ADD_STARTUP_OPTION(optname, optval)
long val
Definition: informix.c:689
#define pg_hton32(x)
Definition: pg_bswap.h:121
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
uint32 ProtocolVersion
Definition: pqcomm.h:100
PGconn * conn
Definition: streamutil.c:53
const char * pgName
Definition: libpq-int.h:273
const char * envName
Definition: libpq-int.h:272
char * replication
Definition: libpq-int.h:398
ProtocolVersion pversion
Definition: libpq-int.h:494
char * pgoptions
Definition: libpq-int.h:394
bool send_appname
Definition: libpq-int.h:524
char * dbName
Definition: libpq-int.h:397
char * fbappname
Definition: libpq-int.h:396
char * pguser
Definition: libpq-int.h:400
char * client_encoding_initial
Definition: libpq-int.h:393
char * appname
Definition: libpq-int.h:395

References ADD_STARTUP_OPTION, pg_conn::appname, pg_conn::client_encoding_initial, conn, pg_conn::dbName, PQEnvironmentOption::envName, pg_conn::fbappname, pg_hton32, pg_strcasecmp(), PQEnvironmentOption::pgName, pg_conn::pgoptions, pg_conn::pguser, pg_conn::pversion, pg_conn::replication, pg_conn::send_appname, and val.

Referenced by pqBuildStartupPacket3().

◆ getAnotherTuple()

static int getAnotherTuple ( PGconn conn,
int  msgLength 
)
static

Definition at line 758 of file fe-protocol3.c.

759{
760 PGresult *result = conn->result;
761 int nfields = result->numAttributes;
762 const char *errmsg;
763 PGdataValue *rowbuf;
764 int tupnfields; /* # fields from tuple */
765 int vlen; /* length of the current field value */
766 int i;
767
768 /* Get the field count and make sure it's what we expect */
769 if (pqGetInt(&tupnfields, 2, conn))
770 {
771 /* We should not run out of data here, so complain */
772 errmsg = libpq_gettext("insufficient data in \"D\" message");
773 goto advance_and_error;
774 }
775
776 if (tupnfields != nfields)
777 {
778 errmsg = libpq_gettext("unexpected field count in \"D\" message");
779 goto advance_and_error;
780 }
781
782 /* Resize row buffer if needed */
783 rowbuf = conn->rowBuf;
784 if (nfields > conn->rowBufLen)
785 {
786 rowbuf = (PGdataValue *) realloc(rowbuf,
787 nfields * sizeof(PGdataValue));
788 if (!rowbuf)
789 {
790 errmsg = NULL; /* means "out of memory", see below */
791 goto advance_and_error;
792 }
793 conn->rowBuf = rowbuf;
794 conn->rowBufLen = nfields;
795 }
796
797 /* Scan the fields */
798 for (i = 0; i < nfields; i++)
799 {
800 /* get the value length */
801 if (pqGetInt(&vlen, 4, conn))
802 {
803 /* We should not run out of data here, so complain */
804 errmsg = libpq_gettext("insufficient data in \"D\" message");
805 goto advance_and_error;
806 }
807 rowbuf[i].len = vlen;
808
809 /*
810 * rowbuf[i].value always points to the next address in the data
811 * buffer even if the value is NULL. This allows row processors to
812 * estimate data sizes more easily.
813 */
814 rowbuf[i].value = conn->inBuffer + conn->inCursor;
815
816 /* Skip over the data value */
817 if (vlen > 0)
818 {
819 if (pqSkipnchar(vlen, conn))
820 {
821 /* We should not run out of data here, so complain */
822 errmsg = libpq_gettext("insufficient data in \"D\" message");
823 goto advance_and_error;
824 }
825 }
826 }
827
828 /* Process the collected row */
829 errmsg = NULL;
831 return 0; /* normal, successful exit */
832
833 /* pqRowProcessor failed, fall through to report it */
834
835advance_and_error:
836
837 /*
838 * Replace partially constructed result with an error result. First
839 * discard the old result to try to win back some memory.
840 */
842
843 /*
844 * If preceding code didn't provide an error message, assume "out of
845 * memory" was meant. The advantage of having this special case is that
846 * freeing the old result first greatly improves the odds that gettext()
847 * will succeed in providing a translation.
848 */
849 if (!errmsg)
850 errmsg = libpq_gettext("out of memory for query result");
851
854
855 /*
856 * Show the message as fully consumed, else pqParseInput3 will overwrite
857 * our error with a complaint about that.
858 */
859 conn->inCursor = conn->inStart + 5 + msgLength;
860
861 /*
862 * Return zero to allow input parsing to continue. Subsequent "D"
863 * messages will be ignored until we get to end of data, since an error
864 * result is already set up.
865 */
866 return 0;
867}
int errmsg(const char *fmt,...)
Definition: elog.c:1070
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:803
int pqRowProcessor(PGconn *conn, const char **errmsgp)
Definition: fe-exec.c:1206
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:779
int pqSkipnchar(size_t len, PGconn *conn)
Definition: fe-misc.c:187
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:216
#define realloc(a, b)
Definition: header.h:60
int i
Definition: isn.c:72
#define libpq_gettext(x)
Definition: libpq-int.h:915
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
const char * value
Definition: libpq-int.h:311
PGdataValue * rowBuf
Definition: libpq-int.h:562
char * inBuffer
Definition: libpq-int.h:545
int inCursor
Definition: libpq-int.h:548
int inStart
Definition: libpq-int.h:547
PGresult * result
Definition: libpq-int.h:575
PQExpBufferData errorMessage
Definition: libpq-int.h:652
int rowBufLen
Definition: libpq-int.h:563
int numAttributes
Definition: libpq-int.h:175

References appendPQExpBuffer(), conn, errmsg(), pg_conn::errorMessage, i, pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inStart, pgDataValue::len, libpq_gettext, pg_result::numAttributes, pqClearAsyncResult(), pqGetInt(), pqRowProcessor(), pqSaveErrorResult(), pqSkipnchar(), realloc, pg_conn::result, pg_conn::rowBuf, pg_conn::rowBufLen, and pgDataValue::value.

Referenced by pqParseInput3().

◆ getCopyDataMessage()

static int getCopyDataMessage ( PGconn conn)
static

Definition at line 1638 of file fe-protocol3.c.

1639{
1640 char id;
1641 int msgLength;
1642 int avail;
1643
1644 for (;;)
1645 {
1646 /*
1647 * Do we have the next input message? To make life simpler for async
1648 * callers, we keep returning 0 until the next message is fully
1649 * available, even if it is not Copy Data.
1650 */
1652 if (pqGetc(&id, conn))
1653 return 0;
1654 if (pqGetInt(&msgLength, 4, conn))
1655 return 0;
1656 if (msgLength < 4)
1657 {
1658 handleSyncLoss(conn, id, msgLength);
1659 return -2;
1660 }
1661 avail = conn->inEnd - conn->inCursor;
1662 if (avail < msgLength - 4)
1663 {
1664 /*
1665 * Before returning, enlarge the input buffer if needed to hold
1666 * the whole message. See notes in parseInput.
1667 */
1668 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength - 4,
1669 conn))
1670 {
1671 /*
1672 * XXX add some better recovery code... plan is to skip over
1673 * the message using its length, then report an error. For the
1674 * moment, just treat this like loss of sync (which indeed it
1675 * might be!)
1676 */
1677 handleSyncLoss(conn, id, msgLength);
1678 return -2;
1679 }
1680 return 0;
1681 }
1682
1683 /*
1684 * If it's a legitimate async message type, process it. (NOTIFY
1685 * messages are not currently possible here, but we handle them for
1686 * completeness.) Otherwise, if it's anything except Copy Data,
1687 * report end-of-copy.
1688 */
1689 switch (id)
1690 {
1692 if (getNotify(conn))
1693 return 0;
1694 break;
1696 if (pqGetErrorNotice3(conn, false))
1697 return 0;
1698 break;
1701 return 0;
1702 break;
1703 case PqMsg_CopyData:
1704 return msgLength;
1705 case PqMsg_CopyDone:
1706
1707 /*
1708 * If this is a CopyDone message, exit COPY_OUT mode and let
1709 * caller read status with PQgetResult(). If we're in
1710 * COPY_BOTH mode, return to COPY_IN mode.
1711 */
1714 else
1716 return -1;
1717 default: /* treat as end of copy */
1718
1719 /*
1720 * Any other message terminates either COPY_IN or COPY_BOTH
1721 * mode.
1722 */
1724 return -1;
1725 }
1726
1727 /* Drop the processed message and loop around for another */
1729 }
1730}
void pqParseDone(PGconn *conn, int newInStart)
Definition: fe-misc.c:443
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:77
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:351
static int getNotify(PGconn *conn)
static int getParameterStatus(PGconn *conn)
static void handleSyncLoss(PGconn *conn, char id, int msgLength)
Definition: fe-protocol3.c:479
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:878
@ PGASYNC_COPY_BOTH
Definition: libpq-int.h:232
@ PGASYNC_COPY_IN
Definition: libpq-int.h:230
@ PGASYNC_BUSY
Definition: libpq-int.h:224
#define PqMsg_CopyDone
Definition: protocol.h:64
#define PqMsg_ParameterStatus
Definition: protocol.h:51
int inEnd
Definition: libpq-int.h:549
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:454

References pg_conn::asyncStatus, conn, getNotify(), getParameterStatus(), handleSyncLoss(), pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, pqCheckInBufferSpace(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), PqMsg_CopyData, PqMsg_CopyDone, PqMsg_NoticeResponse, PqMsg_NotificationResponse, PqMsg_ParameterStatus, and pqParseDone().

Referenced by pqGetCopyData3(), and pqGetlineAsync3().

◆ getCopyStart()

static int getCopyStart ( PGconn conn,
ExecStatusType  copytype 
)
static

Definition at line 1550 of file fe-protocol3.c.

1551{
1552 PGresult *result;
1553 int nfields;
1554 int i;
1555
1556 result = PQmakeEmptyPGresult(conn, copytype);
1557 if (!result)
1558 goto failure;
1559
1561 goto failure;
1562 result->binary = conn->copy_is_binary;
1563 /* the next two bytes are the number of fields */
1564 if (pqGetInt(&(result->numAttributes), 2, conn))
1565 goto failure;
1566 nfields = result->numAttributes;
1567
1568 /* allocate space for the attribute descriptors */
1569 if (nfields > 0)
1570 {
1571 result->attDescs = (PGresAttDesc *)
1572 pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
1573 if (!result->attDescs)
1574 goto failure;
1575 MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
1576 }
1577
1578 for (i = 0; i < nfields; i++)
1579 {
1580 int format;
1581
1582 if (pqGetInt(&format, 2, conn))
1583 goto failure;
1584
1585 /*
1586 * Since pqGetInt treats 2-byte integers as unsigned, we need to
1587 * coerce these results to signed form.
1588 */
1589 format = (int) ((int16) format);
1590 result->attDescs[i].format = format;
1591 }
1592
1593 /* Success! */
1594 conn->result = result;
1595 return 0;
1596
1597failure:
1598 PQclear(result);
1599 return EOF;
1600}
int16_t int16
Definition: c.h:483
#define MemSet(start, val, len)
Definition: c.h:977
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:563
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:159
static char format
char copy_is_binary
Definition: libpq-int.h:465
int binary
Definition: libpq-int.h:184
PGresAttDesc * attDescs
Definition: libpq-int.h:176

References pg_result::attDescs, pg_result::binary, conn, pg_conn::copy_is_binary, format, pgresAttDesc::format, i, MemSet, pg_result::numAttributes, PQclear(), pqGetc(), pqGetInt(), PQmakeEmptyPGresult(), pqResultAlloc(), and pg_conn::result.

Referenced by pqParseInput3().

◆ getNotify()

static int getNotify ( PGconn conn)
static

Definition at line 1494 of file fe-protocol3.c.

1495{
1496 int be_pid;
1497 char *svname;
1498 int nmlen;
1499 int extralen;
1500 PGnotify *newNotify;
1501
1502 if (pqGetInt(&be_pid, 4, conn))
1503 return EOF;
1504 if (pqGets(&conn->workBuffer, conn))
1505 return EOF;
1506 /* must save name while getting extra string */
1507 svname = strdup(conn->workBuffer.data);
1508 if (!svname)
1509 return EOF;
1510 if (pqGets(&conn->workBuffer, conn))
1511 {
1512 free(svname);
1513 return EOF;
1514 }
1515
1516 /*
1517 * Store the strings right after the PGnotify structure so it can all be
1518 * freed at once. We don't use NAMEDATALEN because we don't want to tie
1519 * this interface to a specific server name length.
1520 */
1521 nmlen = strlen(svname);
1522 extralen = strlen(conn->workBuffer.data);
1523 newNotify = (PGnotify *) malloc(sizeof(PGnotify) + nmlen + extralen + 2);
1524 if (newNotify)
1525 {
1526 newNotify->relname = (char *) newNotify + sizeof(PGnotify);
1527 strcpy(newNotify->relname, svname);
1528 newNotify->extra = newNotify->relname + nmlen + 1;
1529 strcpy(newNotify->extra, conn->workBuffer.data);
1530 newNotify->be_pid = be_pid;
1531 newNotify->next = NULL;
1532 if (conn->notifyTail)
1533 conn->notifyTail->next = newNotify;
1534 else
1535 conn->notifyHead = newNotify;
1536 conn->notifyTail = newNotify;
1537 }
1538
1539 free(svname);
1540 return 0;
1541}
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:136
#define free(a)
Definition: header.h:65
#define malloc(a)
Definition: header.h:50
struct pgNotify * next
Definition: libpq-fe.h:222
int be_pid
Definition: libpq-fe.h:219
char * relname
Definition: libpq-fe.h:218
char * extra
Definition: libpq-fe.h:220
PGnotify * notifyHead
Definition: libpq-int.h:467
PGnotify * notifyTail
Definition: libpq-int.h:468
PQExpBufferData workBuffer
Definition: libpq-int.h:656

References pgNotify::be_pid, conn, PQExpBufferData::data, pgNotify::extra, free, malloc, pgNotify::next, pg_conn::notifyHead, pg_conn::notifyTail, pqGetInt(), pqGets(), pgNotify::relname, and pg_conn::workBuffer.

Referenced by getCopyDataMessage(), pqFunctionCall3(), and pqParseInput3().

◆ getParamDescriptions()

static int getParamDescriptions ( PGconn conn,
int  msgLength 
)
static

Definition at line 670 of file fe-protocol3.c.

671{
672 PGresult *result;
673 const char *errmsg = NULL; /* means "out of memory", see below */
674 int nparams;
675 int i;
676
678 if (!result)
679 goto advance_and_error;
680
681 /* parseInput already read the 't' label and message length. */
682 /* the next two bytes are the number of parameters */
683 if (pqGetInt(&(result->numParameters), 2, conn))
684 goto not_enough_data;
685 nparams = result->numParameters;
686
687 /* allocate space for the parameter descriptors */
688 if (nparams > 0)
689 {
690 result->paramDescs = (PGresParamDesc *)
691 pqResultAlloc(result, nparams * sizeof(PGresParamDesc), true);
692 if (!result->paramDescs)
693 goto advance_and_error;
694 MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
695 }
696
697 /* get parameter info */
698 for (i = 0; i < nparams; i++)
699 {
700 int typid;
701
702 if (pqGetInt(&typid, 4, conn))
703 goto not_enough_data;
704 result->paramDescs[i].typid = typid;
705 }
706
707 /* Success! */
708 conn->result = result;
709
710 return 0;
711
712not_enough_data:
713 errmsg = libpq_gettext("insufficient data in \"t\" message");
714
715advance_and_error:
716 /* Discard unsaved result, if any */
717 if (result && result != conn->result)
718 PQclear(result);
719
720 /*
721 * Replace partially constructed result with an error result. First
722 * discard the old result to try to win back some memory.
723 */
725
726 /*
727 * If preceding code didn't provide an error message, assume "out of
728 * memory" was meant. The advantage of having this special case is that
729 * freeing the old result first greatly improves the odds that gettext()
730 * will succeed in providing a translation.
731 */
732 if (!errmsg)
733 errmsg = libpq_gettext("out of memory");
736
737 /*
738 * Show the message as fully consumed, else pqParseInput3 will overwrite
739 * our error with a complaint about that.
740 */
741 conn->inCursor = conn->inStart + 5 + msgLength;
742
743 /*
744 * Return zero to allow input parsing to continue. Essentially, we've
745 * replaced the COMMAND_OK result with an error result, but since this
746 * doesn't affect the protocol state, it's fine.
747 */
748 return 0;
749}
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:120
int numParameters
Definition: libpq-int.h:180
PGresParamDesc * paramDescs
Definition: libpq-int.h:181

References appendPQExpBuffer(), conn, errmsg(), pg_conn::errorMessage, i, pg_conn::inCursor, pg_conn::inStart, libpq_gettext, MemSet, pg_result::numParameters, pg_result::paramDescs, PGRES_COMMAND_OK, PQclear(), pqClearAsyncResult(), pqGetInt(), PQmakeEmptyPGresult(), pqResultAlloc(), pqSaveErrorResult(), pg_conn::result, and pgresParamDesc::typid.

Referenced by pqParseInput3().

◆ getParameterStatus()

static int getParameterStatus ( PGconn conn)
static

Definition at line 1465 of file fe-protocol3.c.

1466{
1467 PQExpBufferData valueBuf;
1468
1469 /* Get the parameter name */
1470 if (pqGets(&conn->workBuffer, conn))
1471 return EOF;
1472 /* Get the parameter value (could be large) */
1473 initPQExpBuffer(&valueBuf);
1474 if (pqGets(&valueBuf, conn))
1475 {
1476 termPQExpBuffer(&valueBuf);
1477 return EOF;
1478 }
1479 /* And save it */
1481 termPQExpBuffer(&valueBuf);
1482 return 0;
1483}
void pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
Definition: fe-exec.c:1081
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129

References conn, PQExpBufferData::data, initPQExpBuffer(), pqGets(), pqSaveParameterStatus(), termPQExpBuffer(), and pg_conn::workBuffer.

Referenced by getCopyDataMessage(), pqFunctionCall3(), and pqParseInput3().

◆ getReadyForQuery()

static int getReadyForQuery ( PGconn conn)
static

Definition at line 1606 of file fe-protocol3.c.

1607{
1608 char xact_status;
1609
1610 if (pqGetc(&xact_status, conn))
1611 return EOF;
1612 switch (xact_status)
1613 {
1614 case 'I':
1616 break;
1617 case 'T':
1619 break;
1620 case 'E':
1622 break;
1623 default:
1625 break;
1626 }
1627
1628 return 0;
1629}
@ PQTRANS_INTRANS
Definition: libpq-fe.h:144
@ PQTRANS_IDLE
Definition: libpq-fe.h:142
@ PQTRANS_UNKNOWN
Definition: libpq-fe.h:146
@ PQTRANS_INERROR
Definition: libpq-fe.h:145
PGTransactionStatusType xactStatus
Definition: libpq-int.h:455

References conn, pqGetc(), PQTRANS_IDLE, PQTRANS_INERROR, PQTRANS_INTRANS, PQTRANS_UNKNOWN, and pg_conn::xactStatus.

Referenced by pqFunctionCall3(), and pqParseInput3().

◆ getRowDescriptions()

static int getRowDescriptions ( PGconn conn,
int  msgLength 
)
static

Definition at line 499 of file fe-protocol3.c.

500{
501 PGresult *result;
502 int nfields;
503 const char *errmsg;
504 int i;
505
506 /*
507 * When doing Describe for a prepared statement, there'll already be a
508 * PGresult created by getParamDescriptions, and we should fill data into
509 * that. Otherwise, create a new, empty PGresult.
510 */
511 if (!conn->cmd_queue_head ||
514 {
515 if (conn->result)
516 result = conn->result;
517 else
519 }
520 else
522 if (!result)
523 {
524 errmsg = NULL; /* means "out of memory", see below */
525 goto advance_and_error;
526 }
527
528 /* parseInput already read the 'T' label and message length. */
529 /* the next two bytes are the number of fields */
530 if (pqGetInt(&(result->numAttributes), 2, conn))
531 {
532 /* We should not run out of data here, so complain */
533 errmsg = libpq_gettext("insufficient data in \"T\" message");
534 goto advance_and_error;
535 }
536 nfields = result->numAttributes;
537
538 /* allocate space for the attribute descriptors */
539 if (nfields > 0)
540 {
541 result->attDescs = (PGresAttDesc *)
542 pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
543 if (!result->attDescs)
544 {
545 errmsg = NULL; /* means "out of memory", see below */
546 goto advance_and_error;
547 }
548 MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
549 }
550
551 /* result->binary is true only if ALL columns are binary */
552 result->binary = (nfields > 0) ? 1 : 0;
553
554 /* get type info */
555 for (i = 0; i < nfields; i++)
556 {
557 int tableid;
558 int columnid;
559 int typid;
560 int typlen;
561 int atttypmod;
562 int format;
563
564 if (pqGets(&conn->workBuffer, conn) ||
565 pqGetInt(&tableid, 4, conn) ||
566 pqGetInt(&columnid, 2, conn) ||
567 pqGetInt(&typid, 4, conn) ||
568 pqGetInt(&typlen, 2, conn) ||
569 pqGetInt(&atttypmod, 4, conn) ||
570 pqGetInt(&format, 2, conn))
571 {
572 /* We should not run out of data here, so complain */
573 errmsg = libpq_gettext("insufficient data in \"T\" message");
574 goto advance_and_error;
575 }
576
577 /*
578 * Since pqGetInt treats 2-byte integers as unsigned, we need to
579 * coerce these results to signed form.
580 */
581 columnid = (int) ((int16) columnid);
582 typlen = (int) ((int16) typlen);
583 format = (int) ((int16) format);
584
585 result->attDescs[i].name = pqResultStrdup(result,
587 if (!result->attDescs[i].name)
588 {
589 errmsg = NULL; /* means "out of memory", see below */
590 goto advance_and_error;
591 }
592 result->attDescs[i].tableid = tableid;
593 result->attDescs[i].columnid = columnid;
594 result->attDescs[i].format = format;
595 result->attDescs[i].typid = typid;
596 result->attDescs[i].typlen = typlen;
597 result->attDescs[i].atttypmod = atttypmod;
598
599 if (format != 1)
600 result->binary = 0;
601 }
602
603 /* Success! */
604 conn->result = result;
605
606 /*
607 * If we're doing a Describe, we're done, and ready to pass the result
608 * back to the client.
609 */
610 if ((!conn->cmd_queue_head) ||
613 {
615 return 0;
616 }
617
618 /*
619 * We could perform additional setup for the new result set here, but for
620 * now there's nothing else to do.
621 */
622
623 /* And we're done. */
624 return 0;
625
626advance_and_error:
627 /* Discard unsaved result, if any */
628 if (result && result != conn->result)
629 PQclear(result);
630
631 /*
632 * Replace partially constructed result with an error result. First
633 * discard the old result to try to win back some memory.
634 */
636
637 /*
638 * If preceding code didn't provide an error message, assume "out of
639 * memory" was meant. The advantage of having this special case is that
640 * freeing the old result first greatly improves the odds that gettext()
641 * will succeed in providing a translation.
642 */
643 if (!errmsg)
644 errmsg = libpq_gettext("out of memory for query result");
645
648
649 /*
650 * Show the message as fully consumed, else pqParseInput3 will overwrite
651 * our error with a complaint about that.
652 */
653 conn->inCursor = conn->inStart + 5 + msgLength;
654
655 /*
656 * Return zero to allow input parsing to continue. Subsequent "D"
657 * messages will be ignored until we get to end of data, since an error
658 * result is already set up.
659 */
660 return 0;
661}
char * pqResultStrdup(PGresult *res, const char *str)
Definition: fe-exec.c:675
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:123
@ PGASYNC_READY
Definition: libpq-int.h:225
@ PGQUERY_DESCRIBE
Definition: libpq-int.h:331
PGQueryClass queryclass
Definition: libpq-int.h:353
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:480
char * name
Definition: libpq-fe.h:295
int columnid
Definition: libpq-fe.h:297
int atttypmod
Definition: libpq-fe.h:301

References appendPQExpBuffer(), pg_conn::asyncStatus, pg_result::attDescs, pgresAttDesc::atttypmod, pg_result::binary, pg_conn::cmd_queue_head, pgresAttDesc::columnid, conn, PQExpBufferData::data, errmsg(), pg_conn::errorMessage, format, pgresAttDesc::format, i, pg_conn::inCursor, pg_conn::inStart, libpq_gettext, MemSet, pgresAttDesc::name, pg_result::numAttributes, PGASYNC_READY, PGQUERY_DESCRIBE, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear(), pqClearAsyncResult(), pqGetInt(), pqGets(), PQmakeEmptyPGresult(), pqResultAlloc(), pqResultStrdup(), pqSaveErrorResult(), PGcmdQueueEntry::queryclass, pg_conn::result, pgresAttDesc::tableid, pgresAttDesc::typid, pgresAttDesc::typlen, and pg_conn::workBuffer.

Referenced by pqParseInput3().

◆ handleSyncLoss()

static void handleSyncLoss ( PGconn conn,
char  id,
int  msgLength 
)
static

Definition at line 479 of file fe-protocol3.c.

480{
481 libpq_append_conn_error(conn, "lost synchronization with server: got message type \"%c\", length %d",
482 id, msgLength);
483 /* build an error result holding the error message */
485 conn->asyncStatus = PGASYNC_READY; /* drop out of PQgetResult wait loop */
486 /* flush input data since we're giving up on processing it */
487 pqDropConnection(conn, true);
488 conn->status = CONNECTION_BAD; /* No more connection to backend */
489}
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:480
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition: fe-misc.c:1372
@ CONNECTION_BAD
Definition: libpq-fe.h:82
ConnStatusType status
Definition: libpq-int.h:453

References pg_conn::asyncStatus, conn, CONNECTION_BAD, libpq_append_conn_error(), PGASYNC_READY, pqDropConnection(), pqSaveErrorResult(), and pg_conn::status.

Referenced by getCopyDataMessage(), pqFunctionCall3(), and pqParseInput3().

◆ pqBuildErrorMessage3()

void pqBuildErrorMessage3 ( PQExpBuffer  msg,
const PGresult res,
PGVerbosity  verbosity,
PGContextVisibility  show_context 
)

Definition at line 1010 of file fe-protocol3.c.

1012{
1013 const char *val;
1014 const char *querytext = NULL;
1015 int querypos = 0;
1016
1017 /* If we couldn't allocate a PGresult, just say "out of memory" */
1018 if (res == NULL)
1019 {
1020 appendPQExpBufferStr(msg, libpq_gettext("out of memory\n"));
1021 return;
1022 }
1023
1024 /*
1025 * If we don't have any broken-down fields, just return the base message.
1026 * This mainly applies if we're given a libpq-generated error result.
1027 */
1028 if (res->errFields == NULL)
1029 {
1030 if (res->errMsg && res->errMsg[0])
1032 else
1033 appendPQExpBufferStr(msg, libpq_gettext("no error message available\n"));
1034 return;
1035 }
1036
1037 /* Else build error message from relevant fields */
1039 if (val)
1040 appendPQExpBuffer(msg, "%s: ", val);
1041
1042 if (verbosity == PQERRORS_SQLSTATE)
1043 {
1044 /*
1045 * If we have a SQLSTATE, print that and nothing else. If not (which
1046 * shouldn't happen for server-generated errors, but might possibly
1047 * happen for libpq-generated ones), fall back to TERSE format, as
1048 * that seems better than printing nothing at all.
1049 */
1051 if (val)
1052 {
1053 appendPQExpBuffer(msg, "%s\n", val);
1054 return;
1055 }
1056 verbosity = PQERRORS_TERSE;
1057 }
1058
1059 if (verbosity == PQERRORS_VERBOSE)
1060 {
1062 if (val)
1063 appendPQExpBuffer(msg, "%s: ", val);
1064 }
1066 if (val)
1069 if (val)
1070 {
1071 if (verbosity != PQERRORS_TERSE && res->errQuery != NULL)
1072 {
1073 /* emit position as a syntax cursor display */
1074 querytext = res->errQuery;
1075 querypos = atoi(val);
1076 }
1077 else
1078 {
1079 /* emit position as text addition to primary message */
1080 /* translator: %s represents a digit string */
1081 appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1082 val);
1083 }
1084 }
1085 else
1086 {
1088 if (val)
1089 {
1091 if (verbosity != PQERRORS_TERSE && querytext != NULL)
1092 {
1093 /* emit position as a syntax cursor display */
1094 querypos = atoi(val);
1095 }
1096 else
1097 {
1098 /* emit position as text addition to primary message */
1099 /* translator: %s represents a digit string */
1100 appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1101 val);
1102 }
1103 }
1104 }
1105 appendPQExpBufferChar(msg, '\n');
1106 if (verbosity != PQERRORS_TERSE)
1107 {
1108 if (querytext && querypos > 0)
1109 reportErrorPosition(msg, querytext, querypos,
1112 if (val)
1113 appendPQExpBuffer(msg, libpq_gettext("DETAIL: %s\n"), val);
1115 if (val)
1116 appendPQExpBuffer(msg, libpq_gettext("HINT: %s\n"), val);
1118 if (val)
1119 appendPQExpBuffer(msg, libpq_gettext("QUERY: %s\n"), val);
1120 if (show_context == PQSHOW_CONTEXT_ALWAYS ||
1121 (show_context == PQSHOW_CONTEXT_ERRORS &&
1123 {
1125 if (val)
1126 appendPQExpBuffer(msg, libpq_gettext("CONTEXT: %s\n"),
1127 val);
1128 }
1129 }
1130 if (verbosity == PQERRORS_VERBOSE)
1131 {
1133 if (val)
1135 libpq_gettext("SCHEMA NAME: %s\n"), val);
1137 if (val)
1139 libpq_gettext("TABLE NAME: %s\n"), val);
1141 if (val)
1143 libpq_gettext("COLUMN NAME: %s\n"), val);
1145 if (val)
1147 libpq_gettext("DATATYPE NAME: %s\n"), val);
1149 if (val)
1151 libpq_gettext("CONSTRAINT NAME: %s\n"), val);
1152 }
1153 if (verbosity == PQERRORS_VERBOSE)
1154 {
1155 const char *valf;
1156 const char *vall;
1157
1161 if (val || valf || vall)
1162 {
1163 appendPQExpBufferStr(msg, libpq_gettext("LOCATION: "));
1164 if (val)
1165 appendPQExpBuffer(msg, libpq_gettext("%s, "), val);
1166 if (valf && vall) /* unlikely we'd have just one */
1167 appendPQExpBuffer(msg, libpq_gettext("%s:%s"),
1168 valf, vall);
1169 appendPQExpBufferChar(msg, '\n');
1170 }
1171 }
1172}
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3466
static void reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding)
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:131
@ PQSHOW_CONTEXT_ALWAYS
Definition: libpq-fe.h:161
@ PQSHOW_CONTEXT_ERRORS
Definition: libpq-fe.h:160
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:153
@ PQERRORS_TERSE
Definition: libpq-fe.h:151
@ PQERRORS_SQLSTATE
Definition: libpq-fe.h:154
#define PG_DIAG_INTERNAL_QUERY
Definition: postgres_ext.h:63
#define PG_DIAG_SCHEMA_NAME
Definition: postgres_ext.h:65
#define PG_DIAG_CONSTRAINT_NAME
Definition: postgres_ext.h:69
#define PG_DIAG_DATATYPE_NAME
Definition: postgres_ext.h:68
#define PG_DIAG_SOURCE_LINE
Definition: postgres_ext.h:71
#define PG_DIAG_STATEMENT_POSITION
Definition: postgres_ext.h:61
#define PG_DIAG_SOURCE_FILE
Definition: postgres_ext.h:70
#define PG_DIAG_MESSAGE_HINT
Definition: postgres_ext.h:60
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:57
#define PG_DIAG_TABLE_NAME
Definition: postgres_ext.h:66
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:58
#define PG_DIAG_COLUMN_NAME
Definition: postgres_ext.h:67
#define PG_DIAG_MESSAGE_DETAIL
Definition: postgres_ext.h:59
#define PG_DIAG_CONTEXT
Definition: postgres_ext.h:64
#define PG_DIAG_SEVERITY
Definition: postgres_ext.h:55
#define PG_DIAG_SOURCE_FUNCTION
Definition: postgres_ext.h:72
#define PG_DIAG_INTERNAL_POSITION
Definition: postgres_ext.h:62
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:378
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
char * errMsg
Definition: libpq-int.h:201
PGMessageField * errFields
Definition: libpq-int.h:202
ExecStatusType resultStatus
Definition: libpq-int.h:182
char * errQuery
Definition: libpq-int.h:203
int client_encoding
Definition: libpq-int.h:194

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), pg_result::client_encoding, pg_result::errFields, pg_result::errMsg, pg_result::errQuery, libpq_gettext, PG_DIAG_COLUMN_NAME, PG_DIAG_CONSTRAINT_NAME, PG_DIAG_CONTEXT, PG_DIAG_DATATYPE_NAME, PG_DIAG_INTERNAL_POSITION, PG_DIAG_INTERNAL_QUERY, PG_DIAG_MESSAGE_DETAIL, PG_DIAG_MESSAGE_HINT, PG_DIAG_MESSAGE_PRIMARY, PG_DIAG_SCHEMA_NAME, PG_DIAG_SEVERITY, PG_DIAG_SOURCE_FILE, PG_DIAG_SOURCE_FUNCTION, PG_DIAG_SOURCE_LINE, PG_DIAG_SQLSTATE, PG_DIAG_STATEMENT_POSITION, PG_DIAG_TABLE_NAME, PGRES_FATAL_ERROR, PQERRORS_SQLSTATE, PQERRORS_TERSE, PQERRORS_VERBOSE, PQresultErrorField(), PQSHOW_CONTEXT_ALWAYS, PQSHOW_CONTEXT_ERRORS, reportErrorPosition(), res, pg_result::resultStatus, and val.

Referenced by pqGetErrorNotice3(), and PQresultVerboseErrorMessage().

◆ pqBuildStartupPacket3()

char * pqBuildStartupPacket3 ( PGconn conn,
int *  packetlen,
const PQEnvironmentOption options 
)

Definition at line 2231 of file fe-protocol3.c.

2233{
2234 char *startpacket;
2235
2236 *packetlen = build_startup_packet(conn, NULL, options);
2237 startpacket = (char *) malloc(*packetlen);
2238 if (!startpacket)
2239 return NULL;
2240 *packetlen = build_startup_packet(conn, startpacket, options);
2241 return startpacket;
2242}
static int build_startup_packet(const PGconn *conn, char *packet, const PQEnvironmentOption *options)

References build_startup_packet(), conn, and malloc.

Referenced by PQconnectPoll().

◆ pqEndcopy3()

int pqEndcopy3 ( PGconn conn)

Definition at line 1908 of file fe-protocol3.c.

1909{
1910 PGresult *result;
1911
1915 {
1916 libpq_append_conn_error(conn, "no COPY in progress");
1917 return 1;
1918 }
1919
1920 /* Send the CopyDone message if needed */
1923 {
1924 if (pqPutMsgStart(PqMsg_CopyDone, conn) < 0 ||
1925 pqPutMsgEnd(conn) < 0)
1926 return 1;
1927
1928 /*
1929 * If we sent the COPY command in extended-query mode, we must issue a
1930 * Sync as well.
1931 */
1932 if (conn->cmd_queue_head &&
1934 {
1935 if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
1936 pqPutMsgEnd(conn) < 0)
1937 return 1;
1938 }
1939 }
1940
1941 /*
1942 * make sure no data is waiting to be sent, abort if we are non-blocking
1943 * and the flush fails
1944 */
1946 return 1;
1947
1948 /* Return to active duty */
1950
1951 /*
1952 * Non blocking connections may have to abort at this point. If everyone
1953 * played the game there should be no problem, but in error scenarios the
1954 * expected messages may not have arrived yet. (We are assuming that the
1955 * backend's packetizing will ensure that CommandComplete arrives along
1956 * with the CopyDone; are there corner cases where that doesn't happen?)
1957 */
1959 return 1;
1960
1961 /* Wait for the completion response */
1962 result = PQgetResult(conn);
1963
1964 /* Expecting a successful result */
1965 if (result && result->resultStatus == PGRES_COMMAND_OK)
1966 {
1967 PQclear(result);
1968 return 0;
1969 }
1970
1971 /*
1972 * Trouble. For backwards-compatibility reasons, we issue the error
1973 * message as if it were a notice (would be nice to get rid of this
1974 * silliness, but too many apps probably don't handle errors from
1975 * PQendcopy reasonably). Note that the app can still obtain the error
1976 * status from the PGconn object.
1977 */
1978 if (conn->errorMessage.len > 0)
1979 {
1980 /* We have to strip the trailing newline ... pain in neck... */
1981 char svLast = conn->errorMessage.data[conn->errorMessage.len - 1];
1982
1983 if (svLast == '\n')
1984 conn->errorMessage.data[conn->errorMessage.len - 1] = '\0';
1986 conn->errorMessage.data[conn->errorMessage.len - 1] = svLast;
1987 }
1988
1989 PQclear(result);
1990
1991 return 1;
1992}
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2062
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:938
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2031
int pqFlush(PGconn *conn)
Definition: fe-misc.c:968
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:473
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:532
@ PGASYNC_COPY_OUT
Definition: libpq-int.h:231
@ PGQUERY_SIMPLE
Definition: libpq-int.h:328
#define pqIsnonblocking(conn)
Definition: libpq-int.h:904
#define PqMsg_Sync
Definition: protocol.h:27
PGNoticeHooks noticeHooks
Definition: libpq-int.h:445

References pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, PQExpBufferData::data, pg_conn::errorMessage, PQExpBufferData::len, libpq_append_conn_error(), pg_conn::noticeHooks, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGQUERY_SIMPLE, PGRES_COMMAND_OK, PQclear(), pqFlush(), PQgetResult(), pqInternalNotice(), PQisBusy(), pqIsnonblocking, PqMsg_CopyDone, PqMsg_Sync, pqPutMsgEnd(), pqPutMsgStart(), PGcmdQueueEntry::queryclass, and pg_result::resultStatus.

Referenced by PQendcopy().

◆ pqFunctionCall3()

PGresult * pqFunctionCall3 ( PGconn conn,
Oid  fnid,
int *  result_buf,
int *  actual_result_len,
int  result_is_int,
const PQArgBlock args,
int  nargs 
)

Definition at line 2001 of file fe-protocol3.c.

2005{
2006 bool needInput = false;
2008 char id;
2009 int msgLength;
2010 int avail;
2011 int i;
2012
2013 /* already validated by PQfn */
2015
2016 /* PQfn already validated connection state */
2017
2019 pqPutInt(fnid, 4, conn) < 0 || /* function id */
2020 pqPutInt(1, 2, conn) < 0 || /* # of format codes */
2021 pqPutInt(1, 2, conn) < 0 || /* format code: BINARY */
2022 pqPutInt(nargs, 2, conn) < 0) /* # of args */
2023 {
2024 /* error message should be set up already */
2025 return NULL;
2026 }
2027
2028 for (i = 0; i < nargs; ++i)
2029 { /* len.int4 + contents */
2030 if (pqPutInt(args[i].len, 4, conn))
2031 return NULL;
2032 if (args[i].len == -1)
2033 continue; /* it's NULL */
2034
2035 if (args[i].isint)
2036 {
2037 if (pqPutInt(args[i].u.integer, args[i].len, conn))
2038 return NULL;
2039 }
2040 else
2041 {
2042 if (pqPutnchar((char *) args[i].u.ptr, args[i].len, conn))
2043 return NULL;
2044 }
2045 }
2046
2047 if (pqPutInt(1, 2, conn) < 0) /* result format code: BINARY */
2048 return NULL;
2049
2050 if (pqPutMsgEnd(conn) < 0 ||
2051 pqFlush(conn))
2052 return NULL;
2053
2054 for (;;)
2055 {
2056 if (needInput)
2057 {
2058 /* Wait for some data to arrive (or for the channel to close) */
2059 if (pqWait(true, false, conn) ||
2060 pqReadData(conn) < 0)
2061 break;
2062 }
2063
2064 /*
2065 * Scan the message. If we run out of data, loop around to try again.
2066 */
2067 needInput = true;
2068
2070 if (pqGetc(&id, conn))
2071 continue;
2072 if (pqGetInt(&msgLength, 4, conn))
2073 continue;
2074
2075 /*
2076 * Try to validate message type/length here. A length less than 4 is
2077 * definitely broken. Large lengths should only be believed for a few
2078 * message types.
2079 */
2080 if (msgLength < 4)
2081 {
2082 handleSyncLoss(conn, id, msgLength);
2083 break;
2084 }
2085 if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
2086 {
2087 handleSyncLoss(conn, id, msgLength);
2088 break;
2089 }
2090
2091 /*
2092 * Can't process if message body isn't all here yet.
2093 */
2094 msgLength -= 4;
2095 avail = conn->inEnd - conn->inCursor;
2096 if (avail < msgLength)
2097 {
2098 /*
2099 * Before looping, enlarge the input buffer if needed to hold the
2100 * whole message. See notes in parseInput.
2101 */
2102 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
2103 conn))
2104 {
2105 /*
2106 * XXX add some better recovery code... plan is to skip over
2107 * the message using its length, then report an error. For the
2108 * moment, just treat this like loss of sync (which indeed it
2109 * might be!)
2110 */
2111 handleSyncLoss(conn, id, msgLength);
2112 break;
2113 }
2114 continue;
2115 }
2116
2117 /*
2118 * We should see V or E response to the command, but might get N
2119 * and/or A notices first. We also need to swallow the final Z before
2120 * returning.
2121 */
2122 switch (id)
2123 {
2124 case 'V': /* function result */
2125 if (pqGetInt(actual_result_len, 4, conn))
2126 continue;
2127 if (*actual_result_len != -1)
2128 {
2129 if (result_is_int)
2130 {
2131 if (pqGetInt(result_buf, *actual_result_len, conn))
2132 continue;
2133 }
2134 else
2135 {
2136 if (pqGetnchar((char *) result_buf,
2137 *actual_result_len,
2138 conn))
2139 continue;
2140 }
2141 }
2142 /* correctly finished function result message */
2143 status = PGRES_COMMAND_OK;
2144 break;
2145 case 'E': /* error return */
2146 if (pqGetErrorNotice3(conn, true))
2147 continue;
2148 status = PGRES_FATAL_ERROR;
2149 break;
2150 case 'A': /* notify message */
2151 /* handle notify and go back to processing return values */
2152 if (getNotify(conn))
2153 continue;
2154 break;
2155 case 'N': /* notice */
2156 /* handle notice and go back to processing return values */
2157 if (pqGetErrorNotice3(conn, false))
2158 continue;
2159 break;
2160 case 'Z': /* backend is ready for new query */
2162 continue;
2163
2164 /* consume the message */
2165 pqParseDone(conn, conn->inStart + 5 + msgLength);
2166
2167 /*
2168 * If we already have a result object (probably an error), use
2169 * that. Otherwise, if we saw a function result message,
2170 * report COMMAND_OK. Otherwise, the backend violated the
2171 * protocol, so complain.
2172 */
2174 {
2175 if (status == PGRES_COMMAND_OK)
2176 {
2177 conn->result = PQmakeEmptyPGresult(conn, status);
2178 if (!conn->result)
2179 {
2180 libpq_append_conn_error(conn, "out of memory");
2182 }
2183 }
2184 else
2185 {
2186 libpq_append_conn_error(conn, "protocol error: no function result");
2188 }
2189 }
2190 /* and we're out */
2191 return pqPrepareAsyncResult(conn);
2192 case 'S': /* parameter status */
2194 continue;
2195 break;
2196 default:
2197 /* The backend violates the protocol. */
2198 libpq_append_conn_error(conn, "protocol error: id=0x%x", id);
2200
2201 /*
2202 * We can't call parsing done due to the protocol violation
2203 * (so message tracing wouldn't work), but trust the specified
2204 * message length as what to skip.
2205 */
2206 conn->inStart += 5 + msgLength;
2207 return pqPrepareAsyncResult(conn);
2208 }
2209
2210 /* Completed parsing this message, keep going */
2211 pqParseDone(conn, conn->inStart + 5 + msgLength);
2212 needInput = false;
2213 }
2214
2215 /*
2216 * We fall out of the loop only upon failing to read data.
2217 * conn->errorMessage has been set by pqWait or pqReadData. We want to
2218 * append it to any already-received error message.
2219 */
2221 return pqPrepareAsyncResult(conn);
2222}
#define Assert(condition)
Definition: c.h:815
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:851
int pqReadData(PGconn *conn)
Definition: fe-misc.c:580
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:253
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:165
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:993
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:202
#define VALID_LONG_MESSAGE_TYPE(id)
Definition: fe-protocol3.c:36
static int getReadyForQuery(PGconn *conn)
ExecStatusType
Definition: libpq-fe.h:118
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:182
#define pgHavePendingResult(conn)
Definition: libpq-int.h:897
const void size_t len
#define PqMsg_FunctionCall
Definition: protocol.h:23
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:460

References generate_unaccent_rules::args, Assert, conn, getNotify(), getParameterStatus(), getReadyForQuery(), handleSyncLoss(), i, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, len, libpq_append_conn_error(), pgHavePendingResult, PGRES_COMMAND_OK, PGRES_FATAL_ERROR, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqCheckInBufferSpace(), pqFlush(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGetnchar(), PQmakeEmptyPGresult(), PqMsg_FunctionCall, pqParseDone(), pqPrepareAsyncResult(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), pqReadData(), pqSaveErrorResult(), pqWait(), pg_conn::result, and VALID_LONG_MESSAGE_TYPE.

Referenced by PQfn().

◆ pqGetCopyData3()

int pqGetCopyData3 ( PGconn conn,
char **  buffer,
int  async 
)

Definition at line 1743 of file fe-protocol3.c.

1744{
1745 int msgLength;
1746
1747 for (;;)
1748 {
1749 /*
1750 * Collect the next input message. To make life simpler for async
1751 * callers, we keep returning 0 until the next message is fully
1752 * available, even if it is not Copy Data.
1753 */
1754 msgLength = getCopyDataMessage(conn);
1755 if (msgLength < 0)
1756 return msgLength; /* end-of-copy or error */
1757 if (msgLength == 0)
1758 {
1759 /* Don't block if async read requested */
1760 if (async)
1761 return 0;
1762 /* Need to load more data */
1763 if (pqWait(true, false, conn) ||
1764 pqReadData(conn) < 0)
1765 return -2;
1766 continue;
1767 }
1768
1769 /*
1770 * Drop zero-length messages (shouldn't happen anyway). Otherwise
1771 * pass the data back to the caller.
1772 */
1773 msgLength -= 4;
1774 if (msgLength > 0)
1775 {
1776 *buffer = (char *) malloc(msgLength + 1);
1777 if (*buffer == NULL)
1778 {
1779 libpq_append_conn_error(conn, "out of memory");
1780 return -2;
1781 }
1782 memcpy(*buffer, &conn->inBuffer[conn->inCursor], msgLength);
1783 (*buffer)[msgLength] = '\0'; /* Add terminating null */
1784
1785 /* Mark message consumed */
1786 pqParseDone(conn, conn->inCursor + msgLength);
1787
1788 return msgLength;
1789 }
1790
1791 /* Empty, so drop it and loop around for another */
1793 }
1794}
static int getCopyDataMessage(PGconn *conn)

References conn, getCopyDataMessage(), pg_conn::inBuffer, pg_conn::inCursor, libpq_append_conn_error(), malloc, pqParseDone(), pqReadData(), and pqWait().

Referenced by PQgetCopyData().

◆ pqGetErrorNotice3()

int pqGetErrorNotice3 ( PGconn conn,
bool  isError 
)

Definition at line 878 of file fe-protocol3.c.

879{
880 PGresult *res = NULL;
881 bool have_position = false;
882 PQExpBufferData workBuf;
883 char id;
884
885 /* If in pipeline mode, set error indicator for it */
886 if (isError && conn->pipelineStatus != PQ_PIPELINE_OFF)
888
889 /*
890 * If this is an error message, pre-emptively clear any incomplete query
891 * result we may have. We'd just throw it away below anyway, and
892 * releasing it before collecting the error might avoid out-of-memory.
893 */
894 if (isError)
896
897 /*
898 * Since the fields might be pretty long, we create a temporary
899 * PQExpBuffer rather than using conn->workBuffer. workBuffer is intended
900 * for stuff that is expected to be short. We shouldn't use
901 * conn->errorMessage either, since this might be only a notice.
902 */
903 initPQExpBuffer(&workBuf);
904
905 /*
906 * Make a PGresult to hold the accumulated fields. We temporarily lie
907 * about the result status, so that PQmakeEmptyPGresult doesn't uselessly
908 * copy conn->errorMessage.
909 *
910 * NB: This allocation can fail, if you run out of memory. The rest of the
911 * function handles that gracefully, and we still try to set the error
912 * message as the connection's error message.
913 */
915 if (res)
917
918 /*
919 * Read the fields and save into res.
920 *
921 * While at it, save the SQLSTATE in conn->last_sqlstate, and note whether
922 * we saw a PG_DIAG_STATEMENT_POSITION field.
923 */
924 for (;;)
925 {
926 if (pqGetc(&id, conn))
927 goto fail;
928 if (id == '\0')
929 break; /* terminator found */
930 if (pqGets(&workBuf, conn))
931 goto fail;
932 pqSaveMessageField(res, id, workBuf.data);
933 if (id == PG_DIAG_SQLSTATE)
934 strlcpy(conn->last_sqlstate, workBuf.data,
935 sizeof(conn->last_sqlstate));
936 else if (id == PG_DIAG_STATEMENT_POSITION)
937 have_position = true;
938 }
939
940 /*
941 * Save the active query text, if any, into res as well; but only if we
942 * might need it for an error cursor display, which is only true if there
943 * is a PG_DIAG_STATEMENT_POSITION field.
944 */
945 if (have_position && res && conn->cmd_queue_head && conn->cmd_queue_head->query)
947
948 /*
949 * Now build the "overall" error message for PQresultErrorMessage.
950 */
951 resetPQExpBuffer(&workBuf);
953
954 /*
955 * Either save error as current async result, or just emit the notice.
956 */
957 if (isError)
958 {
959 pqClearAsyncResult(conn); /* redundant, but be safe */
960 if (res)
961 {
962 pqSetResultError(res, &workBuf, 0);
963 conn->result = res;
964 }
965 else
966 {
967 /* Fall back to using the internal-error processing paths */
968 conn->error_result = true;
969 }
970
971 if (PQExpBufferDataBroken(workBuf))
972 libpq_append_conn_error(conn, "out of memory");
973 else
975 }
976 else
977 {
978 /* if we couldn't allocate the result set, just discard the NOTICE */
979 if (res)
980 {
981 /*
982 * We can cheat a little here and not copy the message. But if we
983 * were unlucky enough to run out of memory while filling workBuf,
984 * insert "out of memory", as in pqSetResultError.
985 */
986 if (PQExpBufferDataBroken(workBuf))
987 res->errMsg = libpq_gettext("out of memory\n");
988 else
989 res->errMsg = workBuf.data;
990 if (res->noticeHooks.noticeRec != NULL)
992 PQclear(res);
993 }
994 }
995
996 termPQExpBuffer(&workBuf);
997 return 0;
998
999fail:
1000 PQclear(res);
1001 termPQExpBuffer(&workBuf);
1002 return EOF;
1003}
void pqSaveMessageField(PGresult *res, char code, const char *value)
Definition: fe-exec.c:1060
void pqSetResultError(PGresult *res, PQExpBuffer errorMessage, int offset)
Definition: fe-exec.c:692
void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
@ PGRES_EMPTY_QUERY
Definition: libpq-fe.h:119
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:130
@ PQ_PIPELINE_ABORTED
Definition: libpq-fe.h:184
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:146
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
PQnoticeReceiver noticeRec
Definition: libpq-int.h:157
void * noticeRecArg
Definition: libpq-int.h:158
PGVerbosity verbosity
Definition: libpq-int.h:538
bool error_result
Definition: libpq-int.h:576
char last_sqlstate[6]
Definition: libpq-int.h:456
PGContextVisibility show_context
Definition: libpq-int.h:539
PGNoticeHooks noticeHooks
Definition: libpq-int.h:191

References appendPQExpBufferStr(), pg_conn::cmd_queue_head, conn, PQExpBufferData::data, pg_result::errMsg, pg_conn::error_result, pg_conn::errorMessage, pg_result::errQuery, initPQExpBuffer(), pg_conn::last_sqlstate, libpq_append_conn_error(), libpq_gettext, pg_result::noticeHooks, PGNoticeHooks::noticeRec, PGNoticeHooks::noticeRecArg, PG_DIAG_SQLSTATE, PG_DIAG_STATEMENT_POSITION, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PGRES_NONFATAL_ERROR, pg_conn::pipelineStatus, PQ_PIPELINE_ABORTED, PQ_PIPELINE_OFF, pqBuildErrorMessage3(), PQclear(), pqClearAsyncResult(), PQExpBufferDataBroken, pqGetc(), pqGets(), PQmakeEmptyPGresult(), pqResultStrdup(), pqSaveMessageField(), pqSetResultError(), PGcmdQueueEntry::query, res, resetPQExpBuffer(), pg_conn::result, pg_result::resultStatus, pg_conn::show_context, strlcpy(), termPQExpBuffer(), and pg_conn::verbosity.

Referenced by getCopyDataMessage(), PQconnectPoll(), pqFunctionCall3(), and pqParseInput3().

◆ pqGetline3()

int pqGetline3 ( PGconn conn,
char *  s,
int  maxlen 
)

Definition at line 1802 of file fe-protocol3.c.

1803{
1804 int status;
1805
1806 if (conn->sock == PGINVALID_SOCKET ||
1810 {
1811 libpq_append_conn_error(conn, "PQgetline: not doing text COPY OUT");
1812 *s = '\0';
1813 return EOF;
1814 }
1815
1816 while ((status = PQgetlineAsync(conn, s, maxlen - 1)) == 0)
1817 {
1818 /* need to load more data */
1819 if (pqWait(true, false, conn) ||
1820 pqReadData(conn) < 0)
1821 {
1822 *s = '\0';
1823 return EOF;
1824 }
1825 }
1826
1827 if (status < 0)
1828 {
1829 /* End of copy detected; gin up old-style terminator */
1830 strcpy(s, "\\.");
1831 return 0;
1832 }
1833
1834 /* Add null terminator, and strip trailing \n if present */
1835 if (s[status - 1] == '\n')
1836 {
1837 s[status - 1] = '\0';
1838 return 0;
1839 }
1840 else
1841 {
1842 s[status] = '\0';
1843 return 1;
1844 }
1845}
int PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
Definition: fe-exec.c:2901
#define PGINVALID_SOCKET
Definition: port.h:31
pgsocket sock
Definition: libpq-int.h:490

References pg_conn::asyncStatus, conn, pg_conn::copy_is_binary, libpq_append_conn_error(), PGASYNC_COPY_BOTH, PGASYNC_COPY_OUT, PGINVALID_SOCKET, PQgetlineAsync(), pqReadData(), pqWait(), and pg_conn::sock.

Referenced by PQgetline().

◆ pqGetlineAsync3()

int pqGetlineAsync3 ( PGconn conn,
char *  buffer,
int  bufsize 
)

Definition at line 1853 of file fe-protocol3.c.

1854{
1855 int msgLength;
1856 int avail;
1857
1860 return -1; /* we are not doing a copy... */
1861
1862 /*
1863 * Recognize the next input message. To make life simpler for async
1864 * callers, we keep returning 0 until the next message is fully available
1865 * even if it is not Copy Data. This should keep PQendcopy from blocking.
1866 * (Note: unlike pqGetCopyData3, we do not change asyncStatus here.)
1867 */
1868 msgLength = getCopyDataMessage(conn);
1869 if (msgLength < 0)
1870 return -1; /* end-of-copy or error */
1871 if (msgLength == 0)
1872 return 0; /* no data yet */
1873
1874 /*
1875 * Move data from libpq's buffer to the caller's. In the case where a
1876 * prior call found the caller's buffer too small, we use
1877 * conn->copy_already_done to remember how much of the row was already
1878 * returned to the caller.
1879 */
1881 avail = msgLength - 4 - conn->copy_already_done;
1882 if (avail <= bufsize)
1883 {
1884 /* Able to consume the whole message */
1885 memcpy(buffer, &conn->inBuffer[conn->inCursor], avail);
1886 /* Mark message consumed */
1887 conn->inStart = conn->inCursor + avail;
1888 /* Reset state for next time */
1890 return avail;
1891 }
1892 else
1893 {
1894 /* We must return a partial message */
1895 memcpy(buffer, &conn->inBuffer[conn->inCursor], bufsize);
1896 /* The message is NOT consumed from libpq's buffer */
1898 return bufsize;
1899 }
1900}
#define bufsize
Definition: indent_globs.h:36
int copy_already_done
Definition: libpq-int.h:466

References pg_conn::asyncStatus, bufsize, conn, pg_conn::copy_already_done, getCopyDataMessage(), pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inStart, PGASYNC_COPY_BOTH, and PGASYNC_COPY_OUT.

Referenced by PQgetlineAsync().

◆ pqGetNegotiateProtocolVersion3()

int pqGetNegotiateProtocolVersion3 ( PGconn conn)

Definition at line 1408 of file fe-protocol3.c.

1409{
1410 int tmp;
1411 ProtocolVersion their_version;
1412 int num;
1414
1415 if (pqGetInt(&tmp, 4, conn) != 0)
1416 return EOF;
1417 their_version = tmp;
1418
1419 if (pqGetInt(&num, 4, conn) != 0)
1420 return EOF;
1421
1423 for (int i = 0; i < num; i++)
1424 {
1425 if (pqGets(&conn->workBuffer, conn))
1426 {
1428 return EOF;
1429 }
1430 if (buf.len > 0)
1433 }
1434
1435 if (their_version < conn->pversion)
1436 libpq_append_conn_error(conn, "protocol version not supported by server: client uses %u.%u, server supports up to %u.%u",
1438 PG_PROTOCOL_MAJOR(their_version), PG_PROTOCOL_MINOR(their_version));
1439 if (num > 0)
1440 {
1442 libpq_ngettext("protocol extension not supported by server: %s",
1443 "protocol extensions not supported by server: %s", num),
1444 buf.data);
1446 }
1447
1448 /* neither -- server shouldn't have sent it */
1449 if (!(their_version < conn->pversion) && !(num > 0))
1450 libpq_append_conn_error(conn, "invalid %s message", "NegotiateProtocolVersion");
1451
1453 return 0;
1454}
#define libpq_ngettext(s, p, n)
Definition: libpq-int.h:916
static char * buf
Definition: pg_test_fsync.c:72
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:87
#define PG_PROTOCOL_MINOR(v)
Definition: pqcomm.h:88

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), buf, conn, PQExpBufferData::data, pg_conn::errorMessage, i, initPQExpBuffer(), libpq_append_conn_error(), libpq_ngettext, PG_PROTOCOL_MAJOR, PG_PROTOCOL_MINOR, pqGetInt(), pqGets(), pg_conn::pversion, termPQExpBuffer(), and pg_conn::workBuffer.

Referenced by PQconnectPoll().

◆ pqParseInput3()

void pqParseInput3 ( PGconn conn)

Definition at line 66 of file fe-protocol3.c.

67{
68 char id;
69 int msgLength;
70 int avail;
71
72 /*
73 * Loop to parse successive complete messages available in the buffer.
74 */
75 for (;;)
76 {
77 /*
78 * Try to read a message. First get the type code and length. Return
79 * if not enough data.
80 */
82 if (pqGetc(&id, conn))
83 return;
84 if (pqGetInt(&msgLength, 4, conn))
85 return;
86
87 /*
88 * Try to validate message type/length here. A length less than 4 is
89 * definitely broken. Large lengths should only be believed for a few
90 * message types.
91 */
92 if (msgLength < 4)
93 {
94 handleSyncLoss(conn, id, msgLength);
95 return;
96 }
97 if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
98 {
99 handleSyncLoss(conn, id, msgLength);
100 return;
101 }
102
103 /*
104 * Can't process if message body isn't all here yet.
105 */
106 msgLength -= 4;
107 avail = conn->inEnd - conn->inCursor;
108 if (avail < msgLength)
109 {
110 /*
111 * Before returning, enlarge the input buffer if needed to hold
112 * the whole message. This is better than leaving it to
113 * pqReadData because we can avoid multiple cycles of realloc()
114 * when the message is large; also, we can implement a reasonable
115 * recovery strategy if we are unable to make the buffer big
116 * enough.
117 */
118 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
119 conn))
120 {
121 /*
122 * XXX add some better recovery code... plan is to skip over
123 * the message using its length, then report an error. For the
124 * moment, just treat this like loss of sync (which indeed it
125 * might be!)
126 */
127 handleSyncLoss(conn, id, msgLength);
128 }
129 return;
130 }
131
132 /*
133 * NOTIFY and NOTICE messages can happen in any state; always process
134 * them right away.
135 *
136 * Most other messages should only be processed while in BUSY state.
137 * (In particular, in READY state we hold off further parsing until
138 * the application collects the current PGresult.)
139 *
140 * However, if the state is IDLE then we got trouble; we need to deal
141 * with the unexpected message somehow.
142 *
143 * ParameterStatus ('S') messages are a special case: in IDLE state we
144 * must process 'em (this case could happen if a new value was adopted
145 * from config file due to SIGHUP), but otherwise we hold off until
146 * BUSY state.
147 */
149 {
150 if (getNotify(conn))
151 return;
152 }
153 else if (id == PqMsg_NoticeResponse)
154 {
155 if (pqGetErrorNotice3(conn, false))
156 return;
157 }
158 else if (conn->asyncStatus != PGASYNC_BUSY)
159 {
160 /* If not IDLE state, just wait ... */
162 return;
163
164 /*
165 * Unexpected message in IDLE state; need to recover somehow.
166 * ERROR messages are handled using the notice processor;
167 * ParameterStatus is handled normally; anything else is just
168 * dropped on the floor after displaying a suitable warning
169 * notice. (An ERROR is very possibly the backend telling us why
170 * it is about to close the connection, so we don't want to just
171 * discard it...)
172 */
173 if (id == PqMsg_ErrorResponse)
174 {
175 if (pqGetErrorNotice3(conn, false /* treat as notice */ ))
176 return;
177 }
178 else if (id == PqMsg_ParameterStatus)
179 {
181 return;
182 }
183 else
184 {
185 /* Any other case is unexpected and we summarily skip it */
187 "message type 0x%02x arrived from server while idle",
188 id);
189 /* Discard the unexpected message */
190 conn->inCursor += msgLength;
191 }
192 }
193 else
194 {
195 /*
196 * In BUSY state, we can process everything.
197 */
198 switch (id)
199 {
201 if (pqGets(&conn->workBuffer, conn))
202 return;
204 {
207 if (!conn->result)
208 {
209 libpq_append_conn_error(conn, "out of memory");
211 }
212 }
213 if (conn->result)
217 break;
219 if (pqGetErrorNotice3(conn, true))
220 return;
222 break;
225 return;
227 {
230 if (!conn->result)
231 {
232 libpq_append_conn_error(conn, "out of memory");
234 }
235 else
236 {
239 }
240 }
241 else
242 {
243 /* Advance the command queue and set us idle */
244 pqCommandQueueAdvance(conn, true, false);
246 }
247 break;
250 {
253 if (!conn->result)
254 {
255 libpq_append_conn_error(conn, "out of memory");
257 }
258 }
260 break;
262 /* If we're doing PQprepare, we're done; else ignore */
263 if (conn->cmd_queue_head &&
265 {
267 {
270 if (!conn->result)
271 {
272 libpq_append_conn_error(conn, "out of memory");
274 }
275 }
277 }
278 break;
280 /* Nothing to do for this message type */
281 break;
283 /* If we're doing PQsendClose, we're done; else ignore */
284 if (conn->cmd_queue_head &&
286 {
288 {
291 if (!conn->result)
292 {
293 libpq_append_conn_error(conn, "out of memory");
295 }
296 }
298 }
299 break;
302 return;
303 break;
305
306 /*
307 * This is expected only during backend startup, but it's
308 * just as easy to handle it as part of the main loop.
309 * Save the data and continue processing.
310 */
311 if (pqGetInt(&(conn->be_pid), 4, conn))
312 return;
313 if (pqGetInt(&(conn->be_key), 4, conn))
314 return;
315 break;
317 if (conn->error_result ||
318 (conn->result != NULL &&
320 {
321 /*
322 * We've already choked for some reason. Just discard
323 * the data till we get to the end of the query.
324 */
325 conn->inCursor += msgLength;
326 }
327 else if (conn->result == NULL ||
330 {
331 /* First 'T' in a query sequence */
332 if (getRowDescriptions(conn, msgLength))
333 return;
334 }
335 else
336 {
337 /*
338 * A new 'T' message is treated as the start of
339 * another PGresult. (It is not clear that this is
340 * really possible with the current backend.) We stop
341 * parsing until the application accepts the current
342 * result.
343 */
345 return;
346 }
347 break;
348 case PqMsg_NoData:
349
350 /*
351 * NoData indicates that we will not be seeing a
352 * RowDescription message because the statement or portal
353 * inquired about doesn't return rows.
354 *
355 * If we're doing a Describe, we have to pass something
356 * back to the client, so set up a COMMAND_OK result,
357 * instead of PGRES_TUPLES_OK. Otherwise we can just
358 * ignore this message.
359 */
360 if (conn->cmd_queue_head &&
362 {
364 {
367 if (!conn->result)
368 {
369 libpq_append_conn_error(conn, "out of memory");
371 }
372 }
374 }
375 break;
377 if (getParamDescriptions(conn, msgLength))
378 return;
379 break;
380 case PqMsg_DataRow:
381 if (conn->result != NULL &&
384 {
385 /* Read another tuple of a normal query response */
386 if (getAnotherTuple(conn, msgLength))
387 return;
388 }
389 else if (conn->error_result ||
390 (conn->result != NULL &&
392 {
393 /*
394 * We've already choked for some reason. Just discard
395 * tuples till we get to the end of the query.
396 */
397 conn->inCursor += msgLength;
398 }
399 else
400 {
401 /* Set up to report error at end of query */
402 libpq_append_conn_error(conn, "server sent data (\"D\" message) without prior row description (\"T\" message)");
404 /* Discard the unexpected message */
405 conn->inCursor += msgLength;
406 }
407 break;
410 return;
412 break;
415 return;
418 break;
421 return;
424 break;
425 case PqMsg_CopyData:
426
427 /*
428 * If we see Copy Data, just silently drop it. This would
429 * only occur if application exits COPY OUT mode too
430 * early.
431 */
432 conn->inCursor += msgLength;
433 break;
434 case PqMsg_CopyDone:
435
436 /*
437 * If we see Copy Done, just silently drop it. This is
438 * the normal case during PQendcopy. We will keep
439 * swallowing data, expecting to see command-complete for
440 * the COPY command.
441 */
442 break;
443 default:
444 libpq_append_conn_error(conn, "unexpected response from server; first received character was \"%c\"", id);
445 /* build an error result holding the error message */
447 /* not sure if we will see more, so go to ready state */
449 /* Discard the unexpected message */
450 conn->inCursor += msgLength;
451 break;
452 } /* switch on protocol character */
453 }
454 /* Successfully consumed this message */
455 if (conn->inCursor == conn->inStart + 5 + msgLength)
456 {
457 /* Normal case: parsing agrees with specified length */
459 }
460 else
461 {
462 /* Trouble --- report it */
463 libpq_append_conn_error(conn, "message contents do not agree with length in message type \"%c\"", id);
464 /* build an error result holding the error message */
467 /* trust the specified message length as what to skip */
468 conn->inStart += 5 + msgLength;
469 }
470 }
471}
void pqCommandQueueAdvance(PGconn *conn, bool isReadyForQuery, bool gotSync)
Definition: fe-exec.c:3142
static int getAnotherTuple(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:758
static int getRowDescriptions(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:499
static int getCopyStart(PGconn *conn, ExecStatusType copytype)
static int getParamDescriptions(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:670
@ PGRES_COPY_IN
Definition: libpq-fe.h:127
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:132
@ PGRES_TUPLES_CHUNK
Definition: libpq-fe.h:137
@ PGRES_COPY_OUT
Definition: libpq-fe.h:126
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:134
@ PQ_PIPELINE_ON
Definition: libpq-fe.h:183
@ PGASYNC_IDLE
Definition: libpq-int.h:223
@ PGQUERY_CLOSE
Definition: libpq-int.h:333
@ PGQUERY_PREPARE
Definition: libpq-int.h:330
#define CMDSTATUS_LEN
Definition: libpq-int.h:91
#define PqMsg_CloseComplete
Definition: protocol.h:40
#define PqMsg_BindComplete
Definition: protocol.h:39
#define PqMsg_ParameterDescription
Definition: protocol.h:58
#define PqMsg_ReadyForQuery
Definition: protocol.h:55
#define PqMsg_CopyInResponse
Definition: protocol.h:45
#define PqMsg_EmptyQueryResponse
Definition: protocol.h:47
#define PqMsg_CopyBothResponse
Definition: protocol.h:54
#define PqMsg_NoData
Definition: protocol.h:56
#define PqMsg_BackendKeyData
Definition: protocol.h:48
#define PqMsg_CommandComplete
Definition: protocol.h:42
#define PqMsg_CopyOutResponse
Definition: protocol.h:46
#define PqMsg_ParseComplete
Definition: protocol.h:38
int be_pid
Definition: libpq-int.h:531
int be_key
Definition: libpq-int.h:532
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:183

References pg_conn::asyncStatus, pg_conn::be_key, pg_conn::be_pid, pg_conn::cmd_queue_head, pg_result::cmdStatus, CMDSTATUS_LEN, conn, pg_conn::copy_already_done, PQExpBufferData::data, pg_conn::error_result, getAnotherTuple(), getCopyStart(), getNotify(), getParamDescriptions(), getParameterStatus(), getReadyForQuery(), getRowDescriptions(), handleSyncLoss(), pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, libpq_append_conn_error(), pg_conn::noticeHooks, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_READY, pgHavePendingResult, PGQUERY_CLOSE, PGQUERY_DESCRIBE, PGQUERY_PREPARE, PGRES_COMMAND_OK, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PGRES_PIPELINE_SYNC, PGRES_TUPLES_CHUNK, PGRES_TUPLES_OK, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, PQ_PIPELINE_ON, pqCheckInBufferSpace(), pqCommandQueueAdvance(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGets(), pqInternalNotice(), PQmakeEmptyPGresult(), PqMsg_BackendKeyData, PqMsg_BindComplete, PqMsg_CloseComplete, PqMsg_CommandComplete, PqMsg_CopyBothResponse, PqMsg_CopyData, PqMsg_CopyDone, PqMsg_CopyInResponse, PqMsg_CopyOutResponse, PqMsg_DataRow, PqMsg_EmptyQueryResponse, PqMsg_ErrorResponse, PqMsg_NoData, PqMsg_NoticeResponse, PqMsg_NotificationResponse, PqMsg_ParameterDescription, PqMsg_ParameterStatus, PqMsg_ParseComplete, PqMsg_ReadyForQuery, PqMsg_RowDescription, pqParseDone(), pqSaveErrorResult(), PGcmdQueueEntry::queryclass, pg_conn::result, pg_result::resultStatus, strlcpy(), VALID_LONG_MESSAGE_TYPE, and pg_conn::workBuffer.

Referenced by parseInput().

◆ reportErrorPosition()

static void reportErrorPosition ( PQExpBuffer  msg,
const char *  query,
int  loc,
int  encoding 
)
static

Definition at line 1181 of file fe-protocol3.c.

1182{
1183#define DISPLAY_SIZE 60 /* screen width limit, in screen cols */
1184#define MIN_RIGHT_CUT 10 /* try to keep this far away from EOL */
1185
1186 char *wquery;
1187 int slen,
1188 cno,
1189 i,
1190 *qidx,
1191 *scridx,
1192 qoffset,
1193 scroffset,
1194 ibeg,
1195 iend,
1196 loc_line;
1197 bool mb_encoding,
1198 beg_trunc,
1199 end_trunc;
1200
1201 /* Convert loc from 1-based to 0-based; no-op if out of range */
1202 loc--;
1203 if (loc < 0)
1204 return;
1205
1206 /* Need a writable copy of the query */
1207 wquery = strdup(query);
1208 if (wquery == NULL)
1209 return; /* fail silently if out of memory */
1210
1211 /*
1212 * Each character might occupy multiple physical bytes in the string, and
1213 * in some Far Eastern character sets it might take more than one screen
1214 * column as well. We compute the starting byte offset and starting
1215 * screen column of each logical character, and store these in qidx[] and
1216 * scridx[] respectively.
1217 */
1218
1219 /* we need a safe allocation size... */
1220 slen = strlen(wquery) + 1;
1221
1222 qidx = (int *) malloc(slen * sizeof(int));
1223 if (qidx == NULL)
1224 {
1225 free(wquery);
1226 return;
1227 }
1228 scridx = (int *) malloc(slen * sizeof(int));
1229 if (scridx == NULL)
1230 {
1231 free(qidx);
1232 free(wquery);
1233 return;
1234 }
1235
1236 /* We can optimize a bit if it's a single-byte encoding */
1237 mb_encoding = (pg_encoding_max_length(encoding) != 1);
1238
1239 /*
1240 * Within the scanning loop, cno is the current character's logical
1241 * number, qoffset is its offset in wquery, and scroffset is its starting
1242 * logical screen column (all indexed from 0). "loc" is the logical
1243 * character number of the error location. We scan to determine loc_line
1244 * (the 1-based line number containing loc) and ibeg/iend (first character
1245 * number and last+1 character number of the line containing loc). Note
1246 * that qidx[] and scridx[] are filled only as far as iend.
1247 */
1248 qoffset = 0;
1249 scroffset = 0;
1250 loc_line = 1;
1251 ibeg = 0;
1252 iend = -1; /* -1 means not set yet */
1253
1254 for (cno = 0; wquery[qoffset] != '\0'; cno++)
1255 {
1256 char ch = wquery[qoffset];
1257
1258 qidx[cno] = qoffset;
1259 scridx[cno] = scroffset;
1260
1261 /*
1262 * Replace tabs with spaces in the writable copy. (Later we might
1263 * want to think about coping with their variable screen width, but
1264 * not today.)
1265 */
1266 if (ch == '\t')
1267 wquery[qoffset] = ' ';
1268
1269 /*
1270 * If end-of-line, count lines and mark positions. Each \r or \n
1271 * counts as a line except when \r \n appear together.
1272 */
1273 else if (ch == '\r' || ch == '\n')
1274 {
1275 if (cno < loc)
1276 {
1277 if (ch == '\r' ||
1278 cno == 0 ||
1279 wquery[qidx[cno - 1]] != '\r')
1280 loc_line++;
1281 /* extract beginning = last line start before loc. */
1282 ibeg = cno + 1;
1283 }
1284 else
1285 {
1286 /* set extract end. */
1287 iend = cno;
1288 /* done scanning. */
1289 break;
1290 }
1291 }
1292
1293 /* Advance */
1294 if (mb_encoding)
1295 {
1296 int w;
1297
1298 w = pg_encoding_dsplen(encoding, &wquery[qoffset]);
1299 /* treat any non-tab control chars as width 1 */
1300 if (w <= 0)
1301 w = 1;
1302 scroffset += w;
1303 qoffset += PQmblenBounded(&wquery[qoffset], encoding);
1304 }
1305 else
1306 {
1307 /* We assume wide chars only exist in multibyte encodings */
1308 scroffset++;
1309 qoffset++;
1310 }
1311 }
1312 /* Fix up if we didn't find an end-of-line after loc */
1313 if (iend < 0)
1314 {
1315 iend = cno; /* query length in chars, +1 */
1316 qidx[iend] = qoffset;
1317 scridx[iend] = scroffset;
1318 }
1319
1320 /* Print only if loc is within computed query length */
1321 if (loc <= cno)
1322 {
1323 /* If the line extracted is too long, we truncate it. */
1324 beg_trunc = false;
1325 end_trunc = false;
1326 if (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1327 {
1328 /*
1329 * We first truncate right if it is enough. This code might be
1330 * off a space or so on enforcing MIN_RIGHT_CUT if there's a wide
1331 * character right there, but that should be okay.
1332 */
1333 if (scridx[ibeg] + DISPLAY_SIZE >= scridx[loc] + MIN_RIGHT_CUT)
1334 {
1335 while (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1336 iend--;
1337 end_trunc = true;
1338 }
1339 else
1340 {
1341 /* Truncate right if not too close to loc. */
1342 while (scridx[loc] + MIN_RIGHT_CUT < scridx[iend])
1343 {
1344 iend--;
1345 end_trunc = true;
1346 }
1347
1348 /* Truncate left if still too long. */
1349 while (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1350 {
1351 ibeg++;
1352 beg_trunc = true;
1353 }
1354 }
1355 }
1356
1357 /* truncate working copy at desired endpoint */
1358 wquery[qidx[iend]] = '\0';
1359
1360 /* Begin building the finished message. */
1361 i = msg->len;
1362 appendPQExpBuffer(msg, libpq_gettext("LINE %d: "), loc_line);
1363 if (beg_trunc)
1364 appendPQExpBufferStr(msg, "...");
1365
1366 /*
1367 * While we have the prefix in the msg buffer, compute its screen
1368 * width.
1369 */
1370 scroffset = 0;
1371 for (; i < msg->len; i += PQmblenBounded(&msg->data[i], encoding))
1372 {
1373 int w = pg_encoding_dsplen(encoding, &msg->data[i]);
1374
1375 if (w <= 0)
1376 w = 1;
1377 scroffset += w;
1378 }
1379
1380 /* Finish up the LINE message line. */
1381 appendPQExpBufferStr(msg, &wquery[qidx[ibeg]]);
1382 if (end_trunc)
1383 appendPQExpBufferStr(msg, "...");
1384 appendPQExpBufferChar(msg, '\n');
1385
1386 /* Now emit the cursor marker line. */
1387 scroffset += scridx[loc] - scridx[ibeg];
1388 for (i = 0; i < scroffset; i++)
1389 appendPQExpBufferChar(msg, ' ');
1390 appendPQExpBufferChar(msg, '^');
1391 appendPQExpBufferChar(msg, '\n');
1392 }
1393
1394 /* Clean up. */
1395 free(scridx);
1396 free(qidx);
1397 free(wquery);
1398}
int PQmblenBounded(const char *s, int encoding)
Definition: fe-misc.c:1234
#define DISPLAY_SIZE
#define MIN_RIGHT_CUT
int32 encoding
Definition: pg_database.h:41
int pg_encoding_dsplen(int encoding, const char *mbstr)
Definition: wchar.c:2090
int pg_encoding_max_length(int encoding)
Definition: wchar.c:2127

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), PQExpBufferData::data, DISPLAY_SIZE, encoding, free, i, PQExpBufferData::len, libpq_gettext, malloc, MIN_RIGHT_CUT, pg_encoding_dsplen(), pg_encoding_max_length(), and PQmblenBounded().

Referenced by pqBuildErrorMessage3().