PostgreSQL Source Code  git master
fe-protocol3.c File Reference
#include "postgres_fe.h"
#include <ctype.h>
#include <fcntl.h>
#include <unistd.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)
 
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) == 'T' || (id) == 'D' || (id) == 'd' || (id) == 'V' || \
(id) == 'E' || (id) == 'N' || (id) == 'A')

Definition at line 38 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 2220 of file fe-protocol3.c.

2222 {
2223  int packet_len = 0;
2224  const PQEnvironmentOption *next_eo;
2225  const char *val;
2226 
2227  /* Protocol version comes first. */
2228  if (packet)
2229  {
2231 
2232  memcpy(packet + packet_len, &pv, sizeof(ProtocolVersion));
2233  }
2234  packet_len += sizeof(ProtocolVersion);
2235 
2236  /* Add user name, database name, options */
2237 
2238 #define ADD_STARTUP_OPTION(optname, optval) \
2239  do { \
2240  if (packet) \
2241  strcpy(packet + packet_len, optname); \
2242  packet_len += strlen(optname) + 1; \
2243  if (packet) \
2244  strcpy(packet + packet_len, optval); \
2245  packet_len += strlen(optval) + 1; \
2246  } while(0)
2247 
2248  if (conn->pguser && conn->pguser[0])
2249  ADD_STARTUP_OPTION("user", conn->pguser);
2250  if (conn->dbName && conn->dbName[0])
2251  ADD_STARTUP_OPTION("database", conn->dbName);
2252  if (conn->replication && conn->replication[0])
2253  ADD_STARTUP_OPTION("replication", conn->replication);
2254  if (conn->pgoptions && conn->pgoptions[0])
2255  ADD_STARTUP_OPTION("options", conn->pgoptions);
2256  if (conn->send_appname)
2257  {
2258  /* Use appname if present, otherwise use fallback */
2260  if (val && val[0])
2261  ADD_STARTUP_OPTION("application_name", val);
2262  }
2263 
2265  ADD_STARTUP_OPTION("client_encoding", conn->client_encoding_initial);
2266 
2267  /* Add any environment-driven GUC settings needed */
2268  for (next_eo = options; next_eo->envName; next_eo++)
2269  {
2270  if ((val = getenv(next_eo->envName)) != NULL)
2271  {
2272  if (pg_strcasecmp(val, "default") != 0)
2273  ADD_STARTUP_OPTION(next_eo->pgName, val);
2274  }
2275  }
2276 
2277  /* Add trailing terminator */
2278  if (packet)
2279  packet[packet_len] = '\0';
2280  packet_len++;
2281 
2282  return packet_len;
2283 }
#define ADD_STARTUP_OPTION(optname, optval)
long val
Definition: informix.c:664
#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:125
PGconn * conn
Definition: streamutil.c:54
const char * pgName
Definition: libpq-int.h:255
const char * envName
Definition: libpq-int.h:254
char * replication
Definition: libpq-int.h:367
ProtocolVersion pversion
Definition: libpq-int.h:448
char * pgoptions
Definition: libpq-int.h:363
bool send_appname
Definition: libpq-int.h:464
char * dbName
Definition: libpq-int.h:366
char * fbappname
Definition: libpq-int.h:365
char * pguser
Definition: libpq-int.h:368
char * client_encoding_initial
Definition: libpq-int.h:362
char * appname
Definition: libpq-int.h:364

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 770 of file fe-protocol3.c.

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

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 1595 of file fe-protocol3.c.

1596 {
1597  char id;
1598  int msgLength;
1599  int avail;
1600 
1601  for (;;)
1602  {
1603  /*
1604  * Do we have the next input message? To make life simpler for async
1605  * callers, we keep returning 0 until the next message is fully
1606  * available, even if it is not Copy Data.
1607  */
1608  conn->inCursor = conn->inStart;
1609  if (pqGetc(&id, conn))
1610  return 0;
1611  if (pqGetInt(&msgLength, 4, conn))
1612  return 0;
1613  if (msgLength < 4)
1614  {
1615  handleSyncLoss(conn, id, msgLength);
1616  return -2;
1617  }
1618  avail = conn->inEnd - conn->inCursor;
1619  if (avail < msgLength - 4)
1620  {
1621  /*
1622  * Before returning, enlarge the input buffer if needed to hold
1623  * the whole message. See notes in parseInput.
1624  */
1625  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength - 4,
1626  conn))
1627  {
1628  /*
1629  * XXX add some better recovery code... plan is to skip over
1630  * the message using its length, then report an error. For the
1631  * moment, just treat this like loss of sync (which indeed it
1632  * might be!)
1633  */
1634  handleSyncLoss(conn, id, msgLength);
1635  return -2;
1636  }
1637  return 0;
1638  }
1639 
1640  /*
1641  * If it's a legitimate async message type, process it. (NOTIFY
1642  * messages are not currently possible here, but we handle them for
1643  * completeness.) Otherwise, if it's anything except Copy Data,
1644  * report end-of-copy.
1645  */
1646  switch (id)
1647  {
1648  case 'A': /* NOTIFY */
1649  if (getNotify(conn))
1650  return 0;
1651  break;
1652  case 'N': /* NOTICE */
1653  if (pqGetErrorNotice3(conn, false))
1654  return 0;
1655  break;
1656  case 'S': /* ParameterStatus */
1657  if (getParameterStatus(conn))
1658  return 0;
1659  break;
1660  case 'd': /* Copy Data, pass it back to caller */
1661  return msgLength;
1662  case 'c':
1663 
1664  /*
1665  * If this is a CopyDone message, exit COPY_OUT mode and let
1666  * caller read status with PQgetResult(). If we're in
1667  * COPY_BOTH mode, return to COPY_IN mode.
1668  */
1671  else
1673  return -1;
1674  default: /* treat as end of copy */
1675 
1676  /*
1677  * Any other message terminates either COPY_IN or COPY_BOTH
1678  * mode.
1679  */
1681  return -1;
1682  }
1683 
1684  /* trace server-to-client message */
1685  if (conn->Pfdebug)
1687 
1688  /* Drop the processed message and loop around for another */
1689  conn->inStart = conn->inCursor;
1690  }
1691 }
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:80
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:354
static int getNotify(PGconn *conn)
static int getParameterStatus(PGconn *conn)
static void handleSyncLoss(PGconn *conn, char id, int msgLength)
Definition: fe-protocol3.c:490
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:890
void pqTraceOutputMessage(PGconn *conn, const char *message, bool toServer)
Definition: fe-trace.c:529
@ PGASYNC_COPY_BOTH
Definition: libpq-int.h:228
@ PGASYNC_COPY_IN
Definition: libpq-int.h:226
@ PGASYNC_BUSY
Definition: libpq-int.h:220
int inEnd
Definition: libpq-int.h:483
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
FILE * Pfdebug
Definition: libpq-int.h:398

References pg_conn::asyncStatus, conn, getNotify(), getParameterStatus(), handleSyncLoss(), pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, pg_conn::Pfdebug, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, pqCheckInBufferSpace(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), and pqTraceOutputMessage().

Referenced by pqGetCopyData3(), and pqGetlineAsync3().

◆ getCopyStart()

static int getCopyStart ( PGconn conn,
ExecStatusType  copytype 
)
static

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

1508 {
1509  PGresult *result;
1510  int nfields;
1511  int i;
1512 
1513  result = PQmakeEmptyPGresult(conn, copytype);
1514  if (!result)
1515  goto failure;
1516 
1517  if (pqGetc(&conn->copy_is_binary, conn))
1518  goto failure;
1519  result->binary = conn->copy_is_binary;
1520  /* the next two bytes are the number of fields */
1521  if (pqGetInt(&(result->numAttributes), 2, conn))
1522  goto failure;
1523  nfields = result->numAttributes;
1524 
1525  /* allocate space for the attribute descriptors */
1526  if (nfields > 0)
1527  {
1528  result->attDescs = (PGresAttDesc *)
1529  pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
1530  if (!result->attDescs)
1531  goto failure;
1532  MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
1533  }
1534 
1535  for (i = 0; i < nfields; i++)
1536  {
1537  int format;
1538 
1539  if (pqGetInt(&format, 2, conn))
1540  goto failure;
1541 
1542  /*
1543  * Since pqGetInt treats 2-byte integers as unsigned, we need to
1544  * coerce these results to signed form.
1545  */
1546  format = (int) ((int16) format);
1547  result->attDescs[i].format = format;
1548  }
1549 
1550  /* Success! */
1551  conn->result = result;
1552  return 0;
1553 
1554 failure:
1555  PQclear(result);
1556  return EOF;
1557 }
signed short int16
Definition: c.h:428
#define MemSet(start, val, len)
Definition: c.h:1008
void PQclear(PGresult *res)
Definition: fe-exec.c:718
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:157
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:560
static char format
char copy_is_binary
Definition: libpq-int.h:419
int binary
Definition: libpq-int.h:180
PGresAttDesc * attDescs
Definition: libpq-int.h:172

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 1451 of file fe-protocol3.c.

1452 {
1453  int be_pid;
1454  char *svname;
1455  int nmlen;
1456  int extralen;
1457  PGnotify *newNotify;
1458 
1459  if (pqGetInt(&be_pid, 4, conn))
1460  return EOF;
1461  if (pqGets(&conn->workBuffer, conn))
1462  return EOF;
1463  /* must save name while getting extra string */
1464  svname = strdup(conn->workBuffer.data);
1465  if (!svname)
1466  return EOF;
1467  if (pqGets(&conn->workBuffer, conn))
1468  {
1469  free(svname);
1470  return EOF;
1471  }
1472 
1473  /*
1474  * Store the strings right after the PQnotify structure so it can all be
1475  * freed at once. We don't use NAMEDATALEN because we don't want to tie
1476  * this interface to a specific server name length.
1477  */
1478  nmlen = strlen(svname);
1479  extralen = strlen(conn->workBuffer.data);
1480  newNotify = (PGnotify *) malloc(sizeof(PGnotify) + nmlen + extralen + 2);
1481  if (newNotify)
1482  {
1483  newNotify->relname = (char *) newNotify + sizeof(PGnotify);
1484  strcpy(newNotify->relname, svname);
1485  newNotify->extra = newNotify->relname + nmlen + 1;
1486  strcpy(newNotify->extra, conn->workBuffer.data);
1487  newNotify->be_pid = be_pid;
1488  newNotify->next = NULL;
1489  if (conn->notifyTail)
1490  conn->notifyTail->next = newNotify;
1491  else
1492  conn->notifyHead = newNotify;
1493  conn->notifyTail = newNotify;
1494  }
1495 
1496  free(svname);
1497  return 0;
1498 }
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:139
#define free(a)
Definition: header.h:65
#define malloc(a)
Definition: header.h:50
struct pgNotify * next
Definition: libpq-fe.h:193
int be_pid
Definition: libpq-fe.h:190
char * relname
Definition: libpq-fe.h:189
char * extra
Definition: libpq-fe.h:191
PGnotify * notifyHead
Definition: libpq-int.h:421
PGnotify * notifyTail
Definition: libpq-int.h:422
PQExpBufferData workBuffer
Definition: libpq-int.h:589

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 682 of file fe-protocol3.c.

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

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 1422 of file fe-protocol3.c.

1423 {
1424  PQExpBufferData valueBuf;
1425 
1426  /* Get the parameter name */
1427  if (pqGets(&conn->workBuffer, conn))
1428  return EOF;
1429  /* Get the parameter value (could be large) */
1430  initPQExpBuffer(&valueBuf);
1431  if (pqGets(&valueBuf, conn))
1432  {
1433  termPQExpBuffer(&valueBuf);
1434  return EOF;
1435  }
1436  /* And save it */
1438  termPQExpBuffer(&valueBuf);
1439  return 0;
1440 }
void pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
Definition: fe-exec.c:1082
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131

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 1563 of file fe-protocol3.c.

1564 {
1565  char xact_status;
1566 
1567  if (pqGetc(&xact_status, conn))
1568  return EOF;
1569  switch (xact_status)
1570  {
1571  case 'I':
1573  break;
1574  case 'T':
1576  break;
1577  case 'E':
1579  break;
1580  default:
1582  break;
1583  }
1584 
1585  return 0;
1586 }
@ PQTRANS_INTRANS
Definition: libpq-fe.h:120
@ PQTRANS_IDLE
Definition: libpq-fe.h:118
@ PQTRANS_UNKNOWN
Definition: libpq-fe.h:122
@ PQTRANS_INERROR
Definition: libpq-fe.h:121
PGTransactionStatusType xactStatus
Definition: libpq-int.h:412

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 511 of file fe-protocol3.c.

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

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 490 of file fe-protocol3.c.

491 {
493  libpq_gettext("lost synchronization with server: got message type \"%c\", length %d\n"),
494  id, msgLength);
495  /* build an error result holding the error message */
497  conn->asyncStatus = PGASYNC_READY; /* drop out of PQgetResult wait loop */
498  /* flush input data since we're giving up on processing it */
499  pqDropConnection(conn, true);
500  conn->status = CONNECTION_BAD; /* No more connection to backend */
501 }
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:449
@ CONNECTION_BAD
Definition: libpq-fe.h:61
ConnStatusType status
Definition: libpq-int.h:410

References appendPQExpBuffer(), pg_conn::asyncStatus, conn, CONNECTION_BAD, pg_conn::errorMessage, libpq_gettext, 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 1023 of file fe-protocol3.c.

1025 {
1026  const char *val;
1027  const char *querytext = NULL;
1028  int querypos = 0;
1029 
1030  /* If we couldn't allocate a PGresult, just say "out of memory" */
1031  if (res == NULL)
1032  {
1033  appendPQExpBufferStr(msg, libpq_gettext("out of memory\n"));
1034  return;
1035  }
1036 
1037  /*
1038  * If we don't have any broken-down fields, just return the base message.
1039  * This mainly applies if we're given a libpq-generated error result.
1040  */
1041  if (res->errFields == NULL)
1042  {
1043  if (res->errMsg && res->errMsg[0])
1045  else
1046  appendPQExpBufferStr(msg, libpq_gettext("no error message available\n"));
1047  return;
1048  }
1049 
1050  /* Else build error message from relevant fields */
1052  if (val)
1053  appendPQExpBuffer(msg, "%s: ", val);
1054 
1055  if (verbosity == PQERRORS_SQLSTATE)
1056  {
1057  /*
1058  * If we have a SQLSTATE, print that and nothing else. If not (which
1059  * shouldn't happen for server-generated errors, but might possibly
1060  * happen for libpq-generated ones), fall back to TERSE format, as
1061  * that seems better than printing nothing at all.
1062  */
1064  if (val)
1065  {
1066  appendPQExpBuffer(msg, "%s\n", val);
1067  return;
1068  }
1069  verbosity = PQERRORS_TERSE;
1070  }
1071 
1072  if (verbosity == PQERRORS_VERBOSE)
1073  {
1075  if (val)
1076  appendPQExpBuffer(msg, "%s: ", val);
1077  }
1079  if (val)
1080  appendPQExpBufferStr(msg, val);
1082  if (val)
1083  {
1084  if (verbosity != PQERRORS_TERSE && res->errQuery != NULL)
1085  {
1086  /* emit position as a syntax cursor display */
1087  querytext = res->errQuery;
1088  querypos = atoi(val);
1089  }
1090  else
1091  {
1092  /* emit position as text addition to primary message */
1093  /* translator: %s represents a digit string */
1094  appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1095  val);
1096  }
1097  }
1098  else
1099  {
1101  if (val)
1102  {
1104  if (verbosity != PQERRORS_TERSE && querytext != NULL)
1105  {
1106  /* emit position as a syntax cursor display */
1107  querypos = atoi(val);
1108  }
1109  else
1110  {
1111  /* emit position as text addition to primary message */
1112  /* translator: %s represents a digit string */
1113  appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1114  val);
1115  }
1116  }
1117  }
1118  appendPQExpBufferChar(msg, '\n');
1119  if (verbosity != PQERRORS_TERSE)
1120  {
1121  if (querytext && querypos > 0)
1122  reportErrorPosition(msg, querytext, querypos,
1123  res->client_encoding);
1125  if (val)
1126  appendPQExpBuffer(msg, libpq_gettext("DETAIL: %s\n"), val);
1128  if (val)
1129  appendPQExpBuffer(msg, libpq_gettext("HINT: %s\n"), val);
1131  if (val)
1132  appendPQExpBuffer(msg, libpq_gettext("QUERY: %s\n"), val);
1133  if (show_context == PQSHOW_CONTEXT_ALWAYS ||
1134  (show_context == PQSHOW_CONTEXT_ERRORS &&
1136  {
1138  if (val)
1139  appendPQExpBuffer(msg, libpq_gettext("CONTEXT: %s\n"),
1140  val);
1141  }
1142  }
1143  if (verbosity == PQERRORS_VERBOSE)
1144  {
1146  if (val)
1147  appendPQExpBuffer(msg,
1148  libpq_gettext("SCHEMA NAME: %s\n"), val);
1150  if (val)
1151  appendPQExpBuffer(msg,
1152  libpq_gettext("TABLE NAME: %s\n"), val);
1154  if (val)
1155  appendPQExpBuffer(msg,
1156  libpq_gettext("COLUMN NAME: %s\n"), val);
1158  if (val)
1159  appendPQExpBuffer(msg,
1160  libpq_gettext("DATATYPE NAME: %s\n"), val);
1162  if (val)
1163  appendPQExpBuffer(msg,
1164  libpq_gettext("CONSTRAINT NAME: %s\n"), val);
1165  }
1166  if (verbosity == PQERRORS_VERBOSE)
1167  {
1168  const char *valf;
1169  const char *vall;
1170 
1174  if (val || valf || vall)
1175  {
1176  appendPQExpBufferStr(msg, libpq_gettext("LOCATION: "));
1177  if (val)
1178  appendPQExpBuffer(msg, libpq_gettext("%s, "), val);
1179  if (valf && vall) /* unlikely we'd have just one */
1180  appendPQExpBuffer(msg, libpq_gettext("%s:%s"),
1181  valf, vall);
1182  appendPQExpBufferChar(msg, '\n');
1183  }
1184  }
1185 }
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3325
static void reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding)
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:108
@ PQSHOW_CONTEXT_ALWAYS
Definition: libpq-fe.h:137
@ PQSHOW_CONTEXT_ERRORS
Definition: libpq-fe.h:136
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:129
@ PQERRORS_TERSE
Definition: libpq-fe.h:127
@ PQERRORS_SQLSTATE
Definition: libpq-fe.h:130
#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:380
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
char * errMsg
Definition: libpq-int.h:197
PGMessageField * errFields
Definition: libpq-int.h:198
ExecStatusType resultStatus
Definition: libpq-int.h:178
char * errQuery
Definition: libpq-int.h:199
int client_encoding
Definition: libpq-int.h:190

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 2197 of file fe-protocol3.c.

2199 {
2200  char *startpacket;
2201 
2202  *packetlen = build_startup_packet(conn, NULL, options);
2203  startpacket = (char *) malloc(*packetlen);
2204  if (!startpacket)
2205  return NULL;
2206  *packetlen = build_startup_packet(conn, startpacket, options);
2207  return startpacket;
2208 }
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 1871 of file fe-protocol3.c.

1872 {
1873  PGresult *result;
1874 
1875  if (conn->asyncStatus != PGASYNC_COPY_IN &&
1878  {
1880  libpq_gettext("no COPY in progress\n"));
1881  return 1;
1882  }
1883 
1884  /* Send the CopyDone message if needed */
1885  if (conn->asyncStatus == PGASYNC_COPY_IN ||
1887  {
1888  if (pqPutMsgStart('c', conn) < 0 ||
1889  pqPutMsgEnd(conn) < 0)
1890  return 1;
1891 
1892  /*
1893  * If we sent the COPY command in extended-query mode, we must issue a
1894  * Sync as well.
1895  */
1896  if (conn->cmd_queue_head &&
1898  {
1899  if (pqPutMsgStart('S', conn) < 0 ||
1900  pqPutMsgEnd(conn) < 0)
1901  return 1;
1902  }
1903  }
1904 
1905  /*
1906  * make sure no data is waiting to be sent, abort if we are non-blocking
1907  * and the flush fails
1908  */
1909  if (pqFlush(conn) && pqIsnonblocking(conn))
1910  return 1;
1911 
1912  /* Return to active duty */
1914 
1915  /*
1916  * Non blocking connections may have to abort at this point. If everyone
1917  * played the game there should be no problem, but in error scenarios the
1918  * expected messages may not have arrived yet. (We are assuming that the
1919  * backend's packetizing will ensure that CommandComplete arrives along
1920  * with the CopyDone; are there corner cases where that doesn't happen?)
1921  */
1922  if (pqIsnonblocking(conn) && PQisBusy(conn))
1923  return 1;
1924 
1925  /* Wait for the completion response */
1926  result = PQgetResult(conn);
1927 
1928  /* Expecting a successful result */
1929  if (result && result->resultStatus == PGRES_COMMAND_OK)
1930  {
1931  PQclear(result);
1932  return 0;
1933  }
1934 
1935  /*
1936  * Trouble. For backwards-compatibility reasons, we issue the error
1937  * message as if it were a notice (would be nice to get rid of this
1938  * silliness, but too many apps probably don't handle errors from
1939  * PQendcopy reasonably). Note that the app can still obtain the error
1940  * status from the PGconn object.
1941  */
1942  if (conn->errorMessage.len > 0)
1943  {
1944  /* We have to strip the trailing newline ... pain in neck... */
1945  char svLast = conn->errorMessage.data[conn->errorMessage.len - 1];
1946 
1947  if (svLast == '\n')
1948  conn->errorMessage.data[conn->errorMessage.len - 1] = '\0';
1950  conn->errorMessage.data[conn->errorMessage.len - 1] = svLast;
1951  }
1952 
1953  PQclear(result);
1954 
1955  return 1;
1956 }
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:939
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2051
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2082
int pqFlush(PGconn *conn)
Definition: fe-misc.c:958
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
@ PGASYNC_COPY_OUT
Definition: libpq-int.h:227
@ PGQUERY_SIMPLE
Definition: libpq-int.h:310
#define pqIsnonblocking(conn)
Definition: libpq-int.h:867
PGNoticeHooks noticeHooks
Definition: libpq-int.h:402

References appendPQExpBufferStr(), pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, PQExpBufferData::data, pg_conn::errorMessage, PQExpBufferData::len, libpq_gettext, 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, 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 1965 of file fe-protocol3.c.

1969 {
1970  bool needInput = false;
1972  char id;
1973  int msgLength;
1974  int avail;
1975  int i;
1976 
1977  /* already validated by PQfn */
1979 
1980  /* PQfn already validated connection state */
1981 
1982  if (pqPutMsgStart('F', conn) < 0 || /* function call msg */
1983  pqPutInt(fnid, 4, conn) < 0 || /* function id */
1984  pqPutInt(1, 2, conn) < 0 || /* # of format codes */
1985  pqPutInt(1, 2, conn) < 0 || /* format code: BINARY */
1986  pqPutInt(nargs, 2, conn) < 0) /* # of args */
1987  {
1988  /* error message should be set up already */
1989  return NULL;
1990  }
1991 
1992  for (i = 0; i < nargs; ++i)
1993  { /* len.int4 + contents */
1994  if (pqPutInt(args[i].len, 4, conn))
1995  return NULL;
1996  if (args[i].len == -1)
1997  continue; /* it's NULL */
1998 
1999  if (args[i].isint)
2000  {
2001  if (pqPutInt(args[i].u.integer, args[i].len, conn))
2002  return NULL;
2003  }
2004  else
2005  {
2006  if (pqPutnchar((char *) args[i].u.ptr, args[i].len, conn))
2007  return NULL;
2008  }
2009  }
2010 
2011  if (pqPutInt(1, 2, conn) < 0) /* result format code: BINARY */
2012  return NULL;
2013 
2014  if (pqPutMsgEnd(conn) < 0 ||
2015  pqFlush(conn))
2016  return NULL;
2017 
2018  for (;;)
2019  {
2020  if (needInput)
2021  {
2022  /* Wait for some data to arrive (or for the channel to close) */
2023  if (pqWait(true, false, conn) ||
2024  pqReadData(conn) < 0)
2025  break;
2026  }
2027 
2028  /*
2029  * Scan the message. If we run out of data, loop around to try again.
2030  */
2031  needInput = true;
2032 
2033  conn->inCursor = conn->inStart;
2034  if (pqGetc(&id, conn))
2035  continue;
2036  if (pqGetInt(&msgLength, 4, conn))
2037  continue;
2038 
2039  /*
2040  * Try to validate message type/length here. A length less than 4 is
2041  * definitely broken. Large lengths should only be believed for a few
2042  * message types.
2043  */
2044  if (msgLength < 4)
2045  {
2046  handleSyncLoss(conn, id, msgLength);
2047  break;
2048  }
2049  if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
2050  {
2051  handleSyncLoss(conn, id, msgLength);
2052  break;
2053  }
2054 
2055  /*
2056  * Can't process if message body isn't all here yet.
2057  */
2058  msgLength -= 4;
2059  avail = conn->inEnd - conn->inCursor;
2060  if (avail < msgLength)
2061  {
2062  /*
2063  * Before looping, enlarge the input buffer if needed to hold the
2064  * whole message. See notes in parseInput.
2065  */
2066  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
2067  conn))
2068  {
2069  /*
2070  * XXX add some better recovery code... plan is to skip over
2071  * the message using its length, then report an error. For the
2072  * moment, just treat this like loss of sync (which indeed it
2073  * might be!)
2074  */
2075  handleSyncLoss(conn, id, msgLength);
2076  break;
2077  }
2078  continue;
2079  }
2080 
2081  /*
2082  * We should see V or E response to the command, but might get N
2083  * and/or A notices first. We also need to swallow the final Z before
2084  * returning.
2085  */
2086  switch (id)
2087  {
2088  case 'V': /* function result */
2089  if (pqGetInt(actual_result_len, 4, conn))
2090  continue;
2091  if (*actual_result_len != -1)
2092  {
2093  if (result_is_int)
2094  {
2095  if (pqGetInt(result_buf, *actual_result_len, conn))
2096  continue;
2097  }
2098  else
2099  {
2100  if (pqGetnchar((char *) result_buf,
2101  *actual_result_len,
2102  conn))
2103  continue;
2104  }
2105  }
2106  /* correctly finished function result message */
2108  break;
2109  case 'E': /* error return */
2110  if (pqGetErrorNotice3(conn, true))
2111  continue;
2113  break;
2114  case 'A': /* notify message */
2115  /* handle notify and go back to processing return values */
2116  if (getNotify(conn))
2117  continue;
2118  break;
2119  case 'N': /* notice */
2120  /* handle notice and go back to processing return values */
2121  if (pqGetErrorNotice3(conn, false))
2122  continue;
2123  break;
2124  case 'Z': /* backend is ready for new query */
2125  if (getReadyForQuery(conn))
2126  continue;
2127  /* consume the message and exit */
2128  conn->inStart += 5 + msgLength;
2129 
2130  /*
2131  * If we already have a result object (probably an error), use
2132  * that. Otherwise, if we saw a function result message,
2133  * report COMMAND_OK. Otherwise, the backend violated the
2134  * protocol, so complain.
2135  */
2136  if (!pgHavePendingResult(conn))
2137  {
2138  if (status == PGRES_COMMAND_OK)
2139  {
2141  if (!conn->result)
2142  {
2144  libpq_gettext("out of memory\n"));
2146  }
2147  }
2148  else
2149  {
2151  libpq_gettext("protocol error: no function result\n"));
2153  }
2154  }
2155  return pqPrepareAsyncResult(conn);
2156  case 'S': /* parameter status */
2157  if (getParameterStatus(conn))
2158  continue;
2159  break;
2160  default:
2161  /* The backend violates the protocol. */
2163  libpq_gettext("protocol error: id=0x%x\n"),
2164  id);
2166  /* trust the specified message length as what to skip */
2167  conn->inStart += 5 + msgLength;
2168  return pqPrepareAsyncResult(conn);
2169  }
2170 
2171  /* trace server-to-client message */
2172  if (conn->Pfdebug)
2174 
2175  /* Completed this message, keep going */
2176  /* trust the specified message length as what to skip */
2177  conn->inStart += 5 + msgLength;
2178  needInput = false;
2179  }
2180 
2181  /*
2182  * We fall out of the loop only upon failing to read data.
2183  * conn->errorMessage has been set by pqWait or pqReadData. We want to
2184  * append it to any already-received error message.
2185  */
2187  return pqPrepareAsyncResult(conn);
2188 }
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:851
int pqReadData(PGconn *conn)
Definition: fe-misc.c:568
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:256
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:168
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:983
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:205
#define VALID_LONG_MESSAGE_TYPE(id)
Definition: fe-protocol3.c:38
static int getReadyForQuery(PGconn *conn)
ExecStatusType
Definition: libpq-fe.h:95
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:158
#define pgHavePendingResult(conn)
Definition: libpq-int.h:860
Assert(fmt[strlen(fmt) - 1] !='\n')
const void size_t len
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:229
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:417

References appendPQExpBuffer(), appendPQExpBufferStr(), generate_unaccent_rules::args, Assert(), conn, pg_conn::errorMessage, getNotify(), getParameterStatus(), getReadyForQuery(), handleSyncLoss(), i, pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, len, libpq_gettext, pg_conn::Pfdebug, pgHavePendingResult, PGRES_COMMAND_OK, PGRES_FATAL_ERROR, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqCheckInBufferSpace(), pqFlush(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGetnchar(), PQmakeEmptyPGresult(), pqPrepareAsyncResult(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), pqReadData(), pqSaveErrorResult(), pqTraceOutputMessage(), pqWait(), pg_conn::result, status(), and VALID_LONG_MESSAGE_TYPE.

Referenced by PQfn().

◆ pqGetCopyData3()

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

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

1705 {
1706  int msgLength;
1707 
1708  for (;;)
1709  {
1710  /*
1711  * Collect the next input message. To make life simpler for async
1712  * callers, we keep returning 0 until the next message is fully
1713  * available, even if it is not Copy Data.
1714  */
1715  msgLength = getCopyDataMessage(conn);
1716  if (msgLength < 0)
1717  return msgLength; /* end-of-copy or error */
1718  if (msgLength == 0)
1719  {
1720  /* Don't block if async read requested */
1721  if (async)
1722  return 0;
1723  /* Need to load more data */
1724  if (pqWait(true, false, conn) ||
1725  pqReadData(conn) < 0)
1726  return -2;
1727  continue;
1728  }
1729 
1730  /*
1731  * Drop zero-length messages (shouldn't happen anyway). Otherwise
1732  * pass the data back to the caller.
1733  */
1734  msgLength -= 4;
1735  if (msgLength > 0)
1736  {
1737  *buffer = (char *) malloc(msgLength + 1);
1738  if (*buffer == NULL)
1739  {
1741  libpq_gettext("out of memory\n"));
1742  return -2;
1743  }
1744  memcpy(*buffer, &conn->inBuffer[conn->inCursor], msgLength);
1745  (*buffer)[msgLength] = '\0'; /* Add terminating null */
1746 
1747  /* Mark message consumed */
1748  conn->inStart = conn->inCursor + msgLength;
1749 
1750  return msgLength;
1751  }
1752 
1753  /* Empty, so drop it and loop around for another */
1754  conn->inStart = conn->inCursor;
1755  }
1756 }
static int getCopyDataMessage(PGconn *conn)

References appendPQExpBufferStr(), conn, pg_conn::errorMessage, getCopyDataMessage(), pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inStart, libpq_gettext, malloc, pqReadData(), and pqWait().

Referenced by PQgetCopyData().

◆ pqGetErrorNotice3()

int pqGetErrorNotice3 ( PGconn conn,
bool  isError 
)

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

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

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_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 1764 of file fe-protocol3.c.

1765 {
1766  int status;
1767 
1768  if (conn->sock == PGINVALID_SOCKET ||
1772  {
1774  libpq_gettext("PQgetline: not doing text COPY OUT\n"));
1775  *s = '\0';
1776  return EOF;
1777  }
1778 
1779  while ((status = PQgetlineAsync(conn, s, maxlen - 1)) == 0)
1780  {
1781  /* need to load more data */
1782  if (pqWait(true, false, conn) ||
1783  pqReadData(conn) < 0)
1784  {
1785  *s = '\0';
1786  return EOF;
1787  }
1788  }
1789 
1790  if (status < 0)
1791  {
1792  /* End of copy detected; gin up old-style terminator */
1793  strcpy(s, "\\.");
1794  return 0;
1795  }
1796 
1797  /* Add null terminator, and strip trailing \n if present */
1798  if (s[status - 1] == '\n')
1799  {
1800  s[status - 1] = '\0';
1801  return 0;
1802  }
1803  else
1804  {
1805  s[status] = '\0';
1806  return 1;
1807  }
1808 }
int PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
Definition: fe-exec.c:2837
#define PGINVALID_SOCKET
Definition: port.h:31
pgsocket sock
Definition: libpq-int.h:444

References appendPQExpBufferStr(), pg_conn::asyncStatus, conn, pg_conn::copy_is_binary, pg_conn::errorMessage, libpq_gettext, PGASYNC_COPY_BOTH, PGASYNC_COPY_OUT, PGINVALID_SOCKET, PQgetlineAsync(), pqReadData(), pqWait(), pg_conn::sock, and status().

Referenced by PQgetline().

◆ pqGetlineAsync3()

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

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

1817 {
1818  int msgLength;
1819  int avail;
1820 
1823  return -1; /* we are not doing a copy... */
1824 
1825  /*
1826  * Recognize the next input message. To make life simpler for async
1827  * callers, we keep returning 0 until the next message is fully available
1828  * even if it is not Copy Data. This should keep PQendcopy from blocking.
1829  * (Note: unlike pqGetCopyData3, we do not change asyncStatus here.)
1830  */
1831  msgLength = getCopyDataMessage(conn);
1832  if (msgLength < 0)
1833  return -1; /* end-of-copy or error */
1834  if (msgLength == 0)
1835  return 0; /* no data yet */
1836 
1837  /*
1838  * Move data from libpq's buffer to the caller's. In the case where a
1839  * prior call found the caller's buffer too small, we use
1840  * conn->copy_already_done to remember how much of the row was already
1841  * returned to the caller.
1842  */
1844  avail = msgLength - 4 - conn->copy_already_done;
1845  if (avail <= bufsize)
1846  {
1847  /* Able to consume the whole message */
1848  memcpy(buffer, &conn->inBuffer[conn->inCursor], avail);
1849  /* Mark message consumed */
1850  conn->inStart = conn->inCursor + avail;
1851  /* Reset state for next time */
1852  conn->copy_already_done = 0;
1853  return avail;
1854  }
1855  else
1856  {
1857  /* We must return a partial message */
1858  memcpy(buffer, &conn->inBuffer[conn->inCursor], bufsize);
1859  /* The message is NOT consumed from libpq's buffer */
1860  conn->copy_already_done += bufsize;
1861  return bufsize;
1862  }
1863 }
int copy_already_done
Definition: libpq-int.h:420

References pg_conn::asyncStatus, 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().

◆ pqParseInput3()

void pqParseInput3 ( PGconn conn)

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

64 {
65  char id;
66  int msgLength;
67  int avail;
68 
69  /*
70  * Loop to parse successive complete messages available in the buffer.
71  */
72  for (;;)
73  {
74  /*
75  * Try to read a message. First get the type code and length. Return
76  * if not enough data.
77  */
79  if (pqGetc(&id, conn))
80  return;
81  if (pqGetInt(&msgLength, 4, conn))
82  return;
83 
84  /*
85  * Try to validate message type/length here. A length less than 4 is
86  * definitely broken. Large lengths should only be believed for a few
87  * message types.
88  */
89  if (msgLength < 4)
90  {
91  handleSyncLoss(conn, id, msgLength);
92  return;
93  }
94  if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
95  {
96  handleSyncLoss(conn, id, msgLength);
97  return;
98  }
99 
100  /*
101  * Can't process if message body isn't all here yet.
102  */
103  msgLength -= 4;
104  avail = conn->inEnd - conn->inCursor;
105  if (avail < msgLength)
106  {
107  /*
108  * Before returning, enlarge the input buffer if needed to hold
109  * the whole message. This is better than leaving it to
110  * pqReadData because we can avoid multiple cycles of realloc()
111  * when the message is large; also, we can implement a reasonable
112  * recovery strategy if we are unable to make the buffer big
113  * enough.
114  */
115  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
116  conn))
117  {
118  /*
119  * XXX add some better recovery code... plan is to skip over
120  * the message using its length, then report an error. For the
121  * moment, just treat this like loss of sync (which indeed it
122  * might be!)
123  */
124  handleSyncLoss(conn, id, msgLength);
125  }
126  return;
127  }
128 
129  /*
130  * NOTIFY and NOTICE messages can happen in any state; always process
131  * them right away.
132  *
133  * Most other messages should only be processed while in BUSY state.
134  * (In particular, in READY state we hold off further parsing until
135  * the application collects the current PGresult.)
136  *
137  * However, if the state is IDLE then we got trouble; we need to deal
138  * with the unexpected message somehow.
139  *
140  * ParameterStatus ('S') messages are a special case: in IDLE state we
141  * must process 'em (this case could happen if a new value was adopted
142  * from config file due to SIGHUP), but otherwise we hold off until
143  * BUSY state.
144  */
145  if (id == 'A')
146  {
147  if (getNotify(conn))
148  return;
149  }
150  else if (id == 'N')
151  {
152  if (pqGetErrorNotice3(conn, false))
153  return;
154  }
155  else if (conn->asyncStatus != PGASYNC_BUSY)
156  {
157  /* If not IDLE state, just wait ... */
158  if (conn->asyncStatus != PGASYNC_IDLE)
159  return;
160 
161  /*
162  * We're also notionally not-IDLE when in pipeline mode the state
163  * says "idle" (so we have completed receiving the results of one
164  * query from the server and dispatched them to the application)
165  * but another query is queued; yield back control to caller so
166  * that they can initiate processing of the next query in the
167  * queue.
168  */
170  conn->cmd_queue_head != NULL)
171  return;
172 
173  /*
174  * Unexpected message in IDLE state; need to recover somehow.
175  * ERROR messages are handled using the notice processor;
176  * ParameterStatus is handled normally; anything else is just
177  * dropped on the floor after displaying a suitable warning
178  * notice. (An ERROR is very possibly the backend telling us why
179  * it is about to close the connection, so we don't want to just
180  * discard it...)
181  */
182  if (id == 'E')
183  {
184  if (pqGetErrorNotice3(conn, false /* treat as notice */ ))
185  return;
186  }
187  else if (id == 'S')
188  {
190  return;
191  }
192  else
193  {
194  /* Any other case is unexpected and we summarily skip it */
196  "message type 0x%02x arrived from server while idle",
197  id);
198  /* Discard the unexpected message */
199  conn->inCursor += msgLength;
200  }
201  }
202  else
203  {
204  /*
205  * In BUSY state, we can process everything.
206  */
207  switch (id)
208  {
209  case 'C': /* command complete */
210  if (pqGets(&conn->workBuffer, conn))
211  return;
213  {
216  if (!conn->result)
217  {
219  libpq_gettext("out of memory"));
221  }
222  }
223  if (conn->result)
225  CMDSTATUS_LEN);
227  break;
228  case 'E': /* error return */
229  if (pqGetErrorNotice3(conn, true))
230  return;
232  break;
233  case 'Z': /* sync response, backend is ready for new
234  * query */
235  if (getReadyForQuery(conn))
236  return;
238  {
241  if (!conn->result)
242  {
244  libpq_gettext("out of memory"));
246  }
247  else
248  {
251  }
252  }
253  else
254  {
255  /*
256  * In simple query protocol, advance the command queue
257  * (see PQgetResult).
258  */
259  if (conn->cmd_queue_head &&
263  }
264  break;
265  case 'I': /* empty query */
267  {
270  if (!conn->result)
271  {
273  libpq_gettext("out of memory"));
275  }
276  }
278  break;
279  case '1': /* Parse Complete */
280  /* If we're doing PQprepare, we're done; else ignore */
281  if (conn->cmd_queue_head &&
283  {
285  {
288  if (!conn->result)
289  {
291  libpq_gettext("out of memory"));
293  }
294  }
296  }
297  break;
298  case '2': /* Bind Complete */
299  case '3': /* Close Complete */
300  /* Nothing to do for these message types */
301  break;
302  case 'S': /* parameter status */
304  return;
305  break;
306  case 'K': /* secret key data from the backend */
307 
308  /*
309  * This is expected only during backend startup, but it's
310  * just as easy to handle it as part of the main loop.
311  * Save the data and continue processing.
312  */
313  if (pqGetInt(&(conn->be_pid), 4, conn))
314  return;
315  if (pqGetInt(&(conn->be_key), 4, conn))
316  return;
317  break;
318  case 'T': /* Row Description */
319  if (conn->error_result ||
320  (conn->result != NULL &&
322  {
323  /*
324  * We've already choked for some reason. Just discard
325  * the data till we get to the end of the query.
326  */
327  conn->inCursor += msgLength;
328  }
329  else if (conn->result == NULL ||
330  (conn->cmd_queue_head &&
332  {
333  /* First 'T' in a query sequence */
334  if (getRowDescriptions(conn, msgLength))
335  return;
336  }
337  else
338  {
339  /*
340  * A new 'T' message is treated as the start of
341  * another PGresult. (It is not clear that this is
342  * really possible with the current backend.) We stop
343  * parsing until the application accepts the current
344  * result.
345  */
347  return;
348  }
349  break;
350  case 'n': /* No Data */
351 
352  /*
353  * NoData indicates that we will not be seeing a
354  * RowDescription message because the statement or portal
355  * inquired about doesn't return rows.
356  *
357  * If we're doing a Describe, we have to pass something
358  * back to the client, so set up a COMMAND_OK result,
359  * instead of PGRES_TUPLES_OK. Otherwise we can just
360  * ignore this message.
361  */
362  if (conn->cmd_queue_head &&
364  {
366  {
369  if (!conn->result)
370  {
372  libpq_gettext("out of memory"));
374  }
375  }
377  }
378  break;
379  case 't': /* Parameter Description */
380  if (getParamDescriptions(conn, msgLength))
381  return;
382  break;
383  case 'D': /* Data Row */
384  if (conn->result != NULL &&
386  {
387  /* Read another tuple of a normal query response */
388  if (getAnotherTuple(conn, msgLength))
389  return;
390  }
391  else if (conn->error_result ||
392  (conn->result != NULL &&
394  {
395  /*
396  * We've already choked for some reason. Just discard
397  * tuples till we get to the end of the query.
398  */
399  conn->inCursor += msgLength;
400  }
401  else
402  {
403  /* Set up to report error at end of query */
405  libpq_gettext("server sent data (\"D\" message) without prior row description (\"T\" message)\n"));
407  /* Discard the unexpected message */
408  conn->inCursor += msgLength;
409  }
410  break;
411  case 'G': /* Start Copy In */
413  return;
415  break;
416  case 'H': /* Start Copy Out */
418  return;
420  conn->copy_already_done = 0;
421  break;
422  case 'W': /* Start Copy Both */
424  return;
426  conn->copy_already_done = 0;
427  break;
428  case 'd': /* Copy Data */
429 
430  /*
431  * If we see Copy Data, just silently drop it. This would
432  * only occur if application exits COPY OUT mode too
433  * early.
434  */
435  conn->inCursor += msgLength;
436  break;
437  case 'c': /* Copy Done */
438 
439  /*
440  * If we see Copy Done, just silently drop it. This is
441  * the normal case during PQendcopy. We will keep
442  * swallowing data, expecting to see command-complete for
443  * the COPY command.
444  */
445  break;
446  default:
448  libpq_gettext("unexpected response from server; first received character was \"%c\"\n"),
449  id);
450  /* build an error result holding the error message */
452  /* not sure if we will see more, so go to ready state */
454  /* Discard the unexpected message */
455  conn->inCursor += msgLength;
456  break;
457  } /* switch on protocol character */
458  }
459  /* Successfully consumed this message */
460  if (conn->inCursor == conn->inStart + 5 + msgLength)
461  {
462  /* trace server-to-client message */
463  if (conn->Pfdebug)
465 
466  /* Normal case: parsing agrees with specified length */
468  }
469  else
470  {
471  /* Trouble --- report it */
473  libpq_gettext("message contents do not agree with length in message type \"%c\"\n"),
474  id);
475  /* build an error result holding the error message */
478  /* trust the specified message length as what to skip */
479  conn->inStart += 5 + msgLength;
480  }
481  }
482 }
void pqCommandQueueAdvance(PGconn *conn)
Definition: fe-exec.c:3062
static int getAnotherTuple(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:770
static int getRowDescriptions(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:511
static int getCopyStart(PGconn *conn, ExecStatusType copytype)
static int getParamDescriptions(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:682
@ PGRES_COPY_IN
Definition: libpq-fe.h:104
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:109
@ PGRES_COPY_OUT
Definition: libpq-fe.h:103
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:111
@ PQ_PIPELINE_ON
Definition: libpq-fe.h:159
@ PGASYNC_IDLE
Definition: libpq-int.h:219
@ PGQUERY_PREPARE
Definition: libpq-int.h:312
#define CMDSTATUS_LEN
Definition: libpq-int.h:87
int be_pid
Definition: libpq-int.h:467
int be_key
Definition: libpq-int.h:468
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:179

References appendPQExpBuffer(), appendPQExpBufferStr(), 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, pg_conn::errorMessage, getAnotherTuple(), getCopyStart(), getNotify(), getParamDescriptions(), getParameterStatus(), getReadyForQuery(), getRowDescriptions(), handleSyncLoss(), pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, libpq_gettext, pg_conn::noticeHooks, pg_conn::Pfdebug, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_READY, pgHavePendingResult, PGQUERY_DESCRIBE, PGQUERY_PREPARE, PGQUERY_SIMPLE, PGRES_COMMAND_OK, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PGRES_PIPELINE_SYNC, PGRES_TUPLES_OK, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, PQ_PIPELINE_ON, pqCheckInBufferSpace(), pqCommandQueueAdvance(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGets(), pqInternalNotice(), PQmakeEmptyPGresult(), pqSaveErrorResult(), pqTraceOutputMessage(), 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 1194 of file fe-protocol3.c.

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

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().