PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
fe-protocol3.c File Reference
#include "postgres_fe.h"
#include <ctype.h>
#include <fcntl.h>
#include "libpq-fe.h"
#include "libpq-int.h"
#include "mb/pg_wchar.h"
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.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

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

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

Referenced by reportErrorPosition().

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

Referenced by reportErrorPosition().

#define VALID_LONG_MESSAGE_TYPE (   id)
Value:
((id) == 'T' || (id) == 'D' || (id) == 'd' || (id) == 'V' || \
(id) == 'E' || (id) == 'N' || (id) == 'A')

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

Referenced by pqFunctionCall3(), and pqParseInput3().

Function Documentation

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

Definition at line 2141 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, NULL, 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().

2143 {
2144  int packet_len = 0;
2145  const PQEnvironmentOption *next_eo;
2146  const char *val;
2147 
2148  /* Protocol version comes first. */
2149  if (packet)
2150  {
2151  ProtocolVersion pv = htonl(conn->pversion);
2152 
2153  memcpy(packet + packet_len, &pv, sizeof(ProtocolVersion));
2154  }
2155  packet_len += sizeof(ProtocolVersion);
2156 
2157  /* Add user name, database name, options */
2158 
2159 #define ADD_STARTUP_OPTION(optname, optval) \
2160  do { \
2161  if (packet) \
2162  strcpy(packet + packet_len, optname); \
2163  packet_len += strlen(optname) + 1; \
2164  if (packet) \
2165  strcpy(packet + packet_len, optval); \
2166  packet_len += strlen(optval) + 1; \
2167  } while(0)
2168 
2169  if (conn->pguser && conn->pguser[0])
2170  ADD_STARTUP_OPTION("user", conn->pguser);
2171  if (conn->dbName && conn->dbName[0])
2172  ADD_STARTUP_OPTION("database", conn->dbName);
2173  if (conn->replication && conn->replication[0])
2174  ADD_STARTUP_OPTION("replication", conn->replication);
2175  if (conn->pgoptions && conn->pgoptions[0])
2176  ADD_STARTUP_OPTION("options", conn->pgoptions);
2177  if (conn->send_appname)
2178  {
2179  /* Use appname if present, otherwise use fallback */
2180  val = conn->appname ? conn->appname : conn->fbappname;
2181  if (val && val[0])
2182  ADD_STARTUP_OPTION("application_name", val);
2183  }
2184 
2185  if (conn->client_encoding_initial && conn->client_encoding_initial[0])
2186  ADD_STARTUP_OPTION("client_encoding", conn->client_encoding_initial);
2187 
2188  /* Add any environment-driven GUC settings needed */
2189  for (next_eo = options; next_eo->envName; next_eo++)
2190  {
2191  if ((val = getenv(next_eo->envName)) != NULL)
2192  {
2193  if (pg_strcasecmp(val, "default") != 0)
2194  ADD_STARTUP_OPTION(next_eo->pgName, val);
2195  }
2196  }
2197 
2198  /* Add trailing terminator */
2199  if (packet)
2200  packet[packet_len] = '\0';
2201  packet_len++;
2202 
2203  return packet_len;
2204 }
const char * envName
Definition: libpq-int.h:253
char * replication
Definition: libpq-int.h:343
char * dbName
Definition: libpq-int.h:342
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
char * client_encoding_initial
Definition: libpq-int.h:338
#define ADD_STARTUP_OPTION(optname, optval)
char * appname
Definition: libpq-int.h:340
char * pguser
Definition: libpq-int.h:344
const char * pgName
Definition: libpq-int.h:253
uint32 ProtocolVersion
Definition: pqcomm.h:113
#define NULL
Definition: c.h:226
char * pgoptions
Definition: libpq-int.h:339
ProtocolVersion pversion
Definition: libpq-int.h:406
char * fbappname
Definition: libpq-int.h:341
long val
Definition: informix.c:689
bool send_appname
Definition: libpq-int.h:419
static int getAnotherTuple ( PGconn conn,
int  msgLength 
)
static

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

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

Referenced by pqParseInput3().

749 {
750  PGresult *result = conn->result;
751  int nfields = result->numAttributes;
752  const char *errmsg;
753  PGdataValue *rowbuf;
754  int tupnfields; /* # fields from tuple */
755  int vlen; /* length of the current field value */
756  int i;
757 
758  /* Get the field count and make sure it's what we expect */
759  if (pqGetInt(&tupnfields, 2, conn))
760  {
761  /* We should not run out of data here, so complain */
762  errmsg = libpq_gettext("insufficient data in \"D\" message");
763  goto advance_and_error;
764  }
765 
766  if (tupnfields != nfields)
767  {
768  errmsg = libpq_gettext("unexpected field count in \"D\" message");
769  goto advance_and_error;
770  }
771 
772  /* Resize row buffer if needed */
773  rowbuf = conn->rowBuf;
774  if (nfields > conn->rowBufLen)
775  {
776  rowbuf = (PGdataValue *) realloc(rowbuf,
777  nfields * sizeof(PGdataValue));
778  if (!rowbuf)
779  {
780  errmsg = NULL; /* means "out of memory", see below */
781  goto advance_and_error;
782  }
783  conn->rowBuf = rowbuf;
784  conn->rowBufLen = nfields;
785  }
786 
787  /* Scan the fields */
788  for (i = 0; i < nfields; i++)
789  {
790  /* get the value length */
791  if (pqGetInt(&vlen, 4, conn))
792  {
793  /* We should not run out of data here, so complain */
794  errmsg = libpq_gettext("insufficient data in \"D\" message");
795  goto advance_and_error;
796  }
797  rowbuf[i].len = vlen;
798 
799  /*
800  * rowbuf[i].value always points to the next address in the data
801  * buffer even if the value is NULL. This allows row processors to
802  * estimate data sizes more easily.
803  */
804  rowbuf[i].value = conn->inBuffer + conn->inCursor;
805 
806  /* Skip over the data value */
807  if (vlen > 0)
808  {
809  if (pqSkipnchar(vlen, conn))
810  {
811  /* We should not run out of data here, so complain */
812  errmsg = libpq_gettext("insufficient data in \"D\" message");
813  goto advance_and_error;
814  }
815  }
816  }
817 
818  /* Sanity check that we absorbed all the data */
819  if (conn->inCursor != conn->inStart + 5 + msgLength)
820  {
821  errmsg = libpq_gettext("extraneous data in \"D\" message");
822  goto advance_and_error;
823  }
824 
825  /* Advance inStart to show that the "D" message has been processed. */
826  conn->inStart = conn->inCursor;
827 
828  /* Process the collected row */
829  errmsg = NULL;
830  if (pqRowProcessor(conn, &errmsg))
831  return 0; /* normal, successful exit */
832 
833  goto set_error_result; /* pqRowProcessor failed, report it */
834 
835 advance_and_error:
836  /* Discard the failed message by pretending we read it */
837  conn->inStart += 5 + msgLength;
838 
839 set_error_result:
840 
841  /*
842  * Replace partially constructed result with an error result. First
843  * discard the old result to try to win back some memory.
844  */
845  pqClearAsyncResult(conn);
846 
847  /*
848  * If preceding code didn't provide an error message, assume "out of
849  * memory" was meant. The advantage of having this special case is that
850  * freeing the old result first greatly improves the odds that gettext()
851  * will succeed in providing a translation.
852  */
853  if (!errmsg)
854  errmsg = libpq_gettext("out of memory for query result");
855 
856  printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
857  pqSaveErrorResult(conn);
858 
859  /*
860  * Return zero to allow input parsing to continue. Subsequent "D"
861  * messages will be ignored until we get to end of data, since an error
862  * result is already set up.
863  */
864  return 0;
865 }
int pqRowProcessor(PGconn *conn, const char **errmsgp)
Definition: fe-exec.c:1030
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
int inStart
Definition: libpq-int.h:435
int rowBufLen
Definition: libpq-int.h:451
const char * value
Definition: libpq-int.h:292
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:272
PGresult * result
Definition: libpq-int.h:454
PGdataValue * rowBuf
Definition: libpq-int.h:450
int numAttributes
Definition: libpq-int.h:172
char * inBuffer
Definition: libpq-int.h:433
PQExpBufferData errorMessage
Definition: libpq-int.h:498
#define NULL
Definition: c.h:226
#define realloc(a, b)
Definition: header.h:55
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
int pqSkipnchar(size_t len, PGconn *conn)
Definition: fe-misc.c:229
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:705
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:728
int inCursor
Definition: libpq-int.h:436
#define libpq_gettext(x)
Definition: libpq-int.h:689
static int getCopyDataMessage ( PGconn conn)
static

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

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

Referenced by pqGetCopyData3(), and pqGetlineAsync3().

1537 {
1538  char id;
1539  int msgLength;
1540  int avail;
1541 
1542  for (;;)
1543  {
1544  /*
1545  * Do we have the next input message? To make life simpler for async
1546  * callers, we keep returning 0 until the next message is fully
1547  * available, even if it is not Copy Data.
1548  */
1549  conn->inCursor = conn->inStart;
1550  if (pqGetc(&id, conn))
1551  return 0;
1552  if (pqGetInt(&msgLength, 4, conn))
1553  return 0;
1554  if (msgLength < 4)
1555  {
1556  handleSyncLoss(conn, id, msgLength);
1557  return -2;
1558  }
1559  avail = conn->inEnd - conn->inCursor;
1560  if (avail < msgLength - 4)
1561  {
1562  /*
1563  * Before returning, enlarge the input buffer if needed to hold
1564  * the whole message. See notes in parseInput.
1565  */
1566  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength - 4,
1567  conn))
1568  {
1569  /*
1570  * XXX add some better recovery code... plan is to skip over
1571  * the message using its length, then report an error. For the
1572  * moment, just treat this like loss of sync (which indeed it
1573  * might be!)
1574  */
1575  handleSyncLoss(conn, id, msgLength);
1576  return -2;
1577  }
1578  return 0;
1579  }
1580 
1581  /*
1582  * If it's a legitimate async message type, process it. (NOTIFY
1583  * messages are not currently possible here, but we handle them for
1584  * completeness.) Otherwise, if it's anything except Copy Data,
1585  * report end-of-copy.
1586  */
1587  switch (id)
1588  {
1589  case 'A': /* NOTIFY */
1590  if (getNotify(conn))
1591  return 0;
1592  break;
1593  case 'N': /* NOTICE */
1594  if (pqGetErrorNotice3(conn, false))
1595  return 0;
1596  break;
1597  case 'S': /* ParameterStatus */
1598  if (getParameterStatus(conn))
1599  return 0;
1600  break;
1601  case 'd': /* Copy Data, pass it back to caller */
1602  return msgLength;
1603  case 'c':
1604 
1605  /*
1606  * If this is a CopyDone message, exit COPY_OUT mode and let
1607  * caller read status with PQgetResult(). If we're in
1608  * COPY_BOTH mode, return to COPY_IN mode.
1609  */
1610  if (conn->asyncStatus == PGASYNC_COPY_BOTH)
1611  conn->asyncStatus = PGASYNC_COPY_IN;
1612  else
1613  conn->asyncStatus = PGASYNC_BUSY;
1614  return -1;
1615  default: /* treat as end of copy */
1616 
1617  /*
1618  * Any other message terminates either COPY_IN or COPY_BOTH
1619  * mode.
1620  */
1621  conn->asyncStatus = PGASYNC_BUSY;
1622  return -1;
1623  }
1624 
1625  /* Drop the processed message and loop around for another */
1626  conn->inStart = conn->inCursor;
1627  }
1628 }
int inEnd
Definition: libpq-int.h:437
int inStart
Definition: libpq-int.h:435
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:413
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:272
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:381
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:876
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:99
static int getParameterStatus(PGconn *conn)
static int getNotify(PGconn *conn)
static void handleSyncLoss(PGconn *conn, char id, int msgLength)
Definition: fe-protocol3.c:450
int inCursor
Definition: libpq-int.h:436
static int getCopyStart ( PGconn conn,
ExecStatusType  copytype 
)
static

Definition at line 1448 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(), pg_conn::result, and TRUE.

Referenced by pqParseInput3().

1449 {
1450  PGresult *result;
1451  int nfields;
1452  int i;
1453 
1454  result = PQmakeEmptyPGresult(conn, copytype);
1455  if (!result)
1456  goto failure;
1457 
1458  if (pqGetc(&conn->copy_is_binary, conn))
1459  goto failure;
1460  result->binary = conn->copy_is_binary;
1461  /* the next two bytes are the number of fields */
1462  if (pqGetInt(&(result->numAttributes), 2, conn))
1463  goto failure;
1464  nfields = result->numAttributes;
1465 
1466  /* allocate space for the attribute descriptors */
1467  if (nfields > 0)
1468  {
1469  result->attDescs = (PGresAttDesc *)
1470  pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
1471  if (!result->attDescs)
1472  goto failure;
1473  MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
1474  }
1475 
1476  for (i = 0; i < nfields; i++)
1477  {
1478  int format;
1479 
1480  if (pqGetInt(&format, 2, conn))
1481  goto failure;
1482 
1483  /*
1484  * Since pqGetInt treats 2-byte integers as unsigned, we need to
1485  * coerce these results to signed form.
1486  */
1487  format = (int) ((int16) format);
1488  result->attDescs[i].format = format;
1489  }
1490 
1491  /* Success! */
1492  conn->result = result;
1493  return 0;
1494 
1495 failure:
1496  PQclear(result);
1497  return EOF;
1498 }
signed short int16
Definition: c.h:252
char copy_is_binary
Definition: libpq-int.h:390
#define MemSet(start, val, len)
Definition: c.h:853
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:272
PGresAttDesc * attDescs
Definition: libpq-int.h:173
PGresult * result
Definition: libpq-int.h:454
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:140
int binary
Definition: libpq-int.h:181
int numAttributes
Definition: libpq-int.h:172
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:99
void PQclear(PGresult *res)
Definition: fe-exec.c:650
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:506
int i
#define TRUE
Definition: c.h:214
static char format
Definition: pg_basebackup.c:83
static int getNotify ( PGconn conn)
static

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

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

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

1393 {
1394  int be_pid;
1395  char *svname;
1396  int nmlen;
1397  int extralen;
1398  PGnotify *newNotify;
1399 
1400  if (pqGetInt(&be_pid, 4, conn))
1401  return EOF;
1402  if (pqGets(&conn->workBuffer, conn))
1403  return EOF;
1404  /* must save name while getting extra string */
1405  svname = strdup(conn->workBuffer.data);
1406  if (!svname)
1407  return EOF;
1408  if (pqGets(&conn->workBuffer, conn))
1409  {
1410  free(svname);
1411  return EOF;
1412  }
1413 
1414  /*
1415  * Store the strings right after the PQnotify structure so it can all be
1416  * freed at once. We don't use NAMEDATALEN because we don't want to tie
1417  * this interface to a specific server name length.
1418  */
1419  nmlen = strlen(svname);
1420  extralen = strlen(conn->workBuffer.data);
1421  newNotify = (PGnotify *) malloc(sizeof(PGnotify) + nmlen + extralen + 2);
1422  if (newNotify)
1423  {
1424  newNotify->relname = (char *) newNotify + sizeof(PGnotify);
1425  strcpy(newNotify->relname, svname);
1426  newNotify->extra = newNotify->relname + nmlen + 1;
1427  strcpy(newNotify->extra, conn->workBuffer.data);
1428  newNotify->be_pid = be_pid;
1429  newNotify->next = NULL;
1430  if (conn->notifyTail)
1431  conn->notifyTail->next = newNotify;
1432  else
1433  conn->notifyHead = newNotify;
1434  conn->notifyTail = newNotify;
1435  }
1436 
1437  free(svname);
1438  return 0;
1439 }
char * extra
Definition: libpq-fe.h:165
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:168
PQExpBufferData workBuffer
Definition: libpq-int.h:501
PGnotify * notifyHead
Definition: libpq-int.h:393
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:272
#define malloc(a)
Definition: header.h:45
int be_pid
Definition: libpq-fe.h:164
char * relname
Definition: libpq-fe.h:163
struct pgNotify * next
Definition: libpq-fe.h:167
#define free(a)
Definition: header.h:60
#define NULL
Definition: c.h:226
PGnotify * notifyTail
Definition: libpq-int.h:394
static int getParamDescriptions ( PGconn conn,
int  msgLength 
)
static

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

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

Referenced by pqParseInput3().

652 {
653  PGresult *result;
654  const char *errmsg = NULL; /* means "out of memory", see below */
655  int nparams;
656  int i;
657 
658  result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
659  if (!result)
660  goto advance_and_error;
661 
662  /* parseInput already read the 't' label and message length. */
663  /* the next two bytes are the number of parameters */
664  if (pqGetInt(&(result->numParameters), 2, conn))
665  goto not_enough_data;
666  nparams = result->numParameters;
667 
668  /* allocate space for the parameter descriptors */
669  if (nparams > 0)
670  {
671  result->paramDescs = (PGresParamDesc *)
672  pqResultAlloc(result, nparams * sizeof(PGresParamDesc), TRUE);
673  if (!result->paramDescs)
674  goto advance_and_error;
675  MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
676  }
677 
678  /* get parameter info */
679  for (i = 0; i < nparams; i++)
680  {
681  int typid;
682 
683  if (pqGetInt(&typid, 4, conn))
684  goto not_enough_data;
685  result->paramDescs[i].typid = typid;
686  }
687 
688  /* Sanity check that we absorbed all the data */
689  if (conn->inCursor != conn->inStart + 5 + msgLength)
690  {
691  errmsg = libpq_gettext("extraneous data in \"t\" message");
692  goto advance_and_error;
693  }
694 
695  /* Success! */
696  conn->result = result;
697 
698  /* Advance inStart to show that the "t" message has been processed. */
699  conn->inStart = conn->inCursor;
700 
701  return 0;
702 
703 not_enough_data:
704  PQclear(result);
705  return EOF;
706 
707 advance_and_error:
708  /* Discard unsaved result, if any */
709  if (result && result != conn->result)
710  PQclear(result);
711 
712  /* Discard the failed message by pretending we read it */
713  conn->inStart += 5 + msgLength;
714 
715  /*
716  * Replace partially constructed result with an error result. First
717  * discard the old result to try to win back some memory.
718  */
719  pqClearAsyncResult(conn);
720 
721  /*
722  * If preceding code didn't provide an error message, assume "out of
723  * memory" was meant. The advantage of having this special case is that
724  * freeing the old result first greatly improves the odds that gettext()
725  * will succeed in providing a translation.
726  */
727  if (!errmsg)
728  errmsg = libpq_gettext("out of memory");
729  printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
730  pqSaveErrorResult(conn);
731 
732  /*
733  * Return zero to allow input parsing to continue. Essentially, we've
734  * replaced the COMMAND_OK result with an error result, but since this
735  * doesn't affect the protocol state, it's fine.
736  */
737  return 0;
738 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
int inStart
Definition: libpq-int.h:435
#define MemSet(start, val, len)
Definition: c.h:853
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:272
PGresult * result
Definition: libpq-int.h:454
int numParameters
Definition: libpq-int.h:177
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:140
PQExpBufferData errorMessage
Definition: libpq-int.h:498
void PQclear(PGresult *res)
Definition: fe-exec.c:650
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:506
PGresParamDesc * paramDescs
Definition: libpq-int.h:178
#define NULL
Definition: c.h:226
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define TRUE
Definition: c.h:214
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:705
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:728
int inCursor
Definition: libpq-int.h:436
#define libpq_gettext(x)
Definition: libpq-int.h:689
static int getParameterStatus ( PGconn conn)
static

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

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

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

1364 {
1365  PQExpBufferData valueBuf;
1366 
1367  /* Get the parameter name */
1368  if (pqGets(&conn->workBuffer, conn))
1369  return EOF;
1370  /* Get the parameter value (could be large) */
1371  initPQExpBuffer(&valueBuf);
1372  if (pqGets(&valueBuf, conn))
1373  {
1374  termPQExpBuffer(&valueBuf);
1375  return EOF;
1376  }
1377  /* And save it */
1378  pqSaveParameterStatus(conn, conn->workBuffer.data, valueBuf.data);
1379  termPQExpBuffer(&valueBuf);
1380  return 0;
1381 }
void pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
Definition: fe-exec.c:912
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:168
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
PQExpBufferData workBuffer
Definition: libpq-int.h:501
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
static int getReadyForQuery ( PGconn conn)
static

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

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

Referenced by pqFunctionCall3(), and pqParseInput3().

1505 {
1506  char xact_status;
1507 
1508  if (pqGetc(&xact_status, conn))
1509  return EOF;
1510  switch (xact_status)
1511  {
1512  case 'I':
1513  conn->xactStatus = PQTRANS_IDLE;
1514  break;
1515  case 'T':
1516  conn->xactStatus = PQTRANS_INTRANS;
1517  break;
1518  case 'E':
1519  conn->xactStatus = PQTRANS_INERROR;
1520  break;
1521  default:
1522  conn->xactStatus = PQTRANS_UNKNOWN;
1523  break;
1524  }
1525 
1526  return 0;
1527 }
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:99
PGTransactionStatusType xactStatus
Definition: libpq-int.h:382
static int getRowDescriptions ( PGconn conn,
int  msgLength 
)
static

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

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

Referenced by pqParseInput3().

474 {
475  PGresult *result;
476  int nfields;
477  const char *errmsg;
478  int i;
479 
480  /*
481  * When doing Describe for a prepared statement, there'll already be a
482  * PGresult created by getParamDescriptions, and we should fill data into
483  * that. Otherwise, create a new, empty PGresult.
484  */
485  if (conn->queryclass == PGQUERY_DESCRIBE)
486  {
487  if (conn->result)
488  result = conn->result;
489  else
490  result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
491  }
492  else
493  result = PQmakeEmptyPGresult(conn, PGRES_TUPLES_OK);
494  if (!result)
495  {
496  errmsg = NULL; /* means "out of memory", see below */
497  goto advance_and_error;
498  }
499 
500  /* parseInput already read the 'T' label and message length. */
501  /* the next two bytes are the number of fields */
502  if (pqGetInt(&(result->numAttributes), 2, conn))
503  {
504  /* We should not run out of data here, so complain */
505  errmsg = libpq_gettext("insufficient data in \"T\" message");
506  goto advance_and_error;
507  }
508  nfields = result->numAttributes;
509 
510  /* allocate space for the attribute descriptors */
511  if (nfields > 0)
512  {
513  result->attDescs = (PGresAttDesc *)
514  pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
515  if (!result->attDescs)
516  {
517  errmsg = NULL; /* means "out of memory", see below */
518  goto advance_and_error;
519  }
520  MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
521  }
522 
523  /* result->binary is true only if ALL columns are binary */
524  result->binary = (nfields > 0) ? 1 : 0;
525 
526  /* get type info */
527  for (i = 0; i < nfields; i++)
528  {
529  int tableid;
530  int columnid;
531  int typid;
532  int typlen;
533  int atttypmod;
534  int format;
535 
536  if (pqGets(&conn->workBuffer, conn) ||
537  pqGetInt(&tableid, 4, conn) ||
538  pqGetInt(&columnid, 2, conn) ||
539  pqGetInt(&typid, 4, conn) ||
540  pqGetInt(&typlen, 2, conn) ||
541  pqGetInt(&atttypmod, 4, conn) ||
542  pqGetInt(&format, 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 
549  /*
550  * Since pqGetInt treats 2-byte integers as unsigned, we need to
551  * coerce these results to signed form.
552  */
553  columnid = (int) ((int16) columnid);
554  typlen = (int) ((int16) typlen);
555  format = (int) ((int16) format);
556 
557  result->attDescs[i].name = pqResultStrdup(result,
558  conn->workBuffer.data);
559  if (!result->attDescs[i].name)
560  {
561  errmsg = NULL; /* means "out of memory", see below */
562  goto advance_and_error;
563  }
564  result->attDescs[i].tableid = tableid;
565  result->attDescs[i].columnid = columnid;
566  result->attDescs[i].format = format;
567  result->attDescs[i].typid = typid;
568  result->attDescs[i].typlen = typlen;
569  result->attDescs[i].atttypmod = atttypmod;
570 
571  if (format != 1)
572  result->binary = 0;
573  }
574 
575  /* Sanity check that we absorbed all the data */
576  if (conn->inCursor != conn->inStart + 5 + msgLength)
577  {
578  errmsg = libpq_gettext("extraneous data in \"T\" message");
579  goto advance_and_error;
580  }
581 
582  /* Success! */
583  conn->result = result;
584 
585  /* Advance inStart to show that the "T" message has been processed. */
586  conn->inStart = conn->inCursor;
587 
588  /*
589  * If we're doing a Describe, we're done, and ready to pass the result
590  * back to the client.
591  */
592  if (conn->queryclass == PGQUERY_DESCRIBE)
593  {
594  conn->asyncStatus = PGASYNC_READY;
595  return 0;
596  }
597 
598  /*
599  * We could perform additional setup for the new result set here, but for
600  * now there's nothing else to do.
601  */
602 
603  /* And we're done. */
604  return 0;
605 
606 advance_and_error:
607  /* Discard unsaved result, if any */
608  if (result && result != conn->result)
609  PQclear(result);
610 
611  /* Discard the failed message by pretending we read it */
612  conn->inStart += 5 + msgLength;
613 
614  /*
615  * Replace partially constructed result with an error result. First
616  * discard the old result to try to win back some memory.
617  */
618  pqClearAsyncResult(conn);
619 
620  /*
621  * If preceding code didn't provide an error message, assume "out of
622  * memory" was meant. The advantage of having this special case is that
623  * freeing the old result first greatly improves the odds that gettext()
624  * will succeed in providing a translation.
625  */
626  if (!errmsg)
627  errmsg = libpq_gettext("out of memory for query result");
628 
629  printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
630  pqSaveErrorResult(conn);
631 
632  /*
633  * Return zero to allow input parsing to continue. Subsequent "D"
634  * messages will be ignored until we get to end of data, since an error
635  * result is already set up.
636  */
637  return 0;
638 }
signed short int16
Definition: c.h:252
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
int inStart
Definition: libpq-int.h:435
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:168
PQExpBufferData workBuffer
Definition: libpq-int.h:501
PGQueryClass queryclass
Definition: libpq-int.h:383
#define MemSet(start, val, len)
Definition: c.h:853
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:272
int columnid
Definition: libpq-fe.h:239
PGresAttDesc * attDescs
Definition: libpq-int.h:173
PGresult * result
Definition: libpq-int.h:454
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:381
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:140
int binary
Definition: libpq-int.h:181
int numAttributes
Definition: libpq-int.h:172
int atttypmod
Definition: libpq-fe.h:243
PQExpBufferData errorMessage
Definition: libpq-int.h:498
void PQclear(PGresult *res)
Definition: fe-exec.c:650
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:506
#define NULL
Definition: c.h:226
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
char * name
Definition: libpq-fe.h:237
#define TRUE
Definition: c.h:214
static char format
Definition: pg_basebackup.c:83
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:705
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:728
int inCursor
Definition: libpq-int.h:436
#define libpq_gettext(x)
Definition: libpq-int.h:689
char * pqResultStrdup(PGresult *res, const char *str)
Definition: fe-exec.c:602
static void handleSyncLoss ( PGconn conn,
char  id,
int  msgLength 
)
static

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

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

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

451 {
454  "lost synchronization with server: got message type \"%c\", length %d\n"),
455  id, msgLength);
456  /* build an error result holding the error message */
457  pqSaveErrorResult(conn);
458  conn->asyncStatus = PGASYNC_READY; /* drop out of GetResult wait loop */
459  /* flush input data since we're giving up on processing it */
460  pqDropConnection(conn, true);
461  conn->status = CONNECTION_BAD; /* No more connection to backend */
462 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:410
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:381
PQExpBufferData errorMessage
Definition: libpq-int.h:498
ConnStatusType status
Definition: libpq-int.h:380
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:728
#define libpq_gettext(x)
Definition: libpq-int.h:689
void pqBuildErrorMessage3 ( PQExpBuffer  msg,
const PGresult res,
PGVerbosity  verbosity,
PGContextVisibility  show_context 
)

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

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), pg_result::client_encoding, pg_result::errFields, pg_result::errMsg, pg_result::errQuery, libpq_gettext, NULL, 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_TERSE, PQERRORS_VERBOSE, PQresultErrorField(), PQSHOW_CONTEXT_ALWAYS, PQSHOW_CONTEXT_ERRORS, reportErrorPosition(), pg_result::resultStatus, and val.

Referenced by pqGetErrorNotice3(), and PQresultVerboseErrorMessage().

984 {
985  const char *val;
986  const char *querytext = NULL;
987  int querypos = 0;
988 
989  /* If we couldn't allocate a PGresult, just say "out of memory" */
990  if (res == NULL)
991  {
992  appendPQExpBuffer(msg, libpq_gettext("out of memory\n"));
993  return;
994  }
995 
996  /*
997  * If we don't have any broken-down fields, just return the base message.
998  * This mainly applies if we're given a libpq-generated error result.
999  */
1000  if (res->errFields == NULL)
1001  {
1002  if (res->errMsg && res->errMsg[0])
1003  appendPQExpBufferStr(msg, res->errMsg);
1004  else
1005  appendPQExpBuffer(msg, libpq_gettext("no error message available\n"));
1006  return;
1007  }
1008 
1009  /* Else build error message from relevant fields */
1011  if (val)
1012  appendPQExpBuffer(msg, "%s: ", val);
1013  if (verbosity == PQERRORS_VERBOSE)
1014  {
1016  if (val)
1017  appendPQExpBuffer(msg, "%s: ", val);
1018  }
1020  if (val)
1021  appendPQExpBufferStr(msg, val);
1023  if (val)
1024  {
1025  if (verbosity != PQERRORS_TERSE && res->errQuery != NULL)
1026  {
1027  /* emit position as a syntax cursor display */
1028  querytext = res->errQuery;
1029  querypos = atoi(val);
1030  }
1031  else
1032  {
1033  /* emit position as text addition to primary message */
1034  /* translator: %s represents a digit string */
1035  appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1036  val);
1037  }
1038  }
1039  else
1040  {
1042  if (val)
1043  {
1044  querytext = PQresultErrorField(res, PG_DIAG_INTERNAL_QUERY);
1045  if (verbosity != PQERRORS_TERSE && querytext != NULL)
1046  {
1047  /* emit position as a syntax cursor display */
1048  querypos = atoi(val);
1049  }
1050  else
1051  {
1052  /* emit position as text addition to primary message */
1053  /* translator: %s represents a digit string */
1054  appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1055  val);
1056  }
1057  }
1058  }
1059  appendPQExpBufferChar(msg, '\n');
1060  if (verbosity != PQERRORS_TERSE)
1061  {
1062  if (querytext && querypos > 0)
1063  reportErrorPosition(msg, querytext, querypos,
1064  res->client_encoding);
1066  if (val)
1067  appendPQExpBuffer(msg, libpq_gettext("DETAIL: %s\n"), val);
1069  if (val)
1070  appendPQExpBuffer(msg, libpq_gettext("HINT: %s\n"), val);
1072  if (val)
1073  appendPQExpBuffer(msg, libpq_gettext("QUERY: %s\n"), val);
1074  if (show_context == PQSHOW_CONTEXT_ALWAYS ||
1075  (show_context == PQSHOW_CONTEXT_ERRORS &&
1077  {
1078  val = PQresultErrorField(res, PG_DIAG_CONTEXT);
1079  if (val)
1080  appendPQExpBuffer(msg, libpq_gettext("CONTEXT: %s\n"),
1081  val);
1082  }
1083  }
1084  if (verbosity == PQERRORS_VERBOSE)
1085  {
1087  if (val)
1088  appendPQExpBuffer(msg,
1089  libpq_gettext("SCHEMA NAME: %s\n"), val);
1091  if (val)
1092  appendPQExpBuffer(msg,
1093  libpq_gettext("TABLE NAME: %s\n"), val);
1095  if (val)
1096  appendPQExpBuffer(msg,
1097  libpq_gettext("COLUMN NAME: %s\n"), val);
1099  if (val)
1100  appendPQExpBuffer(msg,
1101  libpq_gettext("DATATYPE NAME: %s\n"), val);
1103  if (val)
1104  appendPQExpBuffer(msg,
1105  libpq_gettext("CONSTRAINT NAME: %s\n"), val);
1106  }
1107  if (verbosity == PQERRORS_VERBOSE)
1108  {
1109  const char *valf;
1110  const char *vall;
1111 
1115  if (val || valf || vall)
1116  {
1117  appendPQExpBufferStr(msg, libpq_gettext("LOCATION: "));
1118  if (val)
1119  appendPQExpBuffer(msg, libpq_gettext("%s, "), val);
1120  if (valf && vall) /* unlikely we'd have just one */
1121  appendPQExpBuffer(msg, libpq_gettext("%s:%s"),
1122  valf, vall);
1123  appendPQExpBufferChar(msg, '\n');
1124  }
1125  }
1126 }
PGMessageField * errFields
Definition: libpq-int.h:199
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:54
#define PG_DIAG_SCHEMA_NAME
Definition: postgres_ext.h:61
#define PG_DIAG_MESSAGE_DETAIL
Definition: postgres_ext.h:55
#define PG_DIAG_COLUMN_NAME
Definition: postgres_ext.h:63
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
#define PG_DIAG_TABLE_NAME
Definition: postgres_ext.h:62
#define PG_DIAG_SOURCE_LINE
Definition: postgres_ext.h:67
#define PG_DIAG_INTERNAL_POSITION
Definition: postgres_ext.h:58
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:53
char * errMsg
Definition: libpq-int.h:198
#define PG_DIAG_SOURCE_FILE
Definition: postgres_ext.h:66
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:262
static void reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding)
#define PG_DIAG_SEVERITY
Definition: postgres_ext.h:51
#define PG_DIAG_STATEMENT_POSITION
Definition: postgres_ext.h:57
char * errQuery
Definition: libpq-int.h:200
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:396
#define PG_DIAG_DATATYPE_NAME
Definition: postgres_ext.h:64
#define PG_DIAG_CONSTRAINT_NAME
Definition: postgres_ext.h:65
#define PG_DIAG_INTERNAL_QUERY
Definition: postgres_ext.h:59
#define PG_DIAG_MESSAGE_HINT
Definition: postgres_ext.h:56
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:2658
#define NULL
Definition: c.h:226
#define PG_DIAG_SOURCE_FUNCTION
Definition: postgres_ext.h:68
ExecStatusType resultStatus
Definition: libpq-int.h:179
long val
Definition: informix.c:689
#define PG_DIAG_CONTEXT
Definition: postgres_ext.h:60
#define libpq_gettext(x)
Definition: libpq-int.h:689
int client_encoding
Definition: libpq-int.h:191
char* pqBuildStartupPacket3 ( PGconn conn,
int *  packetlen,
const PQEnvironmentOption options 
)

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

References build_startup_packet(), malloc, and NULL.

Referenced by PQconnectPoll().

2120 {
2121  char *startpacket;
2122 
2123  *packetlen = build_startup_packet(conn, NULL, options);
2124  startpacket = (char *) malloc(*packetlen);
2125  if (!startpacket)
2126  return NULL;
2127  *packetlen = build_startup_packet(conn, startpacket, options);
2128  return startpacket;
2129 }
static int build_startup_packet(const PGconn *conn, char *packet, const PQEnvironmentOption *options)
#define malloc(a)
Definition: header.h:45
#define NULL
Definition: c.h:226
int pqEndcopy3 ( PGconn conn)

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

References pg_conn::asyncStatus, 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(), printfPQExpBuffer(), pg_conn::queryclass, resetPQExpBuffer(), and pg_result::resultStatus.

Referenced by PQendcopy().

1809 {
1810  PGresult *result;
1811 
1812  if (conn->asyncStatus != PGASYNC_COPY_IN &&
1813  conn->asyncStatus != PGASYNC_COPY_OUT &&
1814  conn->asyncStatus != PGASYNC_COPY_BOTH)
1815  {
1817  libpq_gettext("no COPY in progress\n"));
1818  return 1;
1819  }
1820 
1821  /* Send the CopyDone message if needed */
1822  if (conn->asyncStatus == PGASYNC_COPY_IN ||
1823  conn->asyncStatus == PGASYNC_COPY_BOTH)
1824  {
1825  if (pqPutMsgStart('c', false, conn) < 0 ||
1826  pqPutMsgEnd(conn) < 0)
1827  return 1;
1828 
1829  /*
1830  * If we sent the COPY command in extended-query mode, we must issue a
1831  * Sync as well.
1832  */
1833  if (conn->queryclass != PGQUERY_SIMPLE)
1834  {
1835  if (pqPutMsgStart('S', false, conn) < 0 ||
1836  pqPutMsgEnd(conn) < 0)
1837  return 1;
1838  }
1839  }
1840 
1841  /*
1842  * make sure no data is waiting to be sent, abort if we are non-blocking
1843  * and the flush fails
1844  */
1845  if (pqFlush(conn) && pqIsnonblocking(conn))
1846  return 1;
1847 
1848  /* Return to active duty */
1849  conn->asyncStatus = PGASYNC_BUSY;
1851 
1852  /*
1853  * Non blocking connections may have to abort at this point. If everyone
1854  * played the game there should be no problem, but in error scenarios the
1855  * expected messages may not have arrived yet. (We are assuming that the
1856  * backend's packetizing will ensure that CommandComplete arrives along
1857  * with the CopyDone; are there corner cases where that doesn't happen?)
1858  */
1859  if (pqIsnonblocking(conn) && PQisBusy(conn))
1860  return 1;
1861 
1862  /* Wait for the completion response */
1863  result = PQgetResult(conn);
1864 
1865  /* Expecting a successful result */
1866  if (result && result->resultStatus == PGRES_COMMAND_OK)
1867  {
1868  PQclear(result);
1869  return 0;
1870  }
1871 
1872  /*
1873  * Trouble. For backwards-compatibility reasons, we issue the error
1874  * message as if it were a notice (would be nice to get rid of this
1875  * silliness, but too many apps probably don't handle errors from
1876  * PQendcopy reasonably). Note that the app can still obtain the error
1877  * status from the PGconn object.
1878  */
1879  if (conn->errorMessage.len > 0)
1880  {
1881  /* We have to strip the trailing newline ... pain in neck... */
1882  char svLast = conn->errorMessage.data[conn->errorMessage.len - 1];
1883 
1884  if (svLast == '\n')
1885  conn->errorMessage.data[conn->errorMessage.len - 1] = '\0';
1886  pqInternalNotice(&conn->noticeHooks, "%s", conn->errorMessage.data);
1887  conn->errorMessage.data[conn->errorMessage.len - 1] = svLast;
1888  }
1889 
1890  PQclear(result);
1891 
1892  return 1;
1893 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:966
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
#define pqIsnonblocking(conn)
Definition: libpq-int.h:683
PGQueryClass queryclass
Definition: libpq-int.h:383
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:524
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:381
PGNoticeHooks noticeHooks
Definition: libpq-int.h:372
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:801
PQExpBufferData errorMessage
Definition: libpq-int.h:498
void PQclear(PGresult *res)
Definition: fe-exec.c:650
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:1681
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:592
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
ExecStatusType resultStatus
Definition: libpq-int.h:179
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1702
#define libpq_gettext(x)
Definition: libpq-int.h:689
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 1902 of file fe-protocol3.c.

References pg_conn::errorMessage, FALSE, getNotify(), getParameterStatus(), getReadyForQuery(), handleSyncLoss(), i, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, PQArgBlock::integer, PQArgBlock::len, libpq_gettext, NULL, PGRES_COMMAND_OK, PGRES_FATAL_ERROR, pqCheckInBufferSpace(), pqFlush(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGetnchar(), pqHandleSendFailure(), PQmakeEmptyPGresult(), pqPrepareAsyncResult(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), pqReadData(), pqSaveErrorResult(), pqWait(), printfPQExpBuffer(), PQArgBlock::ptr, pg_conn::result, status(), TRUE, and VALID_LONG_MESSAGE_TYPE.

Referenced by PQfn().

1906 {
1907  bool needInput = false;
1909  char id;
1910  int msgLength;
1911  int avail;
1912  int i;
1913 
1914  /* PQfn already validated connection state */
1915 
1916  if (pqPutMsgStart('F', false, conn) < 0 || /* function call msg */
1917  pqPutInt(fnid, 4, conn) < 0 || /* function id */
1918  pqPutInt(1, 2, conn) < 0 || /* # of format codes */
1919  pqPutInt(1, 2, conn) < 0 || /* format code: BINARY */
1920  pqPutInt(nargs, 2, conn) < 0) /* # of args */
1921  {
1922  pqHandleSendFailure(conn);
1923  return NULL;
1924  }
1925 
1926  for (i = 0; i < nargs; ++i)
1927  { /* len.int4 + contents */
1928  if (pqPutInt(args[i].len, 4, conn))
1929  {
1930  pqHandleSendFailure(conn);
1931  return NULL;
1932  }
1933  if (args[i].len == -1)
1934  continue; /* it's NULL */
1935 
1936  if (args[i].isint)
1937  {
1938  if (pqPutInt(args[i].u.integer, args[i].len, conn))
1939  {
1940  pqHandleSendFailure(conn);
1941  return NULL;
1942  }
1943  }
1944  else
1945  {
1946  if (pqPutnchar((char *) args[i].u.ptr, args[i].len, conn))
1947  {
1948  pqHandleSendFailure(conn);
1949  return NULL;
1950  }
1951  }
1952  }
1953 
1954  if (pqPutInt(1, 2, conn) < 0) /* result format code: BINARY */
1955  {
1956  pqHandleSendFailure(conn);
1957  return NULL;
1958  }
1959 
1960  if (pqPutMsgEnd(conn) < 0 ||
1961  pqFlush(conn))
1962  {
1963  pqHandleSendFailure(conn);
1964  return NULL;
1965  }
1966 
1967  for (;;)
1968  {
1969  if (needInput)
1970  {
1971  /* Wait for some data to arrive (or for the channel to close) */
1972  if (pqWait(TRUE, FALSE, conn) ||
1973  pqReadData(conn) < 0)
1974  break;
1975  }
1976 
1977  /*
1978  * Scan the message. If we run out of data, loop around to try again.
1979  */
1980  needInput = true;
1981 
1982  conn->inCursor = conn->inStart;
1983  if (pqGetc(&id, conn))
1984  continue;
1985  if (pqGetInt(&msgLength, 4, conn))
1986  continue;
1987 
1988  /*
1989  * Try to validate message type/length here. A length less than 4 is
1990  * definitely broken. Large lengths should only be believed for a few
1991  * message types.
1992  */
1993  if (msgLength < 4)
1994  {
1995  handleSyncLoss(conn, id, msgLength);
1996  break;
1997  }
1998  if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
1999  {
2000  handleSyncLoss(conn, id, msgLength);
2001  break;
2002  }
2003 
2004  /*
2005  * Can't process if message body isn't all here yet.
2006  */
2007  msgLength -= 4;
2008  avail = conn->inEnd - conn->inCursor;
2009  if (avail < msgLength)
2010  {
2011  /*
2012  * Before looping, enlarge the input buffer if needed to hold the
2013  * whole message. See notes in parseInput.
2014  */
2015  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
2016  conn))
2017  {
2018  /*
2019  * XXX add some better recovery code... plan is to skip over
2020  * the message using its length, then report an error. For the
2021  * moment, just treat this like loss of sync (which indeed it
2022  * might be!)
2023  */
2024  handleSyncLoss(conn, id, msgLength);
2025  break;
2026  }
2027  continue;
2028  }
2029 
2030  /*
2031  * We should see V or E response to the command, but might get N
2032  * and/or A notices first. We also need to swallow the final Z before
2033  * returning.
2034  */
2035  switch (id)
2036  {
2037  case 'V': /* function result */
2038  if (pqGetInt(actual_result_len, 4, conn))
2039  continue;
2040  if (*actual_result_len != -1)
2041  {
2042  if (result_is_int)
2043  {
2044  if (pqGetInt(result_buf, *actual_result_len, conn))
2045  continue;
2046  }
2047  else
2048  {
2049  if (pqGetnchar((char *) result_buf,
2050  *actual_result_len,
2051  conn))
2052  continue;
2053  }
2054  }
2055  /* correctly finished function result message */
2056  status = PGRES_COMMAND_OK;
2057  break;
2058  case 'E': /* error return */
2059  if (pqGetErrorNotice3(conn, true))
2060  continue;
2061  status = PGRES_FATAL_ERROR;
2062  break;
2063  case 'A': /* notify message */
2064  /* handle notify and go back to processing return values */
2065  if (getNotify(conn))
2066  continue;
2067  break;
2068  case 'N': /* notice */
2069  /* handle notice and go back to processing return values */
2070  if (pqGetErrorNotice3(conn, false))
2071  continue;
2072  break;
2073  case 'Z': /* backend is ready for new query */
2074  if (getReadyForQuery(conn))
2075  continue;
2076  /* consume the message and exit */
2077  conn->inStart += 5 + msgLength;
2078  /* if we saved a result object (probably an error), use it */
2079  if (conn->result)
2080  return pqPrepareAsyncResult(conn);
2081  return PQmakeEmptyPGresult(conn, status);
2082  case 'S': /* parameter status */
2083  if (getParameterStatus(conn))
2084  continue;
2085  break;
2086  default:
2087  /* The backend violates the protocol. */
2089  libpq_gettext("protocol error: id=0x%x\n"),
2090  id);
2091  pqSaveErrorResult(conn);
2092  /* trust the specified message length as what to skip */
2093  conn->inStart += 5 + msgLength;
2094  return pqPrepareAsyncResult(conn);
2095  }
2096  /* Completed this message, keep going */
2097  /* trust the specified message length as what to skip */
2098  conn->inStart += 5 + msgLength;
2099  needInput = false;
2100  }
2101 
2102  /*
2103  * We fall out of the loop only upon failing to read data.
2104  * conn->errorMessage has been set by pqWait or pqReadData. We want to
2105  * append it to any already-received error message.
2106  */
2107  pqSaveErrorResult(conn);
2108  return pqPrepareAsyncResult(conn);
2109 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:966
int inEnd
Definition: libpq-int.h:437
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
void pqHandleSendFailure(PGconn *conn)
Definition: fe-exec.c:1582
int inStart
Definition: libpq-int.h:435
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:413
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:524
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:272
ExecStatusType
Definition: libpq-fe.h:82
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:200
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:756
PGresult * result
Definition: libpq-int.h:454
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:312
#define FALSE
Definition: c.h:218
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:876
int pqReadData(PGconn *conn)
Definition: fe-misc.c:634
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:989
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:140
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:99
#define VALID_LONG_MESSAGE_TYPE(id)
Definition: fe-protocol3.c:41
PQExpBufferData errorMessage
Definition: libpq-int.h:498
#define NULL
Definition: c.h:226
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:251
static int getReadyForQuery(PGconn *conn)
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:592
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:450
#define TRUE
Definition: c.h:214
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:728
int inCursor
Definition: libpq-int.h:436
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:222
int * ptr
Definition: libpq-fe.h:226
#define libpq_gettext(x)
Definition: libpq-int.h:689
int integer
Definition: libpq-fe.h:227
int pqGetCopyData3 ( PGconn conn,
char **  buffer,
int  async 
)

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

References pg_conn::errorMessage, FALSE, getCopyDataMessage(), pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inStart, libpq_gettext, malloc, NULL, pqReadData(), pqWait(), printfPQExpBuffer(), and TRUE.

Referenced by PQgetCopyData().

1642 {
1643  int msgLength;
1644 
1645  for (;;)
1646  {
1647  /*
1648  * Collect the next input message. To make life simpler for async
1649  * callers, we keep returning 0 until the next message is fully
1650  * available, even if it is not Copy Data.
1651  */
1652  msgLength = getCopyDataMessage(conn);
1653  if (msgLength < 0)
1654  return msgLength; /* end-of-copy or error */
1655  if (msgLength == 0)
1656  {
1657  /* Don't block if async read requested */
1658  if (async)
1659  return 0;
1660  /* Need to load more data */
1661  if (pqWait(TRUE, FALSE, conn) ||
1662  pqReadData(conn) < 0)
1663  return -2;
1664  continue;
1665  }
1666 
1667  /*
1668  * Drop zero-length messages (shouldn't happen anyway). Otherwise
1669  * pass the data back to the caller.
1670  */
1671  msgLength -= 4;
1672  if (msgLength > 0)
1673  {
1674  *buffer = (char *) malloc(msgLength + 1);
1675  if (*buffer == NULL)
1676  {
1678  libpq_gettext("out of memory\n"));
1679  return -2;
1680  }
1681  memcpy(*buffer, &conn->inBuffer[conn->inCursor], msgLength);
1682  (*buffer)[msgLength] = '\0'; /* Add terminating null */
1683 
1684  /* Mark message consumed */
1685  conn->inStart = conn->inCursor + msgLength;
1686 
1687  return msgLength;
1688  }
1689 
1690  /* Empty, so drop it and loop around for another */
1691  conn->inStart = conn->inCursor;
1692  }
1693 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
int inStart
Definition: libpq-int.h:435
#define malloc(a)
Definition: header.h:45
#define FALSE
Definition: c.h:218
int pqReadData(PGconn *conn)
Definition: fe-misc.c:634
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:989
char * inBuffer
Definition: libpq-int.h:433
static int getCopyDataMessage(PGconn *conn)
PQExpBufferData errorMessage
Definition: libpq-int.h:498
#define NULL
Definition: c.h:226
#define TRUE
Definition: c.h:214
int inCursor
Definition: libpq-int.h:436
#define libpq_gettext(x)
Definition: libpq-int.h:689
int pqGetErrorNotice3 ( PGconn conn,
bool  isError 
)

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

References appendPQExpBufferStr(), PQExpBufferData::data, pg_result::errMsg, pg_conn::errorMessage, pg_result::errQuery, initPQExpBuffer(), pg_conn::last_query, pg_conn::last_sqlstate, libpq_gettext, pg_result::noticeHooks, PGNoticeHooks::noticeRec, PGNoticeHooks::noticeRecArg, NULL, PG_DIAG_SQLSTATE, PG_DIAG_STATEMENT_POSITION, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PGRES_NONFATAL_ERROR, pqBuildErrorMessage3(), PQclear(), pqClearAsyncResult(), PQExpBufferDataBroken, pqGetc(), pqGets(), PQmakeEmptyPGresult(), pqResultStrdup(), pqSaveMessageField(), printfPQExpBuffer(), resetPQExpBuffer(), pg_conn::result, pg_result::resultStatus, pg_conn::show_context, strlcpy(), termPQExpBuffer(), and pg_conn::verbosity.

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

877 {
878  PGresult *res = NULL;
879  bool have_position = false;
880  PQExpBufferData workBuf;
881  char id;
882 
883  /*
884  * Since the fields might be pretty long, we create a temporary
885  * PQExpBuffer rather than using conn->workBuffer. workBuffer is intended
886  * for stuff that is expected to be short. We shouldn't use
887  * conn->errorMessage either, since this might be only a notice.
888  */
889  initPQExpBuffer(&workBuf);
890 
891  /*
892  * Make a PGresult to hold the accumulated fields. We temporarily lie
893  * about the result status, so that PQmakeEmptyPGresult doesn't uselessly
894  * copy conn->errorMessage.
895  *
896  * NB: This allocation can fail, if you run out of memory. The rest of the
897  * function handles that gracefully, and we still try to set the error
898  * message as the connection's error message.
899  */
901  if (res)
903 
904  /*
905  * Read the fields and save into res.
906  *
907  * While at it, save the SQLSTATE in conn->last_sqlstate, and note whether
908  * we saw a PG_DIAG_STATEMENT_POSITION field.
909  */
910  for (;;)
911  {
912  if (pqGetc(&id, conn))
913  goto fail;
914  if (id == '\0')
915  break; /* terminator found */
916  if (pqGets(&workBuf, conn))
917  goto fail;
918  pqSaveMessageField(res, id, workBuf.data);
919  if (id == PG_DIAG_SQLSTATE)
920  strlcpy(conn->last_sqlstate, workBuf.data,
921  sizeof(conn->last_sqlstate));
922  else if (id == PG_DIAG_STATEMENT_POSITION)
923  have_position = true;
924  }
925 
926  /*
927  * Save the active query text, if any, into res as well; but only if we
928  * might need it for an error cursor display, which is only true if there
929  * is a PG_DIAG_STATEMENT_POSITION field.
930  */
931  if (have_position && conn->last_query && res)
932  res->errQuery = pqResultStrdup(res, conn->last_query);
933 
934  /*
935  * Now build the "overall" error message for PQresultErrorMessage.
936  */
937  resetPQExpBuffer(&workBuf);
938  pqBuildErrorMessage3(&workBuf, res, conn->verbosity, conn->show_context);
939 
940  /*
941  * Either save error as current async result, or just emit the notice.
942  */
943  if (isError)
944  {
945  if (res)
946  res->errMsg = pqResultStrdup(res, workBuf.data);
947  pqClearAsyncResult(conn);
948  conn->result = res;
949  if (PQExpBufferDataBroken(workBuf))
951  libpq_gettext("out of memory"));
952  else
953  appendPQExpBufferStr(&conn->errorMessage, workBuf.data);
954  }
955  else
956  {
957  /* if we couldn't allocate the result set, just discard the NOTICE */
958  if (res)
959  {
960  /* We can cheat a little here and not copy the message. */
961  res->errMsg = workBuf.data;
962  if (res->noticeHooks.noticeRec != NULL)
963  (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
964  PQclear(res);
965  }
966  }
967 
968  termPQExpBuffer(&workBuf);
969  return 0;
970 
971 fail:
972  PQclear(res);
973  termPQExpBuffer(&workBuf);
974  return EOF;
975 }
PGContextVisibility show_context
Definition: libpq-int.h:429
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:168
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:53
char * errMsg
Definition: libpq-int.h:198
PGresult * result
Definition: libpq-int.h:454
PGNoticeHooks noticeHooks
Definition: libpq-int.h:188
PGVerbosity verbosity
Definition: libpq-int.h:428
PQnoticeReceiver noticeRec
Definition: libpq-int.h:154
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:140
char * last_query
Definition: libpq-int.h:384
#define PG_DIAG_STATEMENT_POSITION
Definition: postgres_ext.h:57
char * errQuery
Definition: libpq-int.h:200
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:99
void pqSaveMessageField(PGresult *res, char code, const char *value)
Definition: fe-exec.c:891
PQExpBufferData errorMessage
Definition: libpq-int.h:498
void PQclear(PGresult *res)
Definition: fe-exec.c:650
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
#define NULL
Definition: c.h:226
void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
Definition: fe-protocol3.c:982
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:705
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
ExecStatusType resultStatus
Definition: libpq-int.h:179
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
#define libpq_gettext(x)
Definition: libpq-int.h:689
char * pqResultStrdup(PGresult *res, const char *str)
Definition: fe-exec.c:602
void * noticeRecArg
Definition: libpq-int.h:155
char last_sqlstate[6]
Definition: libpq-int.h:385
int pqGetline3 ( PGconn conn,
char *  s,
int  maxlen 
)

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

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

Referenced by PQgetline().

1702 {
1703  int status;
1704 
1705  if (conn->sock == PGINVALID_SOCKET ||
1706  (conn->asyncStatus != PGASYNC_COPY_OUT &&
1707  conn->asyncStatus != PGASYNC_COPY_BOTH) ||
1708  conn->copy_is_binary)
1709  {
1711  libpq_gettext("PQgetline: not doing text COPY OUT\n"));
1712  *s = '\0';
1713  return EOF;
1714  }
1715 
1716  while ((status = PQgetlineAsync(conn, s, maxlen - 1)) == 0)
1717  {
1718  /* need to load more data */
1719  if (pqWait(TRUE, FALSE, conn) ||
1720  pqReadData(conn) < 0)
1721  {
1722  *s = '\0';
1723  return EOF;
1724  }
1725  }
1726 
1727  if (status < 0)
1728  {
1729  /* End of copy detected; gin up old-style terminator */
1730  strcpy(s, "\\.");
1731  return 0;
1732  }
1733 
1734  /* Add null terminator, and strip trailing \n if present */
1735  if (s[status - 1] == '\n')
1736  {
1737  s[status - 1] = '\0';
1738  return 0;
1739  }
1740  else
1741  {
1742  s[status] = '\0';
1743  return 1;
1744  }
1745 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
int PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
Definition: fe-exec.c:2469
char copy_is_binary
Definition: libpq-int.h:390
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:381
#define FALSE
Definition: c.h:218
int pqReadData(PGconn *conn)
Definition: fe-misc.c:634
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:989
pgsocket sock
Definition: libpq-int.h:402
#define PGINVALID_SOCKET
Definition: port.h:24
PQExpBufferData errorMessage
Definition: libpq-int.h:498
#define TRUE
Definition: c.h:214
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:222
#define libpq_gettext(x)
Definition: libpq-int.h:689
int pqGetlineAsync3 ( PGconn conn,
char *  buffer,
int  bufsize 
)

Definition at line 1753 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().

1754 {
1755  int msgLength;
1756  int avail;
1757 
1758  if (conn->asyncStatus != PGASYNC_COPY_OUT
1759  && conn->asyncStatus != PGASYNC_COPY_BOTH)
1760  return -1; /* we are not doing a copy... */
1761 
1762  /*
1763  * Recognize the next input message. To make life simpler for async
1764  * callers, we keep returning 0 until the next message is fully available
1765  * even if it is not Copy Data. This should keep PQendcopy from blocking.
1766  * (Note: unlike pqGetCopyData3, we do not change asyncStatus here.)
1767  */
1768  msgLength = getCopyDataMessage(conn);
1769  if (msgLength < 0)
1770  return -1; /* end-of-copy or error */
1771  if (msgLength == 0)
1772  return 0; /* no data yet */
1773 
1774  /*
1775  * Move data from libpq's buffer to the caller's. In the case where a
1776  * prior call found the caller's buffer too small, we use
1777  * conn->copy_already_done to remember how much of the row was already
1778  * returned to the caller.
1779  */
1780  conn->inCursor += conn->copy_already_done;
1781  avail = msgLength - 4 - conn->copy_already_done;
1782  if (avail <= bufsize)
1783  {
1784  /* Able to consume the whole message */
1785  memcpy(buffer, &conn->inBuffer[conn->inCursor], avail);
1786  /* Mark message consumed */
1787  conn->inStart = conn->inCursor + avail;
1788  /* Reset state for next time */
1789  conn->copy_already_done = 0;
1790  return avail;
1791  }
1792  else
1793  {
1794  /* We must return a partial message */
1795  memcpy(buffer, &conn->inBuffer[conn->inCursor], bufsize);
1796  /* The message is NOT consumed from libpq's buffer */
1797  conn->copy_already_done += bufsize;
1798  return bufsize;
1799  }
1800 }
int inStart
Definition: libpq-int.h:435
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:381
char * inBuffer
Definition: libpq-int.h:433
static int getCopyDataMessage(PGconn *conn)
int copy_already_done
Definition: libpq-int.h:391
int inCursor
Definition: libpq-int.h:436
void pqParseInput3 ( PGconn conn)

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

References pg_conn::asyncStatus, pg_conn::be_key, pg_conn::be_pid, 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::inCursor, pg_conn::inEnd, pg_conn::inStart, libpq_gettext, pg_conn::noticeHooks, NULL, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_READY, PGQUERY_DESCRIBE, PGQUERY_PREPARE, PGRES_COMMAND_OK, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PGRES_TUPLES_OK, pqCheckInBufferSpace(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGets(), pqInternalNotice(), PQmakeEmptyPGresult(), pqSaveErrorResult(), printfPQExpBuffer(), pg_conn::queryclass, pg_conn::result, pg_result::resultStatus, strlcpy(), VALID_LONG_MESSAGE_TYPE, and pg_conn::workBuffer.

Referenced by parseInput().

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

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

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

Referenced by pqBuildErrorMessage3().

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