PostgreSQL Source Code  git master
fe-protocol3.c File Reference
#include "postgres_fe.h"
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
#include "libpq-fe.h"
#include "libpq-int.h"
#include "mb/pg_wchar.h"
#include "port/pg_bswap.h"
Include dependency graph for fe-protocol3.c:

Go to the source code of this file.

Macros

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

Functions

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

Macro Definition Documentation

◆ ADD_STARTUP_OPTION

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

Referenced by build_startup_packet().

◆ DISPLAY_SIZE

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

Referenced by reportErrorPosition().

◆ MIN_RIGHT_CUT

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

Referenced by reportErrorPosition().

◆ VALID_LONG_MESSAGE_TYPE

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

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

Referenced by pqFunctionCall3(), and pqParseInput3().

Function Documentation

◆ build_startup_packet()

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

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

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

◆ getAnotherTuple()

static int getAnotherTuple ( PGconn conn,
int  msgLength 
)
static

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

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

◆ getCopyDataMessage()

static int getCopyDataMessage ( PGconn conn)
static

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

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

◆ getCopyStart()

static int getCopyStart ( PGconn conn,
ExecStatusType  copytype 
)
static

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

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

Referenced by pqParseInput3().

1470 {
1471  PGresult *result;
1472  int nfields;
1473  int i;
1474 
1475  result = PQmakeEmptyPGresult(conn, copytype);
1476  if (!result)
1477  goto failure;
1478 
1479  if (pqGetc(&conn->copy_is_binary, conn))
1480  goto failure;
1481  result->binary = conn->copy_is_binary;
1482  /* the next two bytes are the number of fields */
1483  if (pqGetInt(&(result->numAttributes), 2, conn))
1484  goto failure;
1485  nfields = result->numAttributes;
1486 
1487  /* allocate space for the attribute descriptors */
1488  if (nfields > 0)
1489  {
1490  result->attDescs = (PGresAttDesc *)
1491  pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
1492  if (!result->attDescs)
1493  goto failure;
1494  MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
1495  }
1496 
1497  for (i = 0; i < nfields; i++)
1498  {
1499  int format;
1500 
1501  if (pqGetInt(&format, 2, conn))
1502  goto failure;
1503 
1504  /*
1505  * Since pqGetInt treats 2-byte integers as unsigned, we need to
1506  * coerce these results to signed form.
1507  */
1508  format = (int) ((int16) format);
1509  result->attDescs[i].format = format;
1510  }
1511 
1512  /* Success! */
1513  conn->result = result;
1514  return 0;
1515 
1516 failure:
1517  PQclear(result);
1518  return EOF;
1519 }
signed short int16
Definition: c.h:354
char copy_is_binary
Definition: libpq-int.h:398
#define MemSet(start, val, len)
Definition: c.h:971
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:253
PGresAttDesc * attDescs
Definition: libpq-int.h:171
PGresult * result
Definition: libpq-int.h:465
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:141
int binary
Definition: libpq-int.h:179
int numAttributes
Definition: libpq-int.h:170
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:80
void PQclear(PGresult *res)
Definition: fe-exec.c:694
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:534
int i
static char format

◆ getNotify()

static int getNotify ( PGconn conn)
static

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

1414 {
1415  int be_pid;
1416  char *svname;
1417  int nmlen;
1418  int extralen;
1419  PGnotify *newNotify;
1420 
1421  if (pqGetInt(&be_pid, 4, conn))
1422  return EOF;
1423  if (pqGets(&conn->workBuffer, conn))
1424  return EOF;
1425  /* must save name while getting extra string */
1426  svname = strdup(conn->workBuffer.data);
1427  if (!svname)
1428  return EOF;
1429  if (pqGets(&conn->workBuffer, conn))
1430  {
1431  free(svname);
1432  return EOF;
1433  }
1434 
1435  /*
1436  * Store the strings right after the PQnotify structure so it can all be
1437  * freed at once. We don't use NAMEDATALEN because we don't want to tie
1438  * this interface to a specific server name length.
1439  */
1440  nmlen = strlen(svname);
1441  extralen = strlen(conn->workBuffer.data);
1442  newNotify = (PGnotify *) malloc(sizeof(PGnotify) + nmlen + extralen + 2);
1443  if (newNotify)
1444  {
1445  newNotify->relname = (char *) newNotify + sizeof(PGnotify);
1446  strcpy(newNotify->relname, svname);
1447  newNotify->extra = newNotify->relname + nmlen + 1;
1448  strcpy(newNotify->extra, conn->workBuffer.data);
1449  newNotify->be_pid = be_pid;
1450  newNotify->next = NULL;
1451  if (conn->notifyTail)
1452  conn->notifyTail->next = newNotify;
1453  else
1454  conn->notifyHead = newNotify;
1455  conn->notifyTail = newNotify;
1456  }
1457 
1458  free(svname);
1459  return 0;
1460 }
char * extra
Definition: libpq-fe.h:168
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:149
PQExpBufferData workBuffer
Definition: libpq-int.h:529
PGnotify * notifyHead
Definition: libpq-int.h:400
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:253
#define malloc(a)
Definition: header.h:50
int be_pid
Definition: libpq-fe.h:167
char * relname
Definition: libpq-fe.h:166
struct pgNotify * next
Definition: libpq-fe.h:170
#define free(a)
Definition: header.h:65
PGnotify * notifyTail
Definition: libpq-int.h:401

◆ getParamDescriptions()

static int getParamDescriptions ( PGconn conn,
int  msgLength 
)
static

Definition at line 646 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, and pgresParamDesc::typid.

Referenced by pqParseInput3().

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

◆ getParameterStatus()

static int getParameterStatus ( PGconn conn)
static

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

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

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

1385 {
1386  PQExpBufferData valueBuf;
1387 
1388  /* Get the parameter name */
1389  if (pqGets(&conn->workBuffer, conn))
1390  return EOF;
1391  /* Get the parameter value (could be large) */
1392  initPQExpBuffer(&valueBuf);
1393  if (pqGets(&valueBuf, conn))
1394  {
1395  termPQExpBuffer(&valueBuf);
1396  return EOF;
1397  }
1398  /* And save it */
1399  pqSaveParameterStatus(conn, conn->workBuffer.data, valueBuf.data);
1400  termPQExpBuffer(&valueBuf);
1401  return 0;
1402 }
void pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
Definition: fe-exec.c:1014
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:149
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
PQExpBufferData workBuffer
Definition: libpq-int.h:529
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92

◆ getReadyForQuery()

static int getReadyForQuery ( PGconn conn)
static

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

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

Referenced by pqFunctionCall3(), and pqParseInput3().

1526 {
1527  char xact_status;
1528 
1529  if (pqGetc(&xact_status, conn))
1530  return EOF;
1531  switch (xact_status)
1532  {
1533  case 'I':
1534  conn->xactStatus = PQTRANS_IDLE;
1535  break;
1536  case 'T':
1537  conn->xactStatus = PQTRANS_INTRANS;
1538  break;
1539  case 'E':
1540  conn->xactStatus = PQTRANS_INERROR;
1541  break;
1542  default:
1543  conn->xactStatus = PQTRANS_UNKNOWN;
1544  break;
1545  }
1546 
1547  return 0;
1548 }
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:80
PGTransactionStatusType xactStatus
Definition: libpq-int.h:390

◆ getRowDescriptions()

static int getRowDescriptions ( PGconn conn,
int  msgLength 
)
static

Definition at line 468 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, pgresAttDesc::typid, pgresAttDesc::typlen, and pg_conn::workBuffer.

Referenced by pqParseInput3().

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

◆ handleSyncLoss()

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

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

447 {
449  libpq_gettext("lost synchronization with server: got message type \"%c\", length %d\n"),
450  id, msgLength);
451  /* build an error result holding the error message */
452  pqSaveErrorResult(conn);
453  conn->asyncStatus = PGASYNC_READY; /* drop out of GetResult wait loop */
454  /* flush input data since we're giving up on processing it */
455  pqDropConnection(conn, true);
456  conn->status = CONNECTION_BAD; /* No more connection to backend */
457 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:458
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:389
PQExpBufferData errorMessage
Definition: libpq-int.h:526
ConnStatusType status
Definition: libpq-int.h:388
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:772
#define libpq_gettext(x)
Definition: libpq-int.h:805

◆ pqBuildErrorMessage3()

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

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

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

Referenced by pqGetErrorNotice3(), and PQresultVerboseErrorMessage().

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

◆ pqBuildStartupPacket3()

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

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

References build_startup_packet(), and malloc.

Referenced by PQconnectPoll().

2126 {
2127  char *startpacket;
2128 
2129  *packetlen = build_startup_packet(conn, NULL, options);
2130  startpacket = (char *) malloc(*packetlen);
2131  if (!startpacket)
2132  return NULL;
2133  *packetlen = build_startup_packet(conn, startpacket, options);
2134  return startpacket;
2135 }
static int build_startup_packet(const PGconn *conn, char *packet, const PQEnvironmentOption *options)
#define malloc(a)
Definition: header.h:50

◆ pqEndcopy3()

int pqEndcopy3 ( PGconn conn)

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

1830 {
1831  PGresult *result;
1832 
1833  if (conn->asyncStatus != PGASYNC_COPY_IN &&
1834  conn->asyncStatus != PGASYNC_COPY_OUT &&
1835  conn->asyncStatus != PGASYNC_COPY_BOTH)
1836  {
1838  libpq_gettext("no COPY in progress\n"));
1839  return 1;
1840  }
1841 
1842  /* Send the CopyDone message if needed */
1843  if (conn->asyncStatus == PGASYNC_COPY_IN ||
1844  conn->asyncStatus == PGASYNC_COPY_BOTH)
1845  {
1846  if (pqPutMsgStart('c', false, conn) < 0 ||
1847  pqPutMsgEnd(conn) < 0)
1848  return 1;
1849 
1850  /*
1851  * If we sent the COPY command in extended-query mode, we must issue a
1852  * Sync as well.
1853  */
1854  if (conn->queryclass != PGQUERY_SIMPLE)
1855  {
1856  if (pqPutMsgStart('S', false, conn) < 0 ||
1857  pqPutMsgEnd(conn) < 0)
1858  return 1;
1859  }
1860  }
1861 
1862  /*
1863  * make sure no data is waiting to be sent, abort if we are non-blocking
1864  * and the flush fails
1865  */
1866  if (pqFlush(conn) && pqIsnonblocking(conn))
1867  return 1;
1868 
1869  /* Return to active duty */
1870  conn->asyncStatus = PGASYNC_BUSY;
1872 
1873  /*
1874  * Non blocking connections may have to abort at this point. If everyone
1875  * played the game there should be no problem, but in error scenarios the
1876  * expected messages may not have arrived yet. (We are assuming that the
1877  * backend's packetizing will ensure that CommandComplete arrives along
1878  * with the CopyDone; are there corner cases where that doesn't happen?)
1879  */
1880  if (pqIsnonblocking(conn) && PQisBusy(conn))
1881  return 1;
1882 
1883  /* Wait for the completion response */
1884  result = PQgetResult(conn);
1885 
1886  /* Expecting a successful result */
1887  if (result && result->resultStatus == PGRES_COMMAND_OK)
1888  {
1889  PQclear(result);
1890  return 0;
1891  }
1892 
1893  /*
1894  * Trouble. For backwards-compatibility reasons, we issue the error
1895  * message as if it were a notice (would be nice to get rid of this
1896  * silliness, but too many apps probably don't handle errors from
1897  * PQendcopy reasonably). Note that the app can still obtain the error
1898  * status from the PGconn object.
1899  */
1900  if (conn->errorMessage.len > 0)
1901  {
1902  /* We have to strip the trailing newline ... pain in neck... */
1903  char svLast = conn->errorMessage.data[conn->errorMessage.len - 1];
1904 
1905  if (svLast == '\n')
1906  conn->errorMessage.data[conn->errorMessage.len - 1] = '\0';
1907  pqInternalNotice(&conn->noticeHooks, "%s", conn->errorMessage.data);
1908  conn->errorMessage.data[conn->errorMessage.len - 1] = svLast;
1909  }
1910 
1911  PQclear(result);
1912 
1913  return 1;
1914 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:1002
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
#define pqIsnonblocking(conn)
Definition: libpq-int.h:799
PGQueryClass queryclass
Definition: libpq-int.h:391
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:505
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:389
PGNoticeHooks noticeHooks
Definition: libpq-int.h:380
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:871
PQExpBufferData errorMessage
Definition: libpq-int.h:526
void PQclear(PGresult *res)
Definition: fe-exec.c:694
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:1754
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:573
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
ExecStatusType resultStatus
Definition: libpq-int.h:177
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1778
#define libpq_gettext(x)
Definition: libpq-int.h:805

◆ pqFunctionCall3()

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

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

References pg_conn::errorMessage, 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(), PQmakeEmptyPGresult(), pqPrepareAsyncResult(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), pqReadData(), pqSaveErrorResult(), pqWait(), printfPQExpBuffer(), PQArgBlock::ptr, pg_conn::result, status(), and VALID_LONG_MESSAGE_TYPE.

Referenced by PQfn().

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

◆ pqGetCopyData3()

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

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

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

Referenced by PQgetCopyData().

1663 {
1664  int msgLength;
1665 
1666  for (;;)
1667  {
1668  /*
1669  * Collect the next input message. To make life simpler for async
1670  * callers, we keep returning 0 until the next message is fully
1671  * available, even if it is not Copy Data.
1672  */
1673  msgLength = getCopyDataMessage(conn);
1674  if (msgLength < 0)
1675  return msgLength; /* end-of-copy or error */
1676  if (msgLength == 0)
1677  {
1678  /* Don't block if async read requested */
1679  if (async)
1680  return 0;
1681  /* Need to load more data */
1682  if (pqWait(true, false, conn) ||
1683  pqReadData(conn) < 0)
1684  return -2;
1685  continue;
1686  }
1687 
1688  /*
1689  * Drop zero-length messages (shouldn't happen anyway). Otherwise
1690  * pass the data back to the caller.
1691  */
1692  msgLength -= 4;
1693  if (msgLength > 0)
1694  {
1695  *buffer = (char *) malloc(msgLength + 1);
1696  if (*buffer == NULL)
1697  {
1699  libpq_gettext("out of memory\n"));
1700  return -2;
1701  }
1702  memcpy(*buffer, &conn->inBuffer[conn->inCursor], msgLength);
1703  (*buffer)[msgLength] = '\0'; /* Add terminating null */
1704 
1705  /* Mark message consumed */
1706  conn->inStart = conn->inCursor + msgLength;
1707 
1708  return msgLength;
1709  }
1710 
1711  /* Empty, so drop it and loop around for another */
1712  conn->inStart = conn->inCursor;
1713  }
1714 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
int inStart
Definition: libpq-int.h:446
#define malloc(a)
Definition: header.h:50
int pqReadData(PGconn *conn)
Definition: fe-misc.c:615
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:1025
char * inBuffer
Definition: libpq-int.h:444
static int getCopyDataMessage(PGconn *conn)
PQExpBufferData errorMessage
Definition: libpq-int.h:526
int inCursor
Definition: libpq-int.h:447
#define libpq_gettext(x)
Definition: libpq-int.h:805

◆ pqGetErrorNotice3()

int pqGetErrorNotice3 ( PGconn conn,
bool  isError 
)

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

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

◆ pqGetline3()

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

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

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

Referenced by PQgetline().

1723 {
1724  int status;
1725 
1726  if (conn->sock == PGINVALID_SOCKET ||
1727  (conn->asyncStatus != PGASYNC_COPY_OUT &&
1728  conn->asyncStatus != PGASYNC_COPY_BOTH) ||
1729  conn->copy_is_binary)
1730  {
1732  libpq_gettext("PQgetline: not doing text COPY OUT\n"));
1733  *s = '\0';
1734  return EOF;
1735  }
1736 
1737  while ((status = PQgetlineAsync(conn, s, maxlen - 1)) == 0)
1738  {
1739  /* need to load more data */
1740  if (pqWait(true, false, conn) ||
1741  pqReadData(conn) < 0)
1742  {
1743  *s = '\0';
1744  return EOF;
1745  }
1746  }
1747 
1748  if (status < 0)
1749  {
1750  /* End of copy detected; gin up old-style terminator */
1751  strcpy(s, "\\.");
1752  return 0;
1753  }
1754 
1755  /* Add null terminator, and strip trailing \n if present */
1756  if (s[status - 1] == '\n')
1757  {
1758  s[status - 1] = '\0';
1759  return 0;
1760  }
1761  else
1762  {
1763  s[status] = '\0';
1764  return 1;
1765  }
1766 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
int PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
Definition: fe-exec.c:2565
char copy_is_binary
Definition: libpq-int.h:398
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:389
int pqReadData(PGconn *conn)
Definition: fe-misc.c:615
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:1025
pgsocket sock
Definition: libpq-int.h:410
#define PGINVALID_SOCKET
Definition: port.h:33
PQExpBufferData errorMessage
Definition: libpq-int.h:526
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:805

◆ pqGetlineAsync3()

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

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

1775 {
1776  int msgLength;
1777  int avail;
1778 
1779  if (conn->asyncStatus != PGASYNC_COPY_OUT
1780  && conn->asyncStatus != PGASYNC_COPY_BOTH)
1781  return -1; /* we are not doing a copy... */
1782 
1783  /*
1784  * Recognize the next input message. To make life simpler for async
1785  * callers, we keep returning 0 until the next message is fully available
1786  * even if it is not Copy Data. This should keep PQendcopy from blocking.
1787  * (Note: unlike pqGetCopyData3, we do not change asyncStatus here.)
1788  */
1789  msgLength = getCopyDataMessage(conn);
1790  if (msgLength < 0)
1791  return -1; /* end-of-copy or error */
1792  if (msgLength == 0)
1793  return 0; /* no data yet */
1794 
1795  /*
1796  * Move data from libpq's buffer to the caller's. In the case where a
1797  * prior call found the caller's buffer too small, we use
1798  * conn->copy_already_done to remember how much of the row was already
1799  * returned to the caller.
1800  */
1801  conn->inCursor += conn->copy_already_done;
1802  avail = msgLength - 4 - conn->copy_already_done;
1803  if (avail <= bufsize)
1804  {
1805  /* Able to consume the whole message */
1806  memcpy(buffer, &conn->inBuffer[conn->inCursor], avail);
1807  /* Mark message consumed */
1808  conn->inStart = conn->inCursor + avail;
1809  /* Reset state for next time */
1810  conn->copy_already_done = 0;
1811  return avail;
1812  }
1813  else
1814  {
1815  /* We must return a partial message */
1816  memcpy(buffer, &conn->inBuffer[conn->inCursor], bufsize);
1817  /* The message is NOT consumed from libpq's buffer */
1818  conn->copy_already_done += bufsize;
1819  return bufsize;
1820  }
1821 }
int inStart
Definition: libpq-int.h:446
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:389
char * inBuffer
Definition: libpq-int.h:444
static int getCopyDataMessage(PGconn *conn)
int copy_already_done
Definition: libpq-int.h:399
int inCursor
Definition: libpq-int.h:447

◆ pqParseInput3()

void pqParseInput3 ( PGconn conn)

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

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

◆ reportErrorPosition()

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

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

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