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 "port/pg_bswap.h"
#include <unistd.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 40 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 2140 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().

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

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

References 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(), printfPQExpBuffer(), realloc, pg_conn::result, pg_conn::rowBuf, pg_conn::rowBufLen, and pgDataValue::value.

Referenced by pqParseInput3().

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

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

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

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

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

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

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

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

References 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(), printfPQExpBuffer(), pg_conn::result, TRUE, and pgresParamDesc::typid.

Referenced by pqParseInput3().

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

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

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

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

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

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

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

Referenced by pqFunctionCall3(), and pqParseInput3().

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

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

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

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

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

Definition at line 981 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_TERSE, PQERRORS_VERBOSE, PQresultErrorField(), PQSHOW_CONTEXT_ALWAYS, PQSHOW_CONTEXT_ERRORS, reportErrorPosition(), pg_result::resultStatus, and val.

Referenced by pqGetErrorNotice3(), and PQresultVerboseErrorMessage().

983 {
984  const char *val;
985  const char *querytext = NULL;
986  int querypos = 0;
987 
988  /* If we couldn't allocate a PGresult, just say "out of memory" */
989  if (res == NULL)
990  {
991  appendPQExpBuffer(msg, libpq_gettext("out of memory\n"));
992  return;
993  }
994 
995  /*
996  * If we don't have any broken-down fields, just return the base message.
997  * This mainly applies if we're given a libpq-generated error result.
998  */
999  if (res->errFields == NULL)
1000  {
1001  if (res->errMsg && res->errMsg[0])
1002  appendPQExpBufferStr(msg, res->errMsg);
1003  else
1004  appendPQExpBuffer(msg, libpq_gettext("no error message available\n"));
1005  return;
1006  }
1007 
1008  /* Else build error message from relevant fields */
1010  if (val)
1011  appendPQExpBuffer(msg, "%s: ", val);
1012  if (verbosity == PQERRORS_VERBOSE)
1013  {
1015  if (val)
1016  appendPQExpBuffer(msg, "%s: ", val);
1017  }
1019  if (val)
1020  appendPQExpBufferStr(msg, val);
1022  if (val)
1023  {
1024  if (verbosity != PQERRORS_TERSE && res->errQuery != NULL)
1025  {
1026  /* emit position as a syntax cursor display */
1027  querytext = res->errQuery;
1028  querypos = atoi(val);
1029  }
1030  else
1031  {
1032  /* emit position as text addition to primary message */
1033  /* translator: %s represents a digit string */
1034  appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1035  val);
1036  }
1037  }
1038  else
1039  {
1041  if (val)
1042  {
1043  querytext = PQresultErrorField(res, PG_DIAG_INTERNAL_QUERY);
1044  if (verbosity != PQERRORS_TERSE && querytext != NULL)
1045  {
1046  /* emit position as a syntax cursor display */
1047  querypos = atoi(val);
1048  }
1049  else
1050  {
1051  /* emit position as text addition to primary message */
1052  /* translator: %s represents a digit string */
1053  appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1054  val);
1055  }
1056  }
1057  }
1058  appendPQExpBufferChar(msg, '\n');
1059  if (verbosity != PQERRORS_TERSE)
1060  {
1061  if (querytext && querypos > 0)
1062  reportErrorPosition(msg, querytext, querypos,
1063  res->client_encoding);
1065  if (val)
1066  appendPQExpBuffer(msg, libpq_gettext("DETAIL: %s\n"), val);
1068  if (val)
1069  appendPQExpBuffer(msg, libpq_gettext("HINT: %s\n"), val);
1071  if (val)
1072  appendPQExpBuffer(msg, libpq_gettext("QUERY: %s\n"), val);
1073  if (show_context == PQSHOW_CONTEXT_ALWAYS ||
1074  (show_context == PQSHOW_CONTEXT_ERRORS &&
1076  {
1077  val = PQresultErrorField(res, PG_DIAG_CONTEXT);
1078  if (val)
1079  appendPQExpBuffer(msg, libpq_gettext("CONTEXT: %s\n"),
1080  val);
1081  }
1082  }
1083  if (verbosity == PQERRORS_VERBOSE)
1084  {
1086  if (val)
1087  appendPQExpBuffer(msg,
1088  libpq_gettext("SCHEMA NAME: %s\n"), val);
1090  if (val)
1091  appendPQExpBuffer(msg,
1092  libpq_gettext("TABLE NAME: %s\n"), val);
1094  if (val)
1095  appendPQExpBuffer(msg,
1096  libpq_gettext("COLUMN NAME: %s\n"), val);
1098  if (val)
1099  appendPQExpBuffer(msg,
1100  libpq_gettext("DATATYPE NAME: %s\n"), val);
1102  if (val)
1103  appendPQExpBuffer(msg,
1104  libpq_gettext("CONSTRAINT NAME: %s\n"), val);
1105  }
1106  if (verbosity == PQERRORS_VERBOSE)
1107  {
1108  const char *valf;
1109  const char *vall;
1110 
1114  if (val || valf || vall)
1115  {
1116  appendPQExpBufferStr(msg, libpq_gettext("LOCATION: "));
1117  if (val)
1118  appendPQExpBuffer(msg, libpq_gettext("%s, "), val);
1119  if (valf && vall) /* unlikely we'd have just one */
1120  appendPQExpBuffer(msg, libpq_gettext("%s:%s"),
1121  valf, vall);
1122  appendPQExpBufferChar(msg, '\n');
1123  }
1124  }
1125 }
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:385
#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:262
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:396
#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:2709
#define PG_DIAG_SOURCE_FUNCTION
Definition: postgres_ext.h:72
ExecStatusType resultStatus
Definition: libpq-int.h:177
long val
Definition: informix.c:689
#define PG_DIAG_CONTEXT
Definition: postgres_ext.h:64
#define libpq_gettext(x)
Definition: libpq-int.h:682
int client_encoding
Definition: libpq-int.h:189
char* pqBuildStartupPacket3 ( PGconn conn,
int *  packetlen,
const PQEnvironmentOption options 
)

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

References build_startup_packet(), and malloc.

Referenced by PQconnectPoll().

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

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

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

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

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

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

Referenced by PQgetCopyData().

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

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

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

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

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

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

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

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

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

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

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