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)

Referenced by build_startup_packet().

◆ DISPLAY_SIZE

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

Referenced by reportErrorPosition().

◆ MIN_RIGHT_CUT

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

Referenced by reportErrorPosition().

◆ 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.

Referenced by pqFunctionCall3(), and pqParseInput3().

Function Documentation

◆ build_startup_packet()

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

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

References ADD_STARTUP_OPTION, pg_conn::appname, pg_conn::client_encoding_initial, 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().

2182 {
2183  int packet_len = 0;
2184  const PQEnvironmentOption *next_eo;
2185  const char *val;
2186 
2187  /* Protocol version comes first. */
2188  if (packet)
2189  {
2190  ProtocolVersion pv = pg_hton32(conn->pversion);
2191 
2192  memcpy(packet + packet_len, &pv, sizeof(ProtocolVersion));
2193  }
2194  packet_len += sizeof(ProtocolVersion);
2195 
2196  /* Add user name, database name, options */
2197 
2198 #define ADD_STARTUP_OPTION(optname, optval) \
2199  do { \
2200  if (packet) \
2201  strcpy(packet + packet_len, optname); \
2202  packet_len += strlen(optname) + 1; \
2203  if (packet) \
2204  strcpy(packet + packet_len, optval); \
2205  packet_len += strlen(optval) + 1; \
2206  } while(0)
2207 
2208  if (conn->pguser && conn->pguser[0])
2209  ADD_STARTUP_OPTION("user", conn->pguser);
2210  if (conn->dbName && conn->dbName[0])
2211  ADD_STARTUP_OPTION("database", conn->dbName);
2212  if (conn->replication && conn->replication[0])
2213  ADD_STARTUP_OPTION("replication", conn->replication);
2214  if (conn->pgoptions && conn->pgoptions[0])
2215  ADD_STARTUP_OPTION("options", conn->pgoptions);
2216  if (conn->send_appname)
2217  {
2218  /* Use appname if present, otherwise use fallback */
2219  val = conn->appname ? conn->appname : conn->fbappname;
2220  if (val && val[0])
2221  ADD_STARTUP_OPTION("application_name", val);
2222  }
2223 
2224  if (conn->client_encoding_initial && conn->client_encoding_initial[0])
2225  ADD_STARTUP_OPTION("client_encoding", conn->client_encoding_initial);
2226 
2227  /* Add any environment-driven GUC settings needed */
2228  for (next_eo = options; next_eo->envName; next_eo++)
2229  {
2230  if ((val = getenv(next_eo->envName)) != NULL)
2231  {
2232  if (pg_strcasecmp(val, "default") != 0)
2233  ADD_STARTUP_OPTION(next_eo->pgName, val);
2234  }
2235  }
2236 
2237  /* Add trailing terminator */
2238  if (packet)
2239  packet[packet_len] = '\0';
2240  packet_len++;
2241 
2242  return packet_len;
2243 }
const char * envName
Definition: libpq-int.h:253
char * replication
Definition: libpq-int.h:366
char * dbName
Definition: libpq-int.h:365
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
char * client_encoding_initial
Definition: libpq-int.h:361
#define ADD_STARTUP_OPTION(optname, optval)
#define pg_hton32(x)
Definition: pg_bswap.h:121
char * appname
Definition: libpq-int.h:363
char * pguser
Definition: libpq-int.h:367
const char * pgName
Definition: libpq-int.h:253
uint32 ProtocolVersion
Definition: pqcomm.h:125
char * pgoptions
Definition: libpq-int.h:362
ProtocolVersion pversion
Definition: libpq-int.h:447
char * fbappname
Definition: libpq-int.h:364
long val
Definition: informix.c:664
bool send_appname
Definition: libpq-int.h:463

◆ getAnotherTuple()

static int getAnotherTuple ( PGconn conn,
int  msgLength 
)
static

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

References appendPQExpBuffer(), 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().

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

◆ getCopyDataMessage()

static int getCopyDataMessage ( PGconn conn)
static

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

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

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

◆ getCopyStart()

static int getCopyStart ( PGconn conn,
ExecStatusType  copytype 
)
static

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

References pg_result::attDescs, pg_result::binary, 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().

1491 {
1492  PGresult *result;
1493  int nfields;
1494  int i;
1495 
1496  result = PQmakeEmptyPGresult(conn, copytype);
1497  if (!result)
1498  goto failure;
1499 
1500  if (pqGetc(&conn->copy_is_binary, conn))
1501  goto failure;
1502  result->binary = conn->copy_is_binary;
1503  /* the next two bytes are the number of fields */
1504  if (pqGetInt(&(result->numAttributes), 2, conn))
1505  goto failure;
1506  nfields = result->numAttributes;
1507 
1508  /* allocate space for the attribute descriptors */
1509  if (nfields > 0)
1510  {
1511  result->attDescs = (PGresAttDesc *)
1512  pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
1513  if (!result->attDescs)
1514  goto failure;
1515  MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
1516  }
1517 
1518  for (i = 0; i < nfields; i++)
1519  {
1520  int format;
1521 
1522  if (pqGetInt(&format, 2, conn))
1523  goto failure;
1524 
1525  /*
1526  * Since pqGetInt treats 2-byte integers as unsigned, we need to
1527  * coerce these results to signed form.
1528  */
1529  format = (int) ((int16) format);
1530  result->attDescs[i].format = format;
1531  }
1532 
1533  /* Success! */
1534  conn->result = result;
1535  return 0;
1536 
1537 failure:
1538  PQclear(result);
1539  return EOF;
1540 }
signed short int16
Definition: c.h:428
char copy_is_binary
Definition: libpq-int.h:418
#define MemSet(start, val, len)
Definition: c.h:1008
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:219
PGresAttDesc * attDescs
Definition: libpq-int.h:171
PGresult * result
Definition: libpq-int.h:499
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:146
int binary
Definition: libpq-int.h:179
int numAttributes
Definition: libpq-int.h:170
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:80
void PQclear(PGresult *res)
Definition: fe-exec.c:680
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:539
int i
static char format

◆ getNotify()

static int getNotify ( PGconn conn)
static

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

References pgNotify::be_pid, 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().

1435 {
1436  int be_pid;
1437  char *svname;
1438  int nmlen;
1439  int extralen;
1440  PGnotify *newNotify;
1441 
1442  if (pqGetInt(&be_pid, 4, conn))
1443  return EOF;
1444  if (pqGets(&conn->workBuffer, conn))
1445  return EOF;
1446  /* must save name while getting extra string */
1447  svname = strdup(conn->workBuffer.data);
1448  if (!svname)
1449  return EOF;
1450  if (pqGets(&conn->workBuffer, conn))
1451  {
1452  free(svname);
1453  return EOF;
1454  }
1455 
1456  /*
1457  * Store the strings right after the PQnotify structure so it can all be
1458  * freed at once. We don't use NAMEDATALEN because we don't want to tie
1459  * this interface to a specific server name length.
1460  */
1461  nmlen = strlen(svname);
1462  extralen = strlen(conn->workBuffer.data);
1463  newNotify = (PGnotify *) malloc(sizeof(PGnotify) + nmlen + extralen + 2);
1464  if (newNotify)
1465  {
1466  newNotify->relname = (char *) newNotify + sizeof(PGnotify);
1467  strcpy(newNotify->relname, svname);
1468  newNotify->extra = newNotify->relname + nmlen + 1;
1469  strcpy(newNotify->extra, conn->workBuffer.data);
1470  newNotify->be_pid = be_pid;
1471  newNotify->next = NULL;
1472  if (conn->notifyTail)
1473  conn->notifyTail->next = newNotify;
1474  else
1475  conn->notifyHead = newNotify;
1476  conn->notifyTail = newNotify;
1477  }
1478 
1479  free(svname);
1480  return 0;
1481 }
char * extra
Definition: libpq-fe.h:180
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:139
PQExpBufferData workBuffer
Definition: libpq-int.h:572
PGnotify * notifyHead
Definition: libpq-int.h:420
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:219
#define malloc(a)
Definition: header.h:50
int be_pid
Definition: libpq-fe.h:179
char * relname
Definition: libpq-fe.h:178
struct pgNotify * next
Definition: libpq-fe.h:182
#define free(a)
Definition: header.h:65
PGnotify * notifyTail
Definition: libpq-int.h:421

◆ getParamDescriptions()

static int getParamDescriptions ( PGconn conn,
int  msgLength 
)
static

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

References appendPQExpBuffer(), 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().

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

◆ getParameterStatus()

static int getParameterStatus ( PGconn conn)
static

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

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

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

1406 {
1407  PQExpBufferData valueBuf;
1408 
1409  /* Get the parameter name */
1410  if (pqGets(&conn->workBuffer, conn))
1411  return EOF;
1412  /* Get the parameter value (could be large) */
1413  initPQExpBuffer(&valueBuf);
1414  if (pqGets(&valueBuf, conn))
1415  {
1416  termPQExpBuffer(&valueBuf);
1417  return EOF;
1418  }
1419  /* And save it */
1420  pqSaveParameterStatus(conn, conn->workBuffer.data, valueBuf.data);
1421  termPQExpBuffer(&valueBuf);
1422  return 0;
1423 }
void pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
Definition: fe-exec.c:968
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:139
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
PQExpBufferData workBuffer
Definition: libpq-int.h:572
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92

◆ getReadyForQuery()

static int getReadyForQuery ( PGconn conn)
static

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

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

Referenced by pqFunctionCall3(), and pqParseInput3().

1547 {
1548  char xact_status;
1549 
1550  if (pqGetc(&xact_status, conn))
1551  return EOF;
1552  switch (xact_status)
1553  {
1554  case 'I':
1555  conn->xactStatus = PQTRANS_IDLE;
1556  break;
1557  case 'T':
1558  conn->xactStatus = PQTRANS_INTRANS;
1559  break;
1560  case 'E':
1561  conn->xactStatus = PQTRANS_INERROR;
1562  break;
1563  default:
1564  conn->xactStatus = PQTRANS_UNKNOWN;
1565  break;
1566  }
1567 
1568  return 0;
1569 }
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:80
PGTransactionStatusType xactStatus
Definition: libpq-int.h:411

◆ getRowDescriptions()

static int getRowDescriptions ( PGconn conn,
int  msgLength 
)
static

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

References appendPQExpBuffer(), pg_conn::asyncStatus, pg_result::attDescs, pgresAttDesc::atttypmod, pg_result::binary, pg_conn::cmd_queue_head, pgresAttDesc::columnid, 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().

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

◆ handleSyncLoss()

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

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

References appendPQExpBuffer(), pg_conn::asyncStatus, CONNECTION_BAD, pg_conn::errorMessage, libpq_gettext, PGASYNC_READY, pqDropConnection(), pqSaveErrorResult(), and pg_conn::status.

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

489 {
491  libpq_gettext("lost synchronization with server: got message type \"%c\", length %d\n"),
492  id, msgLength);
493  /* build an error result holding the error message */
494  pqSaveErrorResult(conn);
495  conn->asyncStatus = PGASYNC_READY; /* drop out of PQgetResult wait loop */
496  /* flush input data since we're giving up on processing it */
497  pqDropConnection(conn, true);
498  conn->status = CONNECTION_BAD; /* No more connection to backend */
499 }
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:449
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
PQExpBufferData errorMessage
Definition: libpq-int.h:569
ConnStatusType status
Definition: libpq-int.h:409
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:751
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ pqBuildErrorMessage3()

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

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

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(), pg_result::resultStatus, and val.

Referenced by pqGetErrorNotice3(), and PQresultVerboseErrorMessage().

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

◆ pqBuildStartupPacket3()

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

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

References build_startup_packet(), and malloc.

Referenced by PQconnectPoll().

2159 {
2160  char *startpacket;
2161 
2162  *packetlen = build_startup_packet(conn, NULL, options);
2163  startpacket = (char *) malloc(*packetlen);
2164  if (!startpacket)
2165  return NULL;
2166  *packetlen = build_startup_packet(conn, startpacket, options);
2167  return startpacket;
2168 }
static int build_startup_packet(const PGconn *conn, char *packet, const PQEnvironmentOption *options)
#define malloc(a)
Definition: header.h:50

◆ pqEndcopy3()

int pqEndcopy3 ( PGconn conn)

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

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

1855 {
1856  PGresult *result;
1857 
1858  if (conn->asyncStatus != PGASYNC_COPY_IN &&
1859  conn->asyncStatus != PGASYNC_COPY_OUT &&
1860  conn->asyncStatus != PGASYNC_COPY_BOTH)
1861  {
1863  libpq_gettext("no COPY in progress\n"));
1864  return 1;
1865  }
1866 
1867  /* Send the CopyDone message if needed */
1868  if (conn->asyncStatus == PGASYNC_COPY_IN ||
1869  conn->asyncStatus == PGASYNC_COPY_BOTH)
1870  {
1871  if (pqPutMsgStart('c', conn) < 0 ||
1872  pqPutMsgEnd(conn) < 0)
1873  return 1;
1874 
1875  /*
1876  * If we sent the COPY command in extended-query mode, we must issue a
1877  * Sync as well.
1878  */
1879  if (conn->cmd_queue_head &&
1881  {
1882  if (pqPutMsgStart('S', conn) < 0 ||
1883  pqPutMsgEnd(conn) < 0)
1884  return 1;
1885  }
1886  }
1887 
1888  /*
1889  * make sure no data is waiting to be sent, abort if we are non-blocking
1890  * and the flush fails
1891  */
1892  if (pqFlush(conn) && pqIsnonblocking(conn))
1893  return 1;
1894 
1895  /* Return to active duty */
1896  conn->asyncStatus = PGASYNC_BUSY;
1897 
1898  /*
1899  * Non blocking connections may have to abort at this point. If everyone
1900  * played the game there should be no problem, but in error scenarios the
1901  * expected messages may not have arrived yet. (We are assuming that the
1902  * backend's packetizing will ensure that CommandComplete arrives along
1903  * with the CopyDone; are there corner cases where that doesn't happen?)
1904  */
1905  if (pqIsnonblocking(conn) && PQisBusy(conn))
1906  return 1;
1907 
1908  /* Wait for the completion response */
1909  result = PQgetResult(conn);
1910 
1911  /* Expecting a successful result */
1912  if (result && result->resultStatus == PGRES_COMMAND_OK)
1913  {
1914  PQclear(result);
1915  return 0;
1916  }
1917 
1918  /*
1919  * Trouble. For backwards-compatibility reasons, we issue the error
1920  * message as if it were a notice (would be nice to get rid of this
1921  * silliness, but too many apps probably don't handle errors from
1922  * PQendcopy reasonably). Note that the app can still obtain the error
1923  * status from the PGconn object.
1924  */
1925  if (conn->errorMessage.len > 0)
1926  {
1927  /* We have to strip the trailing newline ... pain in neck... */
1928  char svLast = conn->errorMessage.data[conn->errorMessage.len - 1];
1929 
1930  if (svLast == '\n')
1931  conn->errorMessage.data[conn->errorMessage.len - 1] = '\0';
1932  pqInternalNotice(&conn->noticeHooks, "%s", conn->errorMessage.data);
1933  conn->errorMessage.data[conn->errorMessage.len - 1] = svLast;
1934  }
1935 
1936  PQclear(result);
1937 
1938  return 1;
1939 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:965
#define pqIsnonblocking(conn)
Definition: libpq-int.h:835
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:433
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
PGQueryClass queryclass
Definition: libpq-int.h:321
PGNoticeHooks noticeHooks
Definition: libpq-int.h:401
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:825
PQExpBufferData errorMessage
Definition: libpq-int.h:569
void PQclear(PGresult *res)
Definition: fe-exec.c:680
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:1900
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
ExecStatusType resultStatus
Definition: libpq-int.h:177
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1927
#define libpq_gettext(x)
Definition: libpq-int.h:846

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

References appendPQExpBuffer(), Assert, pg_conn::errorMessage, getNotify(), getParameterStatus(), getReadyForQuery(), handleSyncLoss(), i, pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, PQArgBlock::integer, PQArgBlock::len, libpq_gettext, pg_conn::Pfdebug, 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(), PQArgBlock::ptr, pg_conn::result, status(), and VALID_LONG_MESSAGE_TYPE.

Referenced by PQfn().

1952 {
1953  bool needInput = false;
1955  char id;
1956  int msgLength;
1957  int avail;
1958  int i;
1959 
1960  /* already validated by PQfn */
1962 
1963  /* PQfn already validated connection state */
1964 
1965  if (pqPutMsgStart('F', conn) < 0 || /* function call msg */
1966  pqPutInt(fnid, 4, conn) < 0 || /* function id */
1967  pqPutInt(1, 2, conn) < 0 || /* # of format codes */
1968  pqPutInt(1, 2, conn) < 0 || /* format code: BINARY */
1969  pqPutInt(nargs, 2, conn) < 0) /* # of args */
1970  {
1971  /* error message should be set up already */
1972  return NULL;
1973  }
1974 
1975  for (i = 0; i < nargs; ++i)
1976  { /* len.int4 + contents */
1977  if (pqPutInt(args[i].len, 4, conn))
1978  return NULL;
1979  if (args[i].len == -1)
1980  continue; /* it's NULL */
1981 
1982  if (args[i].isint)
1983  {
1984  if (pqPutInt(args[i].u.integer, args[i].len, conn))
1985  return NULL;
1986  }
1987  else
1988  {
1989  if (pqPutnchar((char *) args[i].u.ptr, args[i].len, conn))
1990  return NULL;
1991  }
1992  }
1993 
1994  if (pqPutInt(1, 2, conn) < 0) /* result format code: BINARY */
1995  return NULL;
1996 
1997  if (pqPutMsgEnd(conn) < 0 ||
1998  pqFlush(conn))
1999  return NULL;
2000 
2001  for (;;)
2002  {
2003  if (needInput)
2004  {
2005  /* Wait for some data to arrive (or for the channel to close) */
2006  if (pqWait(true, false, conn) ||
2007  pqReadData(conn) < 0)
2008  break;
2009  }
2010 
2011  /*
2012  * Scan the message. If we run out of data, loop around to try again.
2013  */
2014  needInput = true;
2015 
2016  conn->inCursor = conn->inStart;
2017  if (pqGetc(&id, conn))
2018  continue;
2019  if (pqGetInt(&msgLength, 4, conn))
2020  continue;
2021 
2022  /*
2023  * Try to validate message type/length here. A length less than 4 is
2024  * definitely broken. Large lengths should only be believed for a few
2025  * message types.
2026  */
2027  if (msgLength < 4)
2028  {
2029  handleSyncLoss(conn, id, msgLength);
2030  break;
2031  }
2032  if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
2033  {
2034  handleSyncLoss(conn, id, msgLength);
2035  break;
2036  }
2037 
2038  /*
2039  * Can't process if message body isn't all here yet.
2040  */
2041  msgLength -= 4;
2042  avail = conn->inEnd - conn->inCursor;
2043  if (avail < msgLength)
2044  {
2045  /*
2046  * Before looping, enlarge the input buffer if needed to hold the
2047  * whole message. See notes in parseInput.
2048  */
2049  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
2050  conn))
2051  {
2052  /*
2053  * XXX add some better recovery code... plan is to skip over
2054  * the message using its length, then report an error. For the
2055  * moment, just treat this like loss of sync (which indeed it
2056  * might be!)
2057  */
2058  handleSyncLoss(conn, id, msgLength);
2059  break;
2060  }
2061  continue;
2062  }
2063 
2064  /*
2065  * We should see V or E response to the command, but might get N
2066  * and/or A notices first. We also need to swallow the final Z before
2067  * returning.
2068  */
2069  switch (id)
2070  {
2071  case 'V': /* function result */
2072  if (pqGetInt(actual_result_len, 4, conn))
2073  continue;
2074  if (*actual_result_len != -1)
2075  {
2076  if (result_is_int)
2077  {
2078  if (pqGetInt(result_buf, *actual_result_len, conn))
2079  continue;
2080  }
2081  else
2082  {
2083  if (pqGetnchar((char *) result_buf,
2084  *actual_result_len,
2085  conn))
2086  continue;
2087  }
2088  }
2089  /* correctly finished function result message */
2090  status = PGRES_COMMAND_OK;
2091  break;
2092  case 'E': /* error return */
2093  if (pqGetErrorNotice3(conn, true))
2094  continue;
2095  status = PGRES_FATAL_ERROR;
2096  break;
2097  case 'A': /* notify message */
2098  /* handle notify and go back to processing return values */
2099  if (getNotify(conn))
2100  continue;
2101  break;
2102  case 'N': /* notice */
2103  /* handle notice and go back to processing return values */
2104  if (pqGetErrorNotice3(conn, false))
2105  continue;
2106  break;
2107  case 'Z': /* backend is ready for new query */
2108  if (getReadyForQuery(conn))
2109  continue;
2110  /* consume the message and exit */
2111  conn->inStart += 5 + msgLength;
2112  /* if we saved a result object (probably an error), use it */
2113  if (conn->result)
2114  return pqPrepareAsyncResult(conn);
2115  return PQmakeEmptyPGresult(conn, status);
2116  case 'S': /* parameter status */
2117  if (getParameterStatus(conn))
2118  continue;
2119  break;
2120  default:
2121  /* The backend violates the protocol. */
2123  libpq_gettext("protocol error: id=0x%x\n"),
2124  id);
2125  pqSaveErrorResult(conn);
2126  /* trust the specified message length as what to skip */
2127  conn->inStart += 5 + msgLength;
2128  return pqPrepareAsyncResult(conn);
2129  }
2130 
2131  /* trace server-to-client message */
2132  if (conn->Pfdebug)
2133  pqTraceOutputMessage(conn, conn->inBuffer + conn->inStart, false);
2134 
2135  /* Completed this message, keep going */
2136  /* trust the specified message length as what to skip */
2137  conn->inStart += 5 + msgLength;
2138  needInput = false;
2139  }
2140 
2141  /*
2142  * We fall out of the loop only upon failing to read data.
2143  * conn->errorMessage has been set by pqWait or pqReadData. We want to
2144  * append it to any already-received error message.
2145  */
2146  pqSaveErrorResult(conn);
2147  return pqPrepareAsyncResult(conn);
2148 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:965
int inEnd
Definition: libpq-int.h:482
int inStart
Definition: libpq-int.h:480
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:354
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:416
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:219
ExecStatusType
Definition: libpq-fe.h:83
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:168
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:790
FILE * Pfdebug
Definition: libpq-int.h:397
PGresult * result
Definition: libpq-int.h:499
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:256
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:888
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
int pqReadData(PGconn *conn)
Definition: fe-misc.c:568
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:990
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:146
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:80
char * inBuffer
Definition: libpq-int.h:478
void pqTraceOutputMessage(PGconn *conn, const char *message, bool toServer)
Definition: fe-trace.c:529
#define VALID_LONG_MESSAGE_TYPE(id)
Definition: fe-protocol3.c:38
PQExpBufferData errorMessage
Definition: libpq-int.h:569
#define Assert(condition)
Definition: c.h:804
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:205
static int getReadyForQuery(PGconn *conn)
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
static int getParameterStatus(PGconn *conn)
static int getNotify(PGconn *conn)
int i
static void handleSyncLoss(PGconn *conn, char id, int msgLength)
Definition: fe-protocol3.c:488
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:751
int inCursor
Definition: libpq-int.h:481
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
int * ptr
Definition: libpq-fe.h:241
#define libpq_gettext(x)
Definition: libpq-int.h:846
int integer
Definition: libpq-fe.h:242

◆ pqGetCopyData3()

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

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

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

Referenced by PQgetCopyData().

1688 {
1689  int msgLength;
1690 
1691  for (;;)
1692  {
1693  /*
1694  * Collect the next input message. To make life simpler for async
1695  * callers, we keep returning 0 until the next message is fully
1696  * available, even if it is not Copy Data.
1697  */
1698  msgLength = getCopyDataMessage(conn);
1699  if (msgLength < 0)
1700  return msgLength; /* end-of-copy or error */
1701  if (msgLength == 0)
1702  {
1703  /* Don't block if async read requested */
1704  if (async)
1705  return 0;
1706  /* Need to load more data */
1707  if (pqWait(true, false, conn) ||
1708  pqReadData(conn) < 0)
1709  return -2;
1710  continue;
1711  }
1712 
1713  /*
1714  * Drop zero-length messages (shouldn't happen anyway). Otherwise
1715  * pass the data back to the caller.
1716  */
1717  msgLength -= 4;
1718  if (msgLength > 0)
1719  {
1720  *buffer = (char *) malloc(msgLength + 1);
1721  if (*buffer == NULL)
1722  {
1724  libpq_gettext("out of memory\n"));
1725  return -2;
1726  }
1727  memcpy(*buffer, &conn->inBuffer[conn->inCursor], msgLength);
1728  (*buffer)[msgLength] = '\0'; /* Add terminating null */
1729 
1730  /* Mark message consumed */
1731  conn->inStart = conn->inCursor + msgLength;
1732 
1733  return msgLength;
1734  }
1735 
1736  /* Empty, so drop it and loop around for another */
1737  conn->inStart = conn->inCursor;
1738  }
1739 }
int inStart
Definition: libpq-int.h:480
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define malloc(a)
Definition: header.h:50
int pqReadData(PGconn *conn)
Definition: fe-misc.c:568
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:990
char * inBuffer
Definition: libpq-int.h:478
static int getCopyDataMessage(PGconn *conn)
PQExpBufferData errorMessage
Definition: libpq-int.h:569
int inCursor
Definition: libpq-int.h:481
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ pqGetErrorNotice3()

int pqGetErrorNotice3 ( PGconn conn,
bool  isError 
)

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

References appendPQExpBufferStr(), pg_conn::cmd_queue_head, PQExpBufferData::data, pg_result::errMsg, 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(), PGcmdQueueEntry::query, resetPQExpBuffer(), pg_conn::result, pg_result::resultStatus, pg_conn::show_context, strlcpy(), termPQExpBuffer(), and pg_conn::verbosity.

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

889 {
890  PGresult *res = NULL;
891  bool have_position = false;
892  PQExpBufferData workBuf;
893  char id;
894 
895  /* If in pipeline mode, set error indicator for it */
896  if (isError && conn->pipelineStatus != PQ_PIPELINE_OFF)
898 
899  /*
900  * If this is an error message, pre-emptively clear any incomplete query
901  * result we may have. We'd just throw it away below anyway, and
902  * releasing it before collecting the error might avoid out-of-memory.
903  */
904  if (isError)
905  pqClearAsyncResult(conn);
906 
907  /*
908  * Since the fields might be pretty long, we create a temporary
909  * PQExpBuffer rather than using conn->workBuffer. workBuffer is intended
910  * for stuff that is expected to be short. We shouldn't use
911  * conn->errorMessage either, since this might be only a notice.
912  */
913  initPQExpBuffer(&workBuf);
914 
915  /*
916  * Make a PGresult to hold the accumulated fields. We temporarily lie
917  * about the result status, so that PQmakeEmptyPGresult doesn't uselessly
918  * copy conn->errorMessage.
919  *
920  * NB: This allocation can fail, if you run out of memory. The rest of the
921  * function handles that gracefully, and we still try to set the error
922  * message as the connection's error message.
923  */
925  if (res)
927 
928  /*
929  * Read the fields and save into res.
930  *
931  * While at it, save the SQLSTATE in conn->last_sqlstate, and note whether
932  * we saw a PG_DIAG_STATEMENT_POSITION field.
933  */
934  for (;;)
935  {
936  if (pqGetc(&id, conn))
937  goto fail;
938  if (id == '\0')
939  break; /* terminator found */
940  if (pqGets(&workBuf, conn))
941  goto fail;
942  pqSaveMessageField(res, id, workBuf.data);
943  if (id == PG_DIAG_SQLSTATE)
944  strlcpy(conn->last_sqlstate, workBuf.data,
945  sizeof(conn->last_sqlstate));
946  else if (id == PG_DIAG_STATEMENT_POSITION)
947  have_position = true;
948  }
949 
950  /*
951  * Save the active query text, if any, into res as well; but only if we
952  * might need it for an error cursor display, which is only true if there
953  * is a PG_DIAG_STATEMENT_POSITION field.
954  */
955  if (have_position && res && conn->cmd_queue_head && conn->cmd_queue_head->query)
956  res->errQuery = pqResultStrdup(res, conn->cmd_queue_head->query);
957 
958  /*
959  * Now build the "overall" error message for PQresultErrorMessage.
960  */
961  resetPQExpBuffer(&workBuf);
962  pqBuildErrorMessage3(&workBuf, res, conn->verbosity, conn->show_context);
963 
964  /*
965  * Either save error as current async result, or just emit the notice.
966  */
967  if (isError)
968  {
969  if (res)
970  res->errMsg = pqResultStrdup(res, workBuf.data);
971  pqClearAsyncResult(conn); /* redundant, but be safe */
972  conn->result = res;
973  if (PQExpBufferDataBroken(workBuf))
975  libpq_gettext("out of memory"));
976  else
977  appendPQExpBufferStr(&conn->errorMessage, workBuf.data);
978  }
979  else
980  {
981  /* if we couldn't allocate the result set, just discard the NOTICE */
982  if (res)
983  {
984  /* We can cheat a little here and not copy the message. */
985  res->errMsg = workBuf.data;
986  if (res->noticeHooks.noticeRec != NULL)
988  PQclear(res);
989  }
990  }
991 
992  termPQExpBuffer(&workBuf);
993  return 0;
994 
995 fail:
996  PQclear(res);
997  termPQExpBuffer(&workBuf);
998  return EOF;
999 }
PGContextVisibility show_context
Definition: libpq-int.h:474
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:139
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:433
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:416
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:57
char * errMsg
Definition: libpq-int.h:196
PGresult * result
Definition: libpq-int.h:499
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
PGVerbosity verbosity
Definition: libpq-int.h:473
PQnoticeReceiver noticeRec
Definition: libpq-int.h:152
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:146
#define PG_DIAG_STATEMENT_POSITION
Definition: postgres_ext.h:61
char * errQuery
Definition: libpq-int.h:198
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:80
void pqSaveMessageField(PGresult *res, char code, const char *value)
Definition: fe-exec.c:947
PQExpBufferData errorMessage
Definition: libpq-int.h:569
void PQclear(PGresult *res)
Definition: fe-exec.c:680
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:735
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
ExecStatusType resultStatus
Definition: libpq-int.h:177
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
#define libpq_gettext(x)
Definition: libpq-int.h:846
char * pqResultStrdup(PGresult *res, const char *str)
Definition: fe-exec.c:651
void * noticeRecArg
Definition: libpq-int.h:153
char last_sqlstate[6]
Definition: libpq-int.h:412

◆ pqGetline3()

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

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

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

1748 {
1749  int status;
1750 
1751  if (conn->sock == PGINVALID_SOCKET ||
1752  (conn->asyncStatus != PGASYNC_COPY_OUT &&
1753  conn->asyncStatus != PGASYNC_COPY_BOTH) ||
1754  conn->copy_is_binary)
1755  {
1757  libpq_gettext("PQgetline: not doing text COPY OUT\n"));
1758  *s = '\0';
1759  return EOF;
1760  }
1761 
1762  while ((status = PQgetlineAsync(conn, s, maxlen - 1)) == 0)
1763  {
1764  /* need to load more data */
1765  if (pqWait(true, false, conn) ||
1766  pqReadData(conn) < 0)
1767  {
1768  *s = '\0';
1769  return EOF;
1770  }
1771  }
1772 
1773  if (status < 0)
1774  {
1775  /* End of copy detected; gin up old-style terminator */
1776  strcpy(s, "\\.");
1777  return 0;
1778  }
1779 
1780  /* Add null terminator, and strip trailing \n if present */
1781  if (s[status - 1] == '\n')
1782  {
1783  s[status - 1] = '\0';
1784  return 0;
1785  }
1786  else
1787  {
1788  s[status] = '\0';
1789  return 1;
1790  }
1791 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
int PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
Definition: fe-exec.c:2704
char copy_is_binary
Definition: libpq-int.h:418
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
int pqReadData(PGconn *conn)
Definition: fe-misc.c:568
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:990
pgsocket sock
Definition: libpq-int.h:443
#define PGINVALID_SOCKET
Definition: port.h:33
PQExpBufferData errorMessage
Definition: libpq-int.h:569
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ pqGetlineAsync3()

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

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

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

1800 {
1801  int msgLength;
1802  int avail;
1803 
1804  if (conn->asyncStatus != PGASYNC_COPY_OUT
1805  && conn->asyncStatus != PGASYNC_COPY_BOTH)
1806  return -1; /* we are not doing a copy... */
1807 
1808  /*
1809  * Recognize the next input message. To make life simpler for async
1810  * callers, we keep returning 0 until the next message is fully available
1811  * even if it is not Copy Data. This should keep PQendcopy from blocking.
1812  * (Note: unlike pqGetCopyData3, we do not change asyncStatus here.)
1813  */
1814  msgLength = getCopyDataMessage(conn);
1815  if (msgLength < 0)
1816  return -1; /* end-of-copy or error */
1817  if (msgLength == 0)
1818  return 0; /* no data yet */
1819 
1820  /*
1821  * Move data from libpq's buffer to the caller's. In the case where a
1822  * prior call found the caller's buffer too small, we use
1823  * conn->copy_already_done to remember how much of the row was already
1824  * returned to the caller.
1825  */
1826  conn->inCursor += conn->copy_already_done;
1827  avail = msgLength - 4 - conn->copy_already_done;
1828  if (avail <= bufsize)
1829  {
1830  /* Able to consume the whole message */
1831  memcpy(buffer, &conn->inBuffer[conn->inCursor], avail);
1832  /* Mark message consumed */
1833  conn->inStart = conn->inCursor + avail;
1834  /* Reset state for next time */
1835  conn->copy_already_done = 0;
1836  return avail;
1837  }
1838  else
1839  {
1840  /* We must return a partial message */
1841  memcpy(buffer, &conn->inBuffer[conn->inCursor], bufsize);
1842  /* The message is NOT consumed from libpq's buffer */
1843  conn->copy_already_done += bufsize;
1844  return bufsize;
1845  }
1846 }
int inStart
Definition: libpq-int.h:480
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
char * inBuffer
Definition: libpq-int.h:478
static int getCopyDataMessage(PGconn *conn)
int copy_already_done
Definition: libpq-int.h:419
int inCursor
Definition: libpq-int.h:481

◆ pqParseInput3()

void pqParseInput3 ( PGconn conn)

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

References appendPQExpBuffer(), appendPQExpBufferStr(), pg_conn::asyncStatus, pg_conn::be_key, pg_conn::be_pid, pg_conn::cmd_queue_head, pg_result::cmdStatus, CMDSTATUS_LEN, pg_conn::copy_already_done, PQExpBufferData::data, 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, 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().

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  */
78  conn->inCursor = conn->inStart;
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  */
169  if (conn->pipelineStatus != PQ_PIPELINE_OFF &&
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  {
189  if (getParameterStatus(conn))
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;
212  if (conn->result == NULL)
213  {
214  conn->result = PQmakeEmptyPGresult(conn,
216  if (!conn->result)
217  {
219  libpq_gettext("out of memory"));
220  pqSaveErrorResult(conn);
221  }
222  }
223  if (conn->result)
224  strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
225  CMDSTATUS_LEN);
226  conn->asyncStatus = PGASYNC_READY;
227  break;
228  case 'E': /* error return */
229  if (pqGetErrorNotice3(conn, true))
230  return;
231  conn->asyncStatus = PGASYNC_READY;
232  break;
233  case 'Z': /* sync response, backend is ready for new
234  * query */
235  if (getReadyForQuery(conn))
236  return;
237  if (conn->pipelineStatus != PQ_PIPELINE_OFF)
238  {
239  conn->result = PQmakeEmptyPGresult(conn,
241  if (!conn->result)
242  {
244  libpq_gettext("out of memory"));
245  pqSaveErrorResult(conn);
246  }
247  else
248  {
250  conn->asyncStatus = PGASYNC_READY;
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 &&
261  pqCommandQueueAdvance(conn);
262  conn->asyncStatus = PGASYNC_IDLE;
263  }
264  break;
265  case 'I': /* empty query */
266  if (conn->result == NULL)
267  {
268  conn->result = PQmakeEmptyPGresult(conn,
270  if (!conn->result)
271  {
273  libpq_gettext("out of memory"));
274  pqSaveErrorResult(conn);
275  }
276  }
277  conn->asyncStatus = PGASYNC_READY;
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  {
284  if (conn->result == NULL)
285  {
286  conn->result = PQmakeEmptyPGresult(conn,
288  if (!conn->result)
289  {
291  libpq_gettext("out of memory"));
292  pqSaveErrorResult(conn);
293  }
294  }
295  conn->asyncStatus = PGASYNC_READY;
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 */
303  if (getParameterStatus(conn))
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->result != NULL &&
321  {
322  /*
323  * We've already choked for some reason. Just discard
324  * the data till we get to the end of the query.
325  */
326  conn->inCursor += msgLength;
327  }
328  else if (conn->result == NULL ||
329  (conn->cmd_queue_head &&
331  {
332  /* First 'T' in a query sequence */
333  if (getRowDescriptions(conn, msgLength))
334  return;
335  }
336  else
337  {
338  /*
339  * A new 'T' message is treated as the start of
340  * another PGresult. (It is not clear that this is
341  * really possible with the current backend.) We stop
342  * parsing until the application accepts the current
343  * result.
344  */
345  conn->asyncStatus = PGASYNC_READY;
346  return;
347  }
348  break;
349  case 'n': /* No Data */
350 
351  /*
352  * NoData indicates that we will not be seeing a
353  * RowDescription message because the statement or portal
354  * inquired about doesn't return rows.
355  *
356  * If we're doing a Describe, we have to pass something
357  * back to the client, so set up a COMMAND_OK result,
358  * instead of PGRES_TUPLES_OK. Otherwise we can just
359  * ignore this message.
360  */
361  if (conn->cmd_queue_head &&
363  {
364  if (conn->result == NULL)
365  {
366  conn->result = PQmakeEmptyPGresult(conn,
368  if (!conn->result)
369  {
371  libpq_gettext("out of memory"));
372  pqSaveErrorResult(conn);
373  }
374  }
375  conn->asyncStatus = PGASYNC_READY;
376  }
377  break;
378  case 't': /* Parameter Description */
379  if (getParamDescriptions(conn, msgLength))
380  return;
381  break;
382  case 'D': /* Data Row */
383  if (conn->result != NULL &&
385  {
386  /* Read another tuple of a normal query response */
387  if (getAnotherTuple(conn, msgLength))
388  return;
389  }
390  else if (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 */
403  libpq_gettext("server sent data (\"D\" message) without prior row description (\"T\" message)\n"));
404  pqSaveErrorResult(conn);
405  /* Discard the unexpected message */
406  conn->inCursor += msgLength;
407  }
408  break;
409  case 'G': /* Start Copy In */
410  if (getCopyStart(conn, PGRES_COPY_IN))
411  return;
413  break;
414  case 'H': /* Start Copy Out */
415  if (getCopyStart(conn, PGRES_COPY_OUT))
416  return;
418  conn->copy_already_done = 0;
419  break;
420  case 'W': /* Start Copy Both */
421  if (getCopyStart(conn, PGRES_COPY_BOTH))
422  return;
424  conn->copy_already_done = 0;
425  break;
426  case 'd': /* Copy Data */
427 
428  /*
429  * If we see Copy Data, just silently drop it. This would
430  * only occur if application exits COPY OUT mode too
431  * early.
432  */
433  conn->inCursor += msgLength;
434  break;
435  case 'c': /* Copy Done */
436 
437  /*
438  * If we see Copy Done, just silently drop it. This is
439  * the normal case during PQendcopy. We will keep
440  * swallowing data, expecting to see command-complete for
441  * the COPY command.
442  */
443  break;
444  default:
446  libpq_gettext("unexpected response from server; first received character was \"%c\"\n"),
447  id);
448  /* build an error result holding the error message */
449  pqSaveErrorResult(conn);
450  /* not sure if we will see more, so go to ready state */
451  conn->asyncStatus = PGASYNC_READY;
452  /* Discard the unexpected message */
453  conn->inCursor += msgLength;
454  break;
455  } /* switch on protocol character */
456  }
457  /* Successfully consumed this message */
458  if (conn->inCursor == conn->inStart + 5 + msgLength)
459  {
460  /* trace server-to-client message */
461  if (conn->Pfdebug)
462  pqTraceOutputMessage(conn, conn->inBuffer + conn->inStart, false);
463 
464  /* Normal case: parsing agrees with specified length */
465  conn->inStart = conn->inCursor;
466  }
467  else
468  {
469  /* Trouble --- report it */
471  libpq_gettext("message contents do not agree with length in message type \"%c\"\n"),
472  id);
473  /* build an error result holding the error message */
474  pqSaveErrorResult(conn);
475  conn->asyncStatus = PGASYNC_READY;
476  /* trust the specified message length as what to skip */
477  conn->inStart += 5 + msgLength;
478  }
479  }
480 }
int inEnd
Definition: libpq-int.h:482
int inStart
Definition: libpq-int.h:480
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:139
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PQExpBufferData workBuffer
Definition: libpq-int.h:572
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:354
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:433
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:416
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:219
static int getParamDescriptions(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:680
#define CMDSTATUS_LEN
Definition: libpq-int.h:86
FILE * Pfdebug
Definition: libpq-int.h:397
PGresult * result
Definition: libpq-int.h:499
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
PGQueryClass queryclass
Definition: libpq-int.h:321
static int getRowDescriptions(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:509
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:888
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
PGNoticeHooks noticeHooks
Definition: libpq-int.h:401
static int getAnotherTuple(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:768
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:825
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:146
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:80
void pqCommandQueueAdvance(PGconn *conn)
Definition: fe-exec.c:2926
char * inBuffer
Definition: libpq-int.h:478
void pqTraceOutputMessage(PGconn *conn, const char *message, bool toServer)
Definition: fe-trace.c:529
#define VALID_LONG_MESSAGE_TYPE(id)
Definition: fe-protocol3.c:38
PQExpBufferData errorMessage
Definition: libpq-int.h:569
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
static int getReadyForQuery(PGconn *conn)
static int getCopyStart(PGconn *conn, ExecStatusType copytype)
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178
int be_key
Definition: libpq-int.h:467
int copy_already_done
Definition: libpq-int.h:419
static int getParameterStatus(PGconn *conn)
static int getNotify(PGconn *conn)
static void handleSyncLoss(PGconn *conn, char id, int msgLength)
Definition: fe-protocol3.c:488
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:751
int inCursor
Definition: libpq-int.h:481
int be_pid
Definition: libpq-int.h:466
ExecStatusType resultStatus
Definition: libpq-int.h:177
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ reportErrorPosition()

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

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

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

Referenced by pqBuildErrorMessage3().

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