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

Go to the source code of this file.

Macros

#define PGRESULT_DATA_BLOCKSIZE   2048
 
#define PGRESULT_ALIGN_BOUNDARY   MAXIMUM_ALIGNOF /* from configure */
 
#define PGRESULT_BLOCK_OVERHEAD   Max(sizeof(PGresult_data), PGRESULT_ALIGN_BOUNDARY)
 
#define PGRESULT_SEP_ALLOC_THRESHOLD   (PGRESULT_DATA_BLOCKSIZE / 2)
 
#define ISFIRSTOCTDIGIT(CH)   ((CH) >= '0' && (CH) <= '3')
 
#define ISOCTDIGIT(CH)   ((CH) >= '0' && (CH) <= '7')
 
#define OCTVAL(CH)   ((CH) - '0')
 

Functions

static PGEventdupEvents (PGEvent *events, int count, size_t *memSize)
 
static bool pqAddTuple (PGresult *res, PGresAttValue *tup, const char **errmsgp)
 
static int PQsendQueryInternal (PGconn *conn, const char *query, bool newQuery)
 
static bool PQsendQueryStart (PGconn *conn, bool newQuery)
 
static int PQsendQueryGuts (PGconn *conn, const char *command, const char *stmtName, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
static void parseInput (PGconn *conn)
 
static PGresultgetCopyResult (PGconn *conn, ExecStatusType copytype)
 
static bool PQexecStart (PGconn *conn)
 
static PGresultPQexecFinish (PGconn *conn)
 
static int PQsendDescribe (PGconn *conn, char desc_type, const char *desc_target)
 
static int check_field_number (const PGresult *res, int field_num)
 
static void pqPipelineProcessQueue (PGconn *conn)
 
static int pqPipelineFlush (PGconn *conn)
 
PGresultPQmakeEmptyPGresult (PGconn *conn, ExecStatusType status)
 
int PQsetResultAttrs (PGresult *res, int numAttributes, PGresAttDesc *attDescs)
 
PGresultPQcopyResult (const PGresult *src, int flags)
 
int PQsetvalue (PGresult *res, int tup_num, int field_num, char *value, int len)
 
void * PQresultAlloc (PGresult *res, size_t nBytes)
 
void * pqResultAlloc (PGresult *res, size_t nBytes, bool isBinary)
 
size_t PQresultMemorySize (const PGresult *res)
 
char * pqResultStrdup (PGresult *res, const char *str)
 
void pqSetResultError (PGresult *res, PQExpBuffer errorMessage)
 
void PQclear (PGresult *res)
 
void pqClearAsyncResult (PGconn *conn)
 
void pqSaveErrorResult (PGconn *conn)
 
static void pqSaveWriteError (PGconn *conn)
 
PGresultpqPrepareAsyncResult (PGconn *conn)
 
void pqInternalNotice (const PGNoticeHooks *hooks, const char *fmt,...)
 
void pqSaveMessageField (PGresult *res, char code, const char *value)
 
void pqSaveParameterStatus (PGconn *conn, const char *name, const char *value)
 
int pqRowProcessor (PGconn *conn, const char **errmsgp)
 
static PGcmdQueueEntrypqAllocCmdQueueEntry (PGconn *conn)
 
static void pqAppendCmdQueueEntry (PGconn *conn, PGcmdQueueEntry *entry)
 
static void pqRecycleCmdQueueEntry (PGconn *conn, PGcmdQueueEntry *entry)
 
int PQsendQuery (PGconn *conn, const char *query)
 
int PQsendQueryContinue (PGconn *conn, const char *query)
 
int PQsendQueryParams (PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
int PQsendPrepare (PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
 
int PQsendQueryPrepared (PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
int PQsetSingleRowMode (PGconn *conn)
 
int PQconsumeInput (PGconn *conn)
 
int PQisBusy (PGconn *conn)
 
PGresultPQgetResult (PGconn *conn)
 
PGresultPQexec (PGconn *conn, const char *query)
 
PGresultPQexecParams (PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
PGresultPQprepare (PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
 
PGresultPQexecPrepared (PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
PGresultPQdescribePrepared (PGconn *conn, const char *stmt)
 
PGresultPQdescribePortal (PGconn *conn, const char *portal)
 
int PQsendDescribePrepared (PGconn *conn, const char *stmt)
 
int PQsendDescribePortal (PGconn *conn, const char *portal)
 
PGnotifyPQnotifies (PGconn *conn)
 
int PQputCopyData (PGconn *conn, const char *buffer, int nbytes)
 
int PQputCopyEnd (PGconn *conn, const char *errormsg)
 
int PQgetCopyData (PGconn *conn, char **buffer, int async)
 
int PQgetline (PGconn *conn, char *s, int maxlen)
 
int PQgetlineAsync (PGconn *conn, char *buffer, int bufsize)
 
int PQputline (PGconn *conn, const char *s)
 
int PQputnbytes (PGconn *conn, const char *buffer, int nbytes)
 
int PQendcopy (PGconn *conn)
 
PGresultPQfn (PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
 
int PQenterPipelineMode (PGconn *conn)
 
int PQexitPipelineMode (PGconn *conn)
 
void pqCommandQueueAdvance (PGconn *conn)
 
int PQpipelineSync (PGconn *conn)
 
int PQsendFlushRequest (PGconn *conn)
 
ExecStatusType PQresultStatus (const PGresult *res)
 
char * PQresStatus (ExecStatusType status)
 
char * PQresultErrorMessage (const PGresult *res)
 
char * PQresultVerboseErrorMessage (const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
 
char * PQresultErrorField (const PGresult *res, int fieldcode)
 
int PQntuples (const PGresult *res)
 
int PQnfields (const PGresult *res)
 
int PQbinaryTuples (const PGresult *res)
 
static int check_tuple_field_number (const PGresult *res, int tup_num, int field_num)
 
static int check_param_number (const PGresult *res, int param_num)
 
char * PQfname (const PGresult *res, int field_num)
 
int PQfnumber (const PGresult *res, const char *field_name)
 
Oid PQftable (const PGresult *res, int field_num)
 
int PQftablecol (const PGresult *res, int field_num)
 
int PQfformat (const PGresult *res, int field_num)
 
Oid PQftype (const PGresult *res, int field_num)
 
int PQfsize (const PGresult *res, int field_num)
 
int PQfmod (const PGresult *res, int field_num)
 
char * PQcmdStatus (PGresult *res)
 
char * PQoidStatus (const PGresult *res)
 
Oid PQoidValue (const PGresult *res)
 
char * PQcmdTuples (PGresult *res)
 
char * PQgetvalue (const PGresult *res, int tup_num, int field_num)
 
int PQgetlength (const PGresult *res, int tup_num, int field_num)
 
int PQgetisnull (const PGresult *res, int tup_num, int field_num)
 
int PQnparams (const PGresult *res)
 
Oid PQparamtype (const PGresult *res, int param_num)
 
int PQsetnonblocking (PGconn *conn, int arg)
 
int PQisnonblocking (const PGconn *conn)
 
int PQisthreadsafe (void)
 
int PQflush (PGconn *conn)
 
void PQfreemem (void *ptr)
 
void PQfreeNotify (PGnotify *notify)
 
static size_t PQescapeStringInternal (PGconn *conn, char *to, const char *from, size_t length, int *error, int encoding, bool std_strings)
 
size_t PQescapeStringConn (PGconn *conn, char *to, const char *from, size_t length, int *error)
 
size_t PQescapeString (char *to, const char *from, size_t length)
 
static char * PQescapeInternal (PGconn *conn, const char *str, size_t len, bool as_ident)
 
char * PQescapeLiteral (PGconn *conn, const char *str, size_t len)
 
char * PQescapeIdentifier (PGconn *conn, const char *str, size_t len)
 
static char get_hex (char c)
 
static unsigned char * PQescapeByteaInternal (PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length, bool std_strings, bool use_hex)
 
unsigned char * PQescapeByteaConn (PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length)
 
unsigned char * PQescapeBytea (const unsigned char *from, size_t from_length, size_t *to_length)
 
unsigned char * PQunescapeBytea (const unsigned char *strtext, size_t *retbuflen)
 

Variables

char *const pgresStatus []
 
static int static_client_encoding = PG_SQL_ASCII
 
static bool static_std_strings = false
 
static const char hextbl [] = "0123456789abcdef"
 
static const int8 hexlookup [128]
 

Macro Definition Documentation

◆ ISFIRSTOCTDIGIT

#define ISFIRSTOCTDIGIT (   CH)    ((CH) >= '0' && (CH) <= '3')

Definition at line 4242 of file fe-exec.c.

Referenced by PQunescapeBytea().

◆ ISOCTDIGIT

#define ISOCTDIGIT (   CH)    ((CH) >= '0' && (CH) <= '7')

Definition at line 4243 of file fe-exec.c.

Referenced by PQunescapeBytea().

◆ OCTVAL

#define OCTVAL (   CH)    ((CH) - '0')

Definition at line 4244 of file fe-exec.c.

Referenced by PQunescapeBytea().

◆ PGRESULT_ALIGN_BOUNDARY

#define PGRESULT_ALIGN_BOUNDARY   MAXIMUM_ALIGNOF /* from configure */

Definition at line 134 of file fe-exec.c.

Referenced by pqResultAlloc().

◆ PGRESULT_BLOCK_OVERHEAD

#define PGRESULT_BLOCK_OVERHEAD   Max(sizeof(PGresult_data), PGRESULT_ALIGN_BOUNDARY)

Definition at line 135 of file fe-exec.c.

Referenced by pqResultAlloc().

◆ PGRESULT_DATA_BLOCKSIZE

#define PGRESULT_DATA_BLOCKSIZE   2048

Definition at line 133 of file fe-exec.c.

Referenced by pqResultAlloc().

◆ PGRESULT_SEP_ALLOC_THRESHOLD

#define PGRESULT_SEP_ALLOC_THRESHOLD   (PGRESULT_DATA_BLOCKSIZE / 2)

Definition at line 136 of file fe-exec.c.

Referenced by pqResultAlloc().

Function Documentation

◆ check_field_number()

static int check_field_number ( const PGresult res,
int  field_num 
)
static

Definition at line 3277 of file fe-exec.c.

References pg_result::noticeHooks, pg_result::numAttributes, and pqInternalNotice().

Referenced by PQfformat(), PQfmod(), PQfname(), PQfsize(), PQftable(), PQftablecol(), PQftype(), and PQsetvalue().

3278 {
3279  if (!res)
3280  return false; /* no way to display error message... */
3281  if (field_num < 0 || field_num >= res->numAttributes)
3282  {
3284  "column number %d is out of range 0..%d",
3285  field_num, res->numAttributes - 1);
3286  return false;
3287  }
3288  return true;
3289 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:187
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:839
int numAttributes
Definition: libpq-int.h:171

◆ check_param_number()

static int check_param_number ( const PGresult res,
int  param_num 
)
static

Definition at line 3315 of file fe-exec.c.

References pg_result::noticeHooks, pg_result::numParameters, and pqInternalNotice().

Referenced by PQparamtype().

3316 {
3317  if (!res)
3318  return false; /* no way to display error message... */
3319  if (param_num < 0 || param_num >= res->numParameters)
3320  {
3322  "parameter number %d is out of range 0..%d",
3323  param_num, res->numParameters - 1);
3324  return false;
3325  }
3326 
3327  return true;
3328 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:187
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:839
int numParameters
Definition: libpq-int.h:176

◆ check_tuple_field_number()

static int check_tuple_field_number ( const PGresult res,
int  tup_num,
int  field_num 
)
static

Definition at line 3292 of file fe-exec.c.

References pg_result::noticeHooks, pg_result::ntups, pg_result::numAttributes, and pqInternalNotice().

Referenced by PQgetisnull(), PQgetlength(), and PQgetvalue().

3294 {
3295  if (!res)
3296  return false; /* no way to display error message... */
3297  if (tup_num < 0 || tup_num >= res->ntups)
3298  {
3300  "row number %d is out of range 0..%d",
3301  tup_num, res->ntups - 1);
3302  return false;
3303  }
3304  if (field_num < 0 || field_num >= res->numAttributes)
3305  {
3307  "column number %d is out of range 0..%d",
3308  field_num, res->numAttributes - 1);
3309  return false;
3310  }
3311  return true;
3312 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:187
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:839
int numAttributes
Definition: libpq-int.h:171
int ntups
Definition: libpq-int.h:170

◆ dupEvents()

static PGEvent * dupEvents ( PGEvent events,
int  count,
size_t *  memSize 
)
static

Definition at line 392 of file fe-exec.c.

References free, i, malloc, name, PGEvent::passThrough, and PGEvent::proc.

Referenced by PQcopyResult(), and PQmakeEmptyPGresult().

393 {
394  PGEvent *newEvents;
395  size_t msize;
396  int i;
397 
398  if (!events || count <= 0)
399  return NULL;
400 
401  msize = count * sizeof(PGEvent);
402  newEvents = (PGEvent *) malloc(msize);
403  if (!newEvents)
404  return NULL;
405 
406  for (i = 0; i < count; i++)
407  {
408  newEvents[i].proc = events[i].proc;
409  newEvents[i].passThrough = events[i].passThrough;
410  newEvents[i].data = NULL;
411  newEvents[i].resultInitialized = false;
412  newEvents[i].name = strdup(events[i].name);
413  if (!newEvents[i].name)
414  {
415  while (--i >= 0)
416  free(newEvents[i].name);
417  free(newEvents);
418  return NULL;
419  }
420  msize += strlen(events[i].name) + 1;
421  }
422 
423  *memSize += msize;
424  return newEvents;
425 }
struct PGEvent PGEvent
#define malloc(a)
Definition: header.h:50
#define free(a)
Definition: header.h:65
PGEventProc proc
Definition: libpq-int.h:161
const char * name
Definition: encode.c:561
int i
void * passThrough
Definition: libpq-int.h:163

◆ get_hex()

static char get_hex ( char  c)
inlinestatic

Definition at line 4095 of file fe-exec.c.

References hexlookup.

Referenced by PQunescapeBytea().

4096 {
4097  int res = -1;
4098 
4099  if (c > 0 && c < 127)
4100  res = hexlookup[(unsigned char) c];
4101 
4102  return (char) res;
4103 }
static const int8 hexlookup[128]
Definition: fe-exec.c:4083
char * c

◆ getCopyResult()

static PGresult * getCopyResult ( PGconn conn,
ExecStatusType  copytype 
)
static

Definition at line 2155 of file fe-exec.c.

References pg_conn::asyncStatus, CONNECTION_OK, PGASYNC_IDLE, PQmakeEmptyPGresult(), pqPrepareAsyncResult(), pqSaveErrorResult(), pg_conn::result, pg_result::resultStatus, and pg_conn::status.

Referenced by PQgetResult().

2156 {
2157  /*
2158  * If the server connection has been lost, don't pretend everything is
2159  * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
2160  * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
2161  * error in the earlier steps in PQgetResult). The text returned in the
2162  * result is whatever is in conn->errorMessage; we hope that was filled
2163  * with something relevant when the lost connection was detected.
2164  */
2165  if (conn->status != CONNECTION_OK)
2166  {
2167  pqSaveErrorResult(conn);
2168  conn->asyncStatus = PGASYNC_IDLE;
2169  return pqPrepareAsyncResult(conn);
2170  }
2171 
2172  /* If we have an async result for the COPY, return that */
2173  if (conn->result && conn->result->resultStatus == copytype)
2174  return pqPrepareAsyncResult(conn);
2175 
2176  /* Otherwise, invent a suitable PGresult */
2177  return PQmakeEmptyPGresult(conn, copytype);
2178 }
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:804
PGresult * result
Definition: libpq-int.h:500
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:146
ConnStatusType status
Definition: libpq-int.h:410
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:765
ExecStatusType resultStatus
Definition: libpq-int.h:178

◆ parseInput()

static void parseInput ( PGconn conn)
static

Definition at line 1940 of file fe-exec.c.

References pqParseInput3().

Referenced by PQgetResult(), PQisBusy(), PQnotifies(), and PQputCopyData().

1941 {
1942  pqParseInput3(conn);
1943 }
void pqParseInput3(PGconn *conn)
Definition: fe-protocol3.c:63

◆ pqAddTuple()

static bool pqAddTuple ( PGresult res,
PGresAttValue tup,
const char **  errmsgp 
)
static

Definition at line 894 of file fe-exec.c.

References libpq_gettext, malloc, pg_result::memorySize, pg_result::ntups, realloc, pg_result::tupArrSize, and pg_result::tuples.

Referenced by pqRowProcessor(), and PQsetvalue().

895 {
896  if (res->ntups >= res->tupArrSize)
897  {
898  /*
899  * Try to grow the array.
900  *
901  * We can use realloc because shallow copying of the structure is
902  * okay. Note that the first time through, res->tuples is NULL. While
903  * ANSI says that realloc() should act like malloc() in that case,
904  * some old C libraries (like SunOS 4.1.x) coredump instead. On
905  * failure realloc is supposed to return NULL without damaging the
906  * existing allocation. Note that the positions beyond res->ntups are
907  * garbage, not necessarily NULL.
908  */
909  int newSize;
910  PGresAttValue **newTuples;
911 
912  /*
913  * Since we use integers for row numbers, we can't support more than
914  * INT_MAX rows. Make sure we allow that many, though.
915  */
916  if (res->tupArrSize <= INT_MAX / 2)
917  newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
918  else if (res->tupArrSize < INT_MAX)
919  newSize = INT_MAX;
920  else
921  {
922  *errmsgp = libpq_gettext("PGresult cannot support more than INT_MAX tuples");
923  return false;
924  }
925 
926  /*
927  * Also, on 32-bit platforms we could, in theory, overflow size_t even
928  * before newSize gets to INT_MAX. (In practice we'd doubtless hit
929  * OOM long before that, but let's check.)
930  */
931 #if INT_MAX >= (SIZE_MAX / 2)
932  if (newSize > SIZE_MAX / sizeof(PGresAttValue *))
933  {
934  *errmsgp = libpq_gettext("size_t overflow");
935  return false;
936  }
937 #endif
938 
939  if (res->tuples == NULL)
940  newTuples = (PGresAttValue **)
941  malloc(newSize * sizeof(PGresAttValue *));
942  else
943  newTuples = (PGresAttValue **)
944  realloc(res->tuples, newSize * sizeof(PGresAttValue *));
945  if (!newTuples)
946  return false; /* malloc or realloc failed */
947  res->memorySize +=
948  (newSize - res->tupArrSize) * sizeof(PGresAttValue *);
949  res->tupArrSize = newSize;
950  res->tuples = newTuples;
951  }
952  res->tuples[res->ntups] = tup;
953  res->ntups++;
954  return true;
955 }
size_t memorySize
Definition: libpq-int.h:213
int tupArrSize
Definition: libpq-int.h:175
PGresAttValue ** tuples
Definition: libpq-int.h:173
#define malloc(a)
Definition: header.h:50
int ntups
Definition: libpq-int.h:170
#define realloc(a, b)
Definition: header.h:60
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ pqAllocCmdQueueEntry()

static PGcmdQueueEntry* pqAllocCmdQueueEntry ( PGconn conn)
static

Definition at line 1213 of file fe-exec.c.

References appendPQExpBufferStr(), pg_conn::cmd_queue_recycle, pg_conn::errorMessage, libpq_gettext, malloc, PGcmdQueueEntry::next, and PGcmdQueueEntry::query.

Referenced by PQpipelineSync(), PQsendDescribe(), PQsendPrepare(), PQsendQueryGuts(), and PQsendQueryInternal().

1214 {
1215  PGcmdQueueEntry *entry;
1216 
1217  if (conn->cmd_queue_recycle == NULL)
1218  {
1219  entry = (PGcmdQueueEntry *) malloc(sizeof(PGcmdQueueEntry));
1220  if (entry == NULL)
1221  {
1223  libpq_gettext("out of memory\n"));
1224  return NULL;
1225  }
1226  }
1227  else
1228  {
1229  entry = conn->cmd_queue_recycle;
1230  conn->cmd_queue_recycle = entry->next;
1231  }
1232  entry->next = NULL;
1233  entry->query = NULL;
1234 
1235  return entry;
1236 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
struct PGcmdQueueEntry * next
Definition: libpq-int.h:324
#define malloc(a)
Definition: header.h:50
PQExpBufferData errorMessage
Definition: libpq-int.h:571
PGcmdQueueEntry * cmd_queue_recycle
Definition: libpq-int.h:441
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ pqAppendCmdQueueEntry()

static void pqAppendCmdQueueEntry ( PGconn conn,
PGcmdQueueEntry entry 
)
static

Definition at line 1247 of file fe-exec.c.

References Assert, pg_conn::asyncStatus, pg_conn::cmd_queue_head, pg_conn::cmd_queue_tail, pg_conn::errorMessage, PGcmdQueueEntry::next, PGASYNC_BUSY, PGASYNC_IDLE, pg_conn::pipelineStatus, PQ_PIPELINE_ABORTED, PQ_PIPELINE_OFF, PQ_PIPELINE_ON, pqPipelineProcessQueue(), and resetPQExpBuffer().

Referenced by PQpipelineSync(), PQsendDescribe(), PQsendPrepare(), PQsendQueryGuts(), and PQsendQueryInternal().

1248 {
1249  Assert(entry->next == NULL);
1250 
1251  if (conn->cmd_queue_head == NULL)
1252  conn->cmd_queue_head = entry;
1253  else
1254  conn->cmd_queue_tail->next = entry;
1255 
1256  conn->cmd_queue_tail = entry;
1257 
1258  switch (conn->pipelineStatus)
1259  {
1260  case PQ_PIPELINE_OFF:
1261  case PQ_PIPELINE_ON:
1262 
1263  /*
1264  * When not in pipeline aborted state, if there's a result ready
1265  * to be consumed, let it be so (that is, don't change away from
1266  * READY or READY_MORE); otherwise set us busy to wait for
1267  * something to arrive from the server.
1268  */
1269  if (conn->asyncStatus == PGASYNC_IDLE)
1270  conn->asyncStatus = PGASYNC_BUSY;
1271  break;
1272 
1273  case PQ_PIPELINE_ABORTED:
1274 
1275  /*
1276  * In aborted pipeline state, we don't expect anything from the
1277  * server (since we don't send any queries that are queued).
1278  * Therefore, if IDLE then do what PQgetResult would do to let
1279  * itself consume commands from the queue; if we're in any other
1280  * state, we don't have to do anything.
1281  */
1282  if (conn->asyncStatus == PGASYNC_IDLE)
1283  {
1285  pqPipelineProcessQueue(conn);
1286  }
1287  break;
1288  }
1289 }
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:434
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:417
struct PGcmdQueueEntry * next
Definition: libpq-int.h:324
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
static void pqPipelineProcessQueue(PGconn *conn)
Definition: fe-exec.c:2997
PGcmdQueueEntry * cmd_queue_tail
Definition: libpq-int.h:435
PQExpBufferData errorMessage
Definition: libpq-int.h:571
#define Assert(condition)
Definition: c.h:804
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148

◆ PQbinaryTuples()

int PQbinaryTuples ( const PGresult res)

Definition at line 3264 of file fe-exec.c.

References pg_result::binary.

Referenced by ProcessResult().

3265 {
3266  if (!res)
3267  return 0;
3268  return res->binary;
3269 }
int binary
Definition: libpq-int.h:180

◆ PQclear()

void PQclear ( PGresult res)

Definition at line 694 of file fe-exec.c.

References pg_result::attDescs, pg_result::curBlock, pg_result::errFields, pg_result::events, free, i, PGEvent::name, pg_result::nEvents, pgresult_data::next, pg_result::paramDescs, PGEvent::passThrough, PGEVT_RESULTDESTROY, PGEvent::proc, PGEventResultDestroy::result, PGEvent::resultInitialized, and pg_result::tuples.

Referenced by _check_database_version(), _doSetSessionAuth(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), add_tablespace_footer(), append_depends_on_extension(), appendQualifiedRelation(), BaseBackup(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_rel_oid(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), buildShSecLabels(), check_for_data_types_usage(), check_for_isn_and_int8_passing_mismatch(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_for_tables_with_oids(), check_for_user_defined_encoding_conversions(), check_for_user_defined_postfix_ops(), check_is_install_user(), check_loadable_libraries(), check_prepare_conn(), check_proper_datallowconn(), ClearOrSaveResult(), close_cursor(), cluster_all_databases(), compile_database_list(), compile_relation_list_one_db(), connectDatabase(), ConnectDatabase(), connectToServer(), convertTSFunction(), create_cursor(), CreateReplicationSlot(), createViewAsClause(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_res_error(), deallocate_one(), deallocate_query(), describeAccessMethods(), describeAggregates(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describePublications(), DescribeQuery(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), descriptor_free(), do_lo_import(), do_lo_list(), do_sql_command(), dropDBs(), DropReplicationSlot(), dropRoles(), dropTablespaces(), dumpAgg(), dumpBaseType(), dumpBlobs(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpDomain(), dumpEnumType(), dumpFunc(), dumpGroups(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSearchPath(), dumpSequence(), dumpSequenceData(), dumpStatisticsExt(), dumpTable(), dumpTableData_copy(), dumpTableData_insert(), dumpTableSchema(), dumpTablespaces(), dumpTSConfig(), dumpTSDictionary(), dumpUserConfig(), dumpUserMappings(), ecpg_autostart_transaction(), ecpg_check_PQresult(), ecpg_is_type_an_array(), ecpg_process_output(), ECPGdescribe(), ECPGsetcommit(), ECPGtrans(), EndDBCopyMode(), exec_command_password(), ExecQueryUsingCursor(), execute_foreign_modify(), executeCommand(), executeMaintenanceCommand(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlStatement(), executeStatement(), expand_dbname_patterns(), expand_extension_name_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), fail_lo_xact(), fetch_more_data(), findLastBuiltinOid_V71(), finish_lo_xact(), get_create_object_cmd(), get_db_infos(), get_language_name(), get_loadable_libraries(), get_next_possible_free_pg_type_oid(), get_parallel_object_list(), get_rel_infos(), get_remote_estimate(), get_returning_data(), get_synchronized_snapshot(), get_tablespace_paths(), getAccessMethods(), getAggregates(), getBlobs(), getCasts(), getCollations(), GetConnection(), getConstraints(), getConversions(), getCopyStart(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getParamDescriptions(), getPolicies(), getProcLangs(), getPublications(), getPublicationTables(), getRowDescriptions(), getRules(), getSubscriptions(), getTableAttrs(), GetTableInfo(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), handleCopyIn(), HandleEndOfCopyStream(), init_libpq_conn(), initGenerateDataClientSide(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_connect(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_exec(), libpqrcv_identify_system(), libpqrcv_PQexec(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_startstreaming(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtendedStats(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listOneExtensionContents(), listOperatorClasses(), listOperatorFamilies(), listOpFamilyFunctions(), listOpFamilyOperators(), listPartitionedTables(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), lo_close(), lo_creat(), lo_create(), lo_initialize(), lo_lseek(), lo_lseek64(), lo_open(), lo_read(), lo_tell(), lo_tell64(), lo_truncate(), lo_truncate64(), lo_unlink(), lo_write(), lockTableForWorker(), lookup_object_oid(), main(), materializeResult(), new_9_0_populate_pg_largeobject_metadata(), objectDescription(), old_9_6_invalidate_hash_indexes(), permissionsList(), pg_attribute_noreturn(), pgfdw_cancel_query(), pgfdw_exec_cleanup_query(), pgfdw_get_cleanup_result(), pgfdw_get_result(), pgfdw_report_error(), pgfdw_xact_callback(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresEndDirectModify(), postgresImportForeignSchema(), postgresReScanForeignScan(), pqClearAsyncResult(), PQconnectPoll(), PQcopyResult(), PQencryptPasswordConn(), pqEndcopy3(), PQexecFinish(), PQexecStart(), pqGetErrorNotice3(), pqInternalNotice(), PQmakeEmptyPGresult(), pqRowProcessor(), PQsetClientEncoding(), prepare_common(), prepare_foreign_modify(), process_queued_fetch_requests(), process_result(), processExtensionTables(), processQueryResult(), ProcessResult(), PSQLexecWatch(), readCommandResponse(), ReceiveCopyData(), ReceiveXlogStream(), reindex_all_databases(), report_extension_updates(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_permutation(), run_simple_command(), run_simple_query(), RunIdentifySystem(), sendCommand(), SendQuery(), set_frozenxids(), setup_connection(), sql_conn(), sql_exec(), start_lo_xact(), store_returning_result(), storeQueryResult(), StreamLogicalLog(), TableCommandResultHandler(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), try_complete_step(), tryExecuteStatement(), vacuum_all_databases(), vacuum_one_database(), and vacuumlo().

695 {
696  PGresult_data *block;
697  int i;
698 
699  if (!res)
700  return;
701 
702  for (i = 0; i < res->nEvents; i++)
703  {
704  /* only send DESTROY to successfully-initialized event procs */
705  if (res->events[i].resultInitialized)
706  {
708 
709  evt.result = res;
710  (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
711  res->events[i].passThrough);
712  }
713  free(res->events[i].name);
714  }
715 
716  if (res->events)
717  free(res->events);
718 
719  /* Free all the subsidiary blocks */
720  while ((block = res->curBlock) != NULL)
721  {
722  res->curBlock = block->next;
723  free(block);
724  }
725 
726  /* Free the top-level tuple pointer array */
727  if (res->tuples)
728  free(res->tuples);
729 
730  /* zero out the pointer fields to catch programming errors */
731  res->attDescs = NULL;
732  res->tuples = NULL;
733  res->paramDescs = NULL;
734  res->errFields = NULL;
735  res->events = NULL;
736  res->nEvents = 0;
737  /* res->curBlock was zeroed out earlier */
738 
739  /* Free the PGresult structure itself */
740  free(res);
741 }
PGMessageField * errFields
Definition: libpq-int.h:198
bool resultInitialized
Definition: libpq-int.h:165
PGresult_data * next
Definition: libpq-int.h:106
int nEvents
Definition: libpq-int.h:189
PGresAttDesc * attDescs
Definition: libpq-int.h:172
PGresAttValue ** tuples
Definition: libpq-int.h:173
PGresult_data * curBlock
Definition: libpq-int.h:209
#define free(a)
Definition: header.h:65
PGresParamDesc * paramDescs
Definition: libpq-int.h:177
PGEventProc proc
Definition: libpq-int.h:161
int i
void * passThrough
Definition: libpq-int.h:163
PGEvent * events
Definition: libpq-int.h:188
char * name
Definition: libpq-int.h:162

◆ pqClearAsyncResult()

void pqClearAsyncResult ( PGconn conn)

Definition at line 749 of file fe-exec.c.

References pg_conn::next_result, PQclear(), and pg_conn::result.

Referenced by closePGconn(), getAnotherTuple(), getParamDescriptions(), getRowDescriptions(), PQconnectPoll(), pqGetErrorNotice3(), pqPipelineProcessQueue(), pqSaveErrorResult(), and PQsendQueryStart().

750 {
751  if (conn->result)
752  PQclear(conn->result);
753  conn->result = NULL;
754  if (conn->next_result)
755  PQclear(conn->next_result);
756  conn->next_result = NULL;
757 }
PGresult * result
Definition: libpq-int.h:500
PGresult * next_result
Definition: libpq-int.h:501
void PQclear(PGresult *res)
Definition: fe-exec.c:694

◆ PQcmdStatus()

char* PQcmdStatus ( PGresult res)

Definition at line 3519 of file fe-exec.c.

References pg_result::cmdStatus.

Referenced by dblink_exec(), ecpg_process_output(), materializeResult(), PrintQueryResults(), PrintQueryStatus(), PSQLexecWatch(), SendQuery(), and test_pipelined_insert().

3520 {
3521  if (!res)
3522  return NULL;
3523  return res->cmdStatus;
3524 }
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:179

◆ PQcmdTuples()

char* PQcmdTuples ( PGresult res)

Definition at line 3589 of file fe-exec.c.

References pg_result::cmdStatus, pg_result::noticeHooks, and pqInternalNotice().

Referenced by ecpg_process_output(), execute_dml_stmt(), execute_foreign_modify(), and SetResultVariables().

3590 {
3591  char *p,
3592  *c;
3593 
3594  if (!res)
3595  return "";
3596 
3597  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3598  {
3599  p = res->cmdStatus + 7;
3600  /* INSERT: skip oid and space */
3601  while (*p && *p != ' ')
3602  p++;
3603  if (*p == 0)
3604  goto interpret_error; /* no space? */
3605  p++;
3606  }
3607  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3608  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3609  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3610  p = res->cmdStatus + 7;
3611  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
3612  p = res->cmdStatus + 6;
3613  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3614  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3615  p = res->cmdStatus + 5;
3616  else
3617  return "";
3618 
3619  /* check that we have an integer (at least one digit, nothing else) */
3620  for (c = p; *c; c++)
3621  {
3622  if (!isdigit((unsigned char) *c))
3623  goto interpret_error;
3624  }
3625  if (c == p)
3626  goto interpret_error;
3627 
3628  return p;
3629 
3630 interpret_error:
3632  "could not interpret result from server: %s",
3633  res->cmdStatus);
3634  return "";
3635 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:187
char * c
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:839
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:179

◆ pqCommandQueueAdvance()

void pqCommandQueueAdvance ( PGconn conn)

Definition at line 2976 of file fe-exec.c.

References pg_conn::cmd_queue_head, PGcmdQueueEntry::next, and pqRecycleCmdQueueEntry().

Referenced by PQgetResult(), and pqParseInput3().

2977 {
2978  PGcmdQueueEntry *prevquery;
2979 
2980  if (conn->cmd_queue_head == NULL)
2981  return;
2982 
2983  /* delink from queue */
2984  prevquery = conn->cmd_queue_head;
2985  conn->cmd_queue_head = conn->cmd_queue_head->next;
2986 
2987  /* and make it recyclable */
2988  prevquery->next = NULL;
2989  pqRecycleCmdQueueEntry(conn, prevquery);
2990 }
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:434
struct PGcmdQueueEntry * next
Definition: libpq-int.h:324
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1296

◆ PQconsumeInput()

int PQconsumeInput ( PGconn conn)

Definition at line 1904 of file fe-exec.c.

References pqFlush(), pqIsnonblocking, and pqReadData().

Referenced by advanceConnectionState(), CopyStreamReceive(), dblink_get_notify(), dblink_is_busy(), ecpg_process_output(), libpqrcv_PQgetResult(), libpqrcv_receive(), main(), pgfdw_get_cleanup_result(), pgfdw_get_result(), postgresForeignAsyncNotify(), PQconnectPoll(), PrintNotifications(), StreamLogicalLog(), test_nosync(), test_pipelined_insert(), test_uniqviol(), try_complete_step(), and wait_on_slots().

1905 {
1906  if (!conn)
1907  return 0;
1908 
1909  /*
1910  * for non-blocking connections try to flush the send-queue, otherwise we
1911  * may never get a response for something that may not have already been
1912  * sent because it's in our write buffer!
1913  */
1914  if (pqIsnonblocking(conn))
1915  {
1916  if (pqFlush(conn) < 0)
1917  return 0;
1918  }
1919 
1920  /*
1921  * Load more data, if available. We do this no matter what state we are
1922  * in, since we are probably getting called because the application wants
1923  * to get rid of a read-select condition. Note that we will NOT block
1924  * waiting for more input.
1925  */
1926  if (pqReadData(conn) < 0)
1927  return 0;
1928 
1929  /* Parsing of the data waits till later. */
1930  return 1;
1931 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:965
#define pqIsnonblocking(conn)
Definition: libpq-int.h:830
int pqReadData(PGconn *conn)
Definition: fe-misc.c:568

◆ PQcopyResult()

PGresult* PQcopyResult ( const PGresult src,
int  flags 
)

Definition at line 299 of file fe-exec.c.

References pg_result::attDescs, pg_result::client_encoding, pg_result::cmdStatus, PGEventResultCopy::dest, generate_unaccent_rules::dest, dupEvents(), pg_result::events, i, pgresAttValue::len, pg_result::memorySize, pg_result::nEvents, pg_result::noticeHooks, pg_result::ntups, pg_result::numAttributes, PGEvent::passThrough, PG_COPYRES_ATTRS, PG_COPYRES_EVENTS, PG_COPYRES_NOTICEHOOKS, PG_COPYRES_TUPLES, PGEVT_RESULTCOPY, PGRES_TUPLES_OK, PQclear(), PQmakeEmptyPGresult(), PQsetResultAttrs(), PQsetvalue(), PGEvent::proc, PGEvent::resultInitialized, PGEventResultCopy::src, pg_result::tuples, and pgresAttValue::value.

Referenced by pqRowProcessor().

300 {
301  PGresult *dest;
302  int i;
303 
304  if (!src)
305  return NULL;
306 
307  dest = PQmakeEmptyPGresult(NULL, PGRES_TUPLES_OK);
308  if (!dest)
309  return NULL;
310 
311  /* Always copy these over. Is cmdStatus really useful here? */
312  dest->client_encoding = src->client_encoding;
313  strcpy(dest->cmdStatus, src->cmdStatus);
314 
315  /* Wants attrs? */
316  if (flags & (PG_COPYRES_ATTRS | PG_COPYRES_TUPLES))
317  {
318  if (!PQsetResultAttrs(dest, src->numAttributes, src->attDescs))
319  {
320  PQclear(dest);
321  return NULL;
322  }
323  }
324 
325  /* Wants to copy tuples? */
326  if (flags & PG_COPYRES_TUPLES)
327  {
328  int tup,
329  field;
330 
331  for (tup = 0; tup < src->ntups; tup++)
332  {
333  for (field = 0; field < src->numAttributes; field++)
334  {
335  if (!PQsetvalue(dest, tup, field,
336  src->tuples[tup][field].value,
337  src->tuples[tup][field].len))
338  {
339  PQclear(dest);
340  return NULL;
341  }
342  }
343  }
344  }
345 
346  /* Wants to copy notice hooks? */
347  if (flags & PG_COPYRES_NOTICEHOOKS)
348  dest->noticeHooks = src->noticeHooks;
349 
350  /* Wants to copy PGEvents? */
351  if ((flags & PG_COPYRES_EVENTS) && src->nEvents > 0)
352  {
353  dest->events = dupEvents(src->events, src->nEvents,
354  &dest->memorySize);
355  if (!dest->events)
356  {
357  PQclear(dest);
358  return NULL;
359  }
360  dest->nEvents = src->nEvents;
361  }
362 
363  /* Okay, trigger PGEVT_RESULTCOPY event */
364  for (i = 0; i < dest->nEvents; i++)
365  {
366  if (src->events[i].resultInitialized)
367  {
368  PGEventResultCopy evt;
369 
370  evt.src = src;
371  evt.dest = dest;
372  if (!dest->events[i].proc(PGEVT_RESULTCOPY, &evt,
373  dest->events[i].passThrough))
374  {
375  PQclear(dest);
376  return NULL;
377  }
378  dest->events[i].resultInitialized = true;
379  }
380  }
381 
382  return dest;
383 }
size_t memorySize
Definition: libpq-int.h:213
const PGresult * src
Definition: libpq-events.h:60
bool resultInitialized
Definition: libpq-int.h:165
int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len)
Definition: fe-exec.c:436
int nEvents
Definition: libpq-int.h:189
PGresAttDesc * attDescs
Definition: libpq-int.h:172
#define PG_COPYRES_TUPLES
Definition: libpq-fe.h:44
PGresAttValue ** tuples
Definition: libpq-int.h:173
#define PG_COPYRES_EVENTS
Definition: libpq-fe.h:45
PGNoticeHooks noticeHooks
Definition: libpq-int.h:187
#define PG_COPYRES_NOTICEHOOKS
Definition: libpq-fe.h:46
int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs)
Definition: fe-exec.c:234
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:146
int numAttributes
Definition: libpq-int.h:171
#define PG_COPYRES_ATTRS
Definition: libpq-fe.h:43
void PQclear(PGresult *res)
Definition: fe-exec.c:694
int ntups
Definition: libpq-int.h:170
PGEventProc proc
Definition: libpq-int.h:161
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:179
int i
void * passThrough
Definition: libpq-int.h:163
char * value
Definition: libpq-int.h:139
static PGEvent * dupEvents(PGEvent *events, int count, size_t *memSize)
Definition: fe-exec.c:392
PGEvent * events
Definition: libpq-int.h:188
PGresult * dest
Definition: libpq-events.h:61
int client_encoding
Definition: libpq-int.h:190

◆ PQdescribePortal()

PGresult* PQdescribePortal ( PGconn conn,
const char *  portal 
)

Definition at line 2405 of file fe-exec.c.

References PQexecFinish(), PQexecStart(), and PQsendDescribe().

2406 {
2407  if (!PQexecStart(conn))
2408  return NULL;
2409  if (!PQsendDescribe(conn, 'P', portal))
2410  return NULL;
2411  return PQexecFinish(conn);
2412 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2450
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2340
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2275

◆ PQdescribePrepared()

PGresult* PQdescribePrepared ( PGconn conn,
const char *  stmt 
)

Definition at line 2386 of file fe-exec.c.

References PQexecFinish(), PQexecStart(), and PQsendDescribe().

Referenced by DescribeQuery(), and ECPGdescribe().

2387 {
2388  if (!PQexecStart(conn))
2389  return NULL;
2390  if (!PQsendDescribe(conn, 'S', stmt))
2391  return NULL;
2392  return PQexecFinish(conn);
2393 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2450
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2340
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2275

◆ PQendcopy()

int PQendcopy ( PGconn conn)

Definition at line 2802 of file fe-exec.c.

References pqEndcopy3().

Referenced by ecpg_check_PQresult(), initGenerateDataClientSide(), and libpqrcv_endstreaming().

2803 {
2804  if (!conn)
2805  return 0;
2806 
2807  return pqEndcopy3(conn);
2808 }
int pqEndcopy3(PGconn *conn)

◆ PQenterPipelineMode()

int PQenterPipelineMode ( PGconn conn)

Definition at line 2894 of file fe-exec.c.

References appendPQExpBufferStr(), pg_conn::asyncStatus, pg_conn::errorMessage, libpq_gettext, PGASYNC_IDLE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, and PQ_PIPELINE_ON.

Referenced by executeMetaCommand(), test_disallowed_in_pipeline(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), and test_uniqviol().

2895 {
2896  if (!conn)
2897  return 0;
2898 
2899  /* succeed with no action if already in pipeline mode */
2900  if (conn->pipelineStatus != PQ_PIPELINE_OFF)
2901  return 1;
2902 
2903  if (conn->asyncStatus != PGASYNC_IDLE)
2904  {
2906  libpq_gettext("cannot enter pipeline mode, connection not idle\n"));
2907  return 0;
2908  }
2909 
2911 
2912  return 1;
2913 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:417
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
PQExpBufferData errorMessage
Definition: libpq-int.h:571
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQescapeBytea()

unsigned char* PQescapeBytea ( const unsigned char *  from,
size_t  from_length,
size_t *  to_length 
)

Definition at line 4234 of file fe-exec.c.

References PQescapeByteaInternal(), and static_std_strings.

4235 {
4236  return PQescapeByteaInternal(NULL, from, from_length, to_length,
4238  false /* can't use hex */ );
4239 }
static bool static_std_strings
Definition: fe-exec.c:52
static unsigned char * PQescapeByteaInternal(PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length, bool std_strings, bool use_hex)
Definition: fe-exec.c:4122

◆ PQescapeByteaConn()

unsigned char* PQescapeByteaConn ( PGconn conn,
const unsigned char *  from,
size_t  from_length,
size_t *  to_length 
)

Definition at line 4219 of file fe-exec.c.

References pg_conn::errorMessage, PQescapeByteaInternal(), resetPQExpBuffer(), pg_conn::std_strings, and pg_conn::sversion.

4222 {
4223  if (!conn)
4224  return NULL;
4225 
4227 
4228  return PQescapeByteaInternal(conn, from, from_length, to_length,
4229  conn->std_strings,
4230  (conn->sversion >= 90000));
4231 }
int sversion
Definition: libpq-int.h:449
PQExpBufferData errorMessage
Definition: libpq-int.h:571
bool std_strings
Definition: libpq-int.h:471
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
static unsigned char * PQescapeByteaInternal(PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length, bool std_strings, bool use_hex)
Definition: fe-exec.c:4122

◆ PQescapeByteaInternal()

static unsigned char* PQescapeByteaInternal ( PGconn conn,
const unsigned char *  from,
size_t  from_length,
size_t *  to_length,
bool  std_strings,
bool  use_hex 
)
static

Definition at line 4122 of file fe-exec.c.

References appendPQExpBufferStr(), pg_conn::errorMessage, hextbl, i, libpq_gettext, and malloc.

Referenced by PQescapeBytea(), and PQescapeByteaConn().

4125 {
4126  const unsigned char *vp;
4127  unsigned char *rp;
4128  unsigned char *result;
4129  size_t i;
4130  size_t len;
4131  size_t bslash_len = (std_strings ? 1 : 2);
4132 
4133  /*
4134  * empty string has 1 char ('\0')
4135  */
4136  len = 1;
4137 
4138  if (use_hex)
4139  {
4140  len += bslash_len + 1 + 2 * from_length;
4141  }
4142  else
4143  {
4144  vp = from;
4145  for (i = from_length; i > 0; i--, vp++)
4146  {
4147  if (*vp < 0x20 || *vp > 0x7e)
4148  len += bslash_len + 3;
4149  else if (*vp == '\'')
4150  len += 2;
4151  else if (*vp == '\\')
4152  len += bslash_len + bslash_len;
4153  else
4154  len++;
4155  }
4156  }
4157 
4158  *to_length = len;
4159  rp = result = (unsigned char *) malloc(len);
4160  if (rp == NULL)
4161  {
4162  if (conn)
4164  libpq_gettext("out of memory\n"));
4165  return NULL;
4166  }
4167 
4168  if (use_hex)
4169  {
4170  if (!std_strings)
4171  *rp++ = '\\';
4172  *rp++ = '\\';
4173  *rp++ = 'x';
4174  }
4175 
4176  vp = from;
4177  for (i = from_length; i > 0; i--, vp++)
4178  {
4179  unsigned char c = *vp;
4180 
4181  if (use_hex)
4182  {
4183  *rp++ = hextbl[(c >> 4) & 0xF];
4184  *rp++ = hextbl[c & 0xF];
4185  }
4186  else if (c < 0x20 || c > 0x7e)
4187  {
4188  if (!std_strings)
4189  *rp++ = '\\';
4190  *rp++ = '\\';
4191  *rp++ = (c >> 6) + '0';
4192  *rp++ = ((c >> 3) & 07) + '0';
4193  *rp++ = (c & 07) + '0';
4194  }
4195  else if (c == '\'')
4196  {
4197  *rp++ = '\'';
4198  *rp++ = '\'';
4199  }
4200  else if (c == '\\')
4201  {
4202  if (!std_strings)
4203  {
4204  *rp++ = '\\';
4205  *rp++ = '\\';
4206  }
4207  *rp++ = '\\';
4208  *rp++ = '\\';
4209  }
4210  else
4211  *rp++ = c;
4212  }
4213  *rp = '\0';
4214 
4215  return result;
4216 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define malloc(a)
Definition: header.h:50
char * c
PQExpBufferData errorMessage
Definition: libpq-int.h:571
static const char hextbl[]
Definition: fe-exec.c:4081
int i
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQescapeIdentifier()

char* PQescapeIdentifier ( PGconn conn,
const char *  str,
size_t  len 
)

Definition at line 4075 of file fe-exec.c.

References PQescapeInternal().

Referenced by initCreatePKeys(), initCreateTables(), main(), psql_get_variable(), stringlist_to_identifierstr(), and vacuumlo().

4076 {
4077  return PQescapeInternal(conn, str, len, true);
4078 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:3946

◆ PQescapeInternal()

static char* PQescapeInternal ( PGconn conn,
const char *  str,
size_t  len,
bool  as_ident 
)
static

Definition at line 3946 of file fe-exec.c.

References appendPQExpBufferStr(), pg_conn::client_encoding, pg_conn::errorMessage, i, IS_HIGHBIT_SET, libpq_gettext, malloc, pg_encoding_mblen(), resetPQExpBuffer(), and generate_unaccent_rules::str.

Referenced by PQescapeIdentifier(), and PQescapeLiteral().

3947 {
3948  const char *s;
3949  char *result;
3950  char *rp;
3951  int num_quotes = 0; /* single or double, depending on as_ident */
3952  int num_backslashes = 0;
3953  int input_len;
3954  int result_size;
3955  char quote_char = as_ident ? '"' : '\'';
3956 
3957  /* We must have a connection, else fail immediately. */
3958  if (!conn)
3959  return NULL;
3960 
3962 
3963  /* Scan the string for characters that must be escaped. */
3964  for (s = str; (s - str) < len && *s != '\0'; ++s)
3965  {
3966  if (*s == quote_char)
3967  ++num_quotes;
3968  else if (*s == '\\')
3969  ++num_backslashes;
3970  else if (IS_HIGHBIT_SET(*s))
3971  {
3972  int charlen;
3973 
3974  /* Slow path for possible multibyte characters */
3975  charlen = pg_encoding_mblen(conn->client_encoding, s);
3976 
3977  /* Multibyte character overruns allowable length. */
3978  if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
3979  {
3981  libpq_gettext("incomplete multibyte character\n"));
3982  return NULL;
3983  }
3984 
3985  /* Adjust s, bearing in mind that for loop will increment it. */
3986  s += charlen - 1;
3987  }
3988  }
3989 
3990  /* Allocate output buffer. */
3991  input_len = s - str;
3992  result_size = input_len + num_quotes + 3; /* two quotes, plus a NUL */
3993  if (!as_ident && num_backslashes > 0)
3994  result_size += num_backslashes + 2;
3995  result = rp = (char *) malloc(result_size);
3996  if (rp == NULL)
3997  {
3999  libpq_gettext("out of memory\n"));
4000  return NULL;
4001  }
4002 
4003  /*
4004  * If we are escaping a literal that contains backslashes, we use the
4005  * escape string syntax so that the result is correct under either value
4006  * of standard_conforming_strings. We also emit a leading space in this
4007  * case, to guard against the possibility that the result might be
4008  * interpolated immediately following an identifier.
4009  */
4010  if (!as_ident && num_backslashes > 0)
4011  {
4012  *rp++ = ' ';
4013  *rp++ = 'E';
4014  }
4015 
4016  /* Opening quote. */
4017  *rp++ = quote_char;
4018 
4019  /*
4020  * Use fast path if possible.
4021  *
4022  * We've already verified that the input string is well-formed in the
4023  * current encoding. If it contains no quotes and, in the case of
4024  * literal-escaping, no backslashes, then we can just copy it directly to
4025  * the output buffer, adding the necessary quotes.
4026  *
4027  * If not, we must rescan the input and process each character
4028  * individually.
4029  */
4030  if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
4031  {
4032  memcpy(rp, str, input_len);
4033  rp += input_len;
4034  }
4035  else
4036  {
4037  for (s = str; s - str < input_len; ++s)
4038  {
4039  if (*s == quote_char || (!as_ident && *s == '\\'))
4040  {
4041  *rp++ = *s;
4042  *rp++ = *s;
4043  }
4044  else if (!IS_HIGHBIT_SET(*s))
4045  *rp++ = *s;
4046  else
4047  {
4048  int i = pg_encoding_mblen(conn->client_encoding, s);
4049 
4050  while (1)
4051  {
4052  *rp++ = *s;
4053  if (--i == 0)
4054  break;
4055  ++s; /* for loop will provide the final increment */
4056  }
4057  }
4058  }
4059  }
4060 
4061  /* Closing quote and terminating NUL. */
4062  *rp++ = quote_char;
4063  *rp = '\0';
4064 
4065  return result;
4066 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define malloc(a)
Definition: header.h:50
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1156
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1914
PQExpBufferData errorMessage
Definition: libpq-int.h:571
int i
int client_encoding
Definition: libpq-int.h:470
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQescapeLiteral()

char* PQescapeLiteral ( PGconn conn,
const char *  str,
size_t  len 
)

Definition at line 4069 of file fe-exec.c.

References PQescapeInternal().

Referenced by DescribeQuery(), libpqrcv_startstreaming(), and psql_get_variable().

4070 {
4071  return PQescapeInternal(conn, str, len, false);
4072 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:3946

◆ PQescapeString()

size_t PQescapeString ( char *  to,
const char *  from,
size_t  length 
)

Definition at line 3931 of file fe-exec.c.

References PQescapeStringInternal(), static_client_encoding, and static_std_strings.

Referenced by get_comma_elts(), and quote_postgres().

3932 {
3933  return PQescapeStringInternal(NULL, to, from, length, NULL,
3936 }
static bool static_std_strings
Definition: fe-exec.c:52
static int static_client_encoding
Definition: fe-exec.c:51
static size_t PQescapeStringInternal(PGconn *conn, char *to, const char *from, size_t length, int *error, int encoding, bool std_strings)
Definition: fe-exec.c:3835

◆ PQescapeStringConn()

size_t PQescapeStringConn ( PGconn conn,
char *  to,
const char *  from,
size_t  length,
int *  error 
)

Definition at line 3910 of file fe-exec.c.

References pg_conn::client_encoding, pg_conn::errorMessage, PQescapeStringInternal(), resetPQExpBuffer(), and pg_conn::std_strings.

Referenced by appendStringLiteralConn(), BaseBackup(), check_loadable_libraries(), and do_lo_import().

3913 {
3914  if (!conn)
3915  {
3916  /* force empty-string result */
3917  *to = '\0';
3918  if (error)
3919  *error = 1;
3920  return 0;
3921  }
3922 
3924 
3925  return PQescapeStringInternal(conn, to, from, length, error,
3926  conn->client_encoding,
3927  conn->std_strings);
3928 }
static void error(void)
Definition: sql-dyntest.c:147
PQExpBufferData errorMessage
Definition: libpq-int.h:571
bool std_strings
Definition: libpq-int.h:471
static size_t PQescapeStringInternal(PGconn *conn, char *to, const char *from, size_t length, int *error, int encoding, bool std_strings)
Definition: fe-exec.c:3835
int client_encoding
Definition: libpq-int.h:470
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148

◆ PQescapeStringInternal()

static size_t PQescapeStringInternal ( PGconn conn,
char *  to,
const char *  from,
size_t  length,
int *  error,
int  encoding,
bool  std_strings 
)
static

Definition at line 3835 of file fe-exec.c.

References appendPQExpBufferStr(), pg_conn::errorMessage, i, IS_HIGHBIT_SET, libpq_gettext, pg_encoding_mblen(), remaining, source, and SQL_STR_DOUBLE.

Referenced by PQescapeString(), and PQescapeStringConn().

3839 {
3840  const char *source = from;
3841  char *target = to;
3842  size_t remaining = length;
3843 
3844  if (error)
3845  *error = 0;
3846 
3847  while (remaining > 0 && *source != '\0')
3848  {
3849  char c = *source;
3850  int len;
3851  int i;
3852 
3853  /* Fast path for plain ASCII */
3854  if (!IS_HIGHBIT_SET(c))
3855  {
3856  /* Apply quoting if needed */
3857  if (SQL_STR_DOUBLE(c, !std_strings))
3858  *target++ = c;
3859  /* Copy the character */
3860  *target++ = c;
3861  source++;
3862  remaining--;
3863  continue;
3864  }
3865 
3866  /* Slow path for possible multibyte characters */
3867  len = pg_encoding_mblen(encoding, source);
3868 
3869  /* Copy the character */
3870  for (i = 0; i < len; i++)
3871  {
3872  if (remaining == 0 || *source == '\0')
3873  break;
3874  *target++ = *source++;
3875  remaining--;
3876  }
3877 
3878  /*
3879  * If we hit premature end of string (ie, incomplete multibyte
3880  * character), try to pad out to the correct length with spaces. We
3881  * may not be able to pad completely, but we will always be able to
3882  * insert at least one pad space (since we'd not have quoted a
3883  * multibyte character). This should be enough to make a string that
3884  * the server will error out on.
3885  */
3886  if (i < len)
3887  {
3888  if (error)
3889  *error = 1;
3890  if (conn)
3892  libpq_gettext("incomplete multibyte character\n"));
3893  for (; i < len; i++)
3894  {
3895  if (((size_t) (target - to)) / 2 >= length)
3896  break;
3897  *target++ = ' ';
3898  }
3899  break;
3900  }
3901  }
3902 
3903  /* Write the terminating NUL character. */
3904  *target = '\0';
3905 
3906  return target - to;
3907 }
int remaining
Definition: informix.c:667
static void error(void)
Definition: sql-dyntest.c:147
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1156
char * c
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1914
PQExpBufferData errorMessage
Definition: libpq-int.h:571
static rewind_source * source
Definition: pg_rewind.c:79
int32 encoding
Definition: pg_database.h:41
int i
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:1164
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQexec()

PGresult* PQexec ( PGconn conn,
const char *  query 
)

Definition at line 2193 of file fe-exec.c.

References PQexecFinish(), PQexecStart(), and PQsendQuery().

Referenced by _doSetSessionAuth(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), check_loadable_libraries(), check_prepare_conn(), CreateReplicationSlot(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), deallocate_one(), DescribeQuery(), DropReplicationSlot(), ecpg_autostart_transaction(), ecpg_execute(), ecpg_is_type_an_array(), ECPGsetcommit(), ECPGtrans(), ExecQueryUsingCursor(), executeCommand(), executeMaintenanceCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlQuery(), ExecuteSqlStatement(), executeStatement(), get_create_object_cmd(), GetConnection(), GetTableInfo(), init_libpq_conn(), initGenerateDataClientSide(), libpq_traverse_files(), lo_initialize(), lockTableForWorker(), lookup_object_oid(), main(), pgfdw_xact_callback(), PQencryptPasswordConn(), PQsetClientEncoding(), PSQLexec(), PSQLexecWatch(), ReceiveXlogStream(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_permutation(), run_simple_command(), run_simple_query(), RunIdentifySystem(), SendQuery(), sql_conn(), sql_exec(), StreamLogicalLog(), test_disallowed_in_pipeline(), test_pipeline_abort(), test_prepared(), test_transaction(), test_uniqviol(), tryExecuteStatement(), and vacuumlo().

2194 {
2195  if (!PQexecStart(conn))
2196  return NULL;
2197  if (!PQsendQuery(conn, query))
2198  return NULL;
2199  return PQexecFinish(conn);
2200 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1326
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2340
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2275

◆ PQexecFinish()

static PGresult * PQexecFinish ( PGconn conn)
static

Definition at line 2340 of file fe-exec.c.

References CONNECTION_BAD, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PQclear(), PQgetResult(), pg_result::resultStatus, and pg_conn::status.

Referenced by PQdescribePortal(), PQdescribePrepared(), PQexec(), PQexecParams(), PQexecPrepared(), and PQprepare().

2341 {
2342  PGresult *result;
2343  PGresult *lastResult;
2344 
2345  /*
2346  * For backwards compatibility, return the last result if there are more
2347  * than one. (We used to have logic here to concatenate successive error
2348  * messages, but now that happens automatically, since conn->errorMessage
2349  * will continue to accumulate errors throughout this loop.)
2350  *
2351  * We have to stop if we see copy in/out/both, however. We will resume
2352  * parsing after application performs the data transfer.
2353  *
2354  * Also stop if the connection is lost (else we'll loop infinitely).
2355  */
2356  lastResult = NULL;
2357  while ((result = PQgetResult(conn)) != NULL)
2358  {
2359  if (lastResult)
2360  PQclear(lastResult);
2361  lastResult = result;
2362  if (result->resultStatus == PGRES_COPY_IN ||
2363  result->resultStatus == PGRES_COPY_OUT ||
2364  result->resultStatus == PGRES_COPY_BOTH ||
2365  conn->status == CONNECTION_BAD)
2366  break;
2367  }
2368 
2369  return lastResult;
2370 }
void PQclear(PGresult *res)
Definition: fe-exec.c:694
ConnStatusType status
Definition: libpq-int.h:410
ExecStatusType resultStatus
Definition: libpq-int.h:178
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1978

◆ PQexecParams()

PGresult* PQexecParams ( PGconn conn,
const char *  command,
int  nParams,
const Oid paramTypes,
const char *const *  paramValues,
const int *  paramLengths,
const int *  paramFormats,
int  resultFormat 
)

Definition at line 2207 of file fe-exec.c.

References PQexecFinish(), PQexecStart(), and PQsendQueryParams().

Referenced by ecpg_execute(), libpq_fetch_file(), and main().

2215 {
2216  if (!PQexecStart(conn))
2217  return NULL;
2218  if (!PQsendQueryParams(conn, command,
2219  nParams, paramTypes, paramValues, paramLengths,
2220  paramFormats, resultFormat))
2221  return NULL;
2222  return PQexecFinish(conn);
2223 }
int PQsendQueryParams(PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:1438
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2340
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2275

◆ PQexecPrepared()

PGresult* PQexecPrepared ( PGconn conn,
const char *  stmtName,
int  nParams,
const char *const *  paramValues,
const int *  paramLengths,
const int *  paramFormats,
int  resultFormat 
)

Definition at line 2254 of file fe-exec.c.

References PQexecFinish(), PQexecStart(), and PQsendQueryPrepared().

Referenced by ecpg_execute(), and try_complete_step().

2261 {
2262  if (!PQexecStart(conn))
2263  return NULL;
2264  if (!PQsendQueryPrepared(conn, stmtName,
2265  nParams, paramValues, paramLengths,
2266  paramFormats, resultFormat))
2267  return NULL;
2268  return PQexecFinish(conn);
2269 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2340
int PQsendQueryPrepared(PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:1584
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2275

◆ PQexecStart()

static bool PQexecStart ( PGconn conn)
static

Definition at line 2275 of file fe-exec.c.

References appendPQExpBufferStr(), pg_conn::asyncStatus, CONNECTION_BAD, pg_conn::errorMessage, libpq_gettext, PGASYNC_BUSY, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, PQclear(), PQgetResult(), PQputCopyEnd(), resetPQExpBuffer(), pg_result::resultStatus, and pg_conn::status.

Referenced by PQdescribePortal(), PQdescribePrepared(), PQexec(), PQexecParams(), PQexecPrepared(), and PQprepare().

2276 {
2277  PGresult *result;
2278 
2279  if (!conn)
2280  return false;
2281 
2282  if (conn->pipelineStatus != PQ_PIPELINE_OFF)
2283  {
2285  libpq_gettext("synchronous command execution functions are not allowed in pipeline mode\n"));
2286  return false;
2287  }
2288 
2289  /*
2290  * Since this is the beginning of a query cycle, reset the error buffer.
2291  */
2293 
2294  /*
2295  * Silently discard any prior query result that application didn't eat.
2296  * This is probably poor design, but it's here for backward compatibility.
2297  */
2298  while ((result = PQgetResult(conn)) != NULL)
2299  {
2300  ExecStatusType resultStatus = result->resultStatus;
2301 
2302  PQclear(result); /* only need its status */
2303  if (resultStatus == PGRES_COPY_IN)
2304  {
2305  /* get out of a COPY IN state */
2306  if (PQputCopyEnd(conn,
2307  libpq_gettext("COPY terminated by new PQexec")) < 0)
2308  return false;
2309  /* keep waiting to swallow the copy's failure message */
2310  }
2311  else if (resultStatus == PGRES_COPY_OUT)
2312  {
2313  /*
2314  * Get out of a COPY OUT state: we just switch back to BUSY and
2315  * allow the remaining COPY data to be dropped on the floor.
2316  */
2317  conn->asyncStatus = PGASYNC_BUSY;
2318  /* keep waiting to swallow the copy's completion message */
2319  }
2320  else if (resultStatus == PGRES_COPY_BOTH)
2321  {
2322  /* We don't allow PQexec during COPY BOTH */
2324  libpq_gettext("PQexec not allowed during COPY BOTH\n"));
2325  return false;
2326  }
2327  /* check for loss of connection, too */
2328  if (conn->status == CONNECTION_BAD)
2329  return false;
2330  }
2331 
2332  /* OK to send a command */
2333  return true;
2334 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:417
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2600
ExecStatusType
Definition: libpq-fe.h:92
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
PQExpBufferData errorMessage
Definition: libpq-int.h:571
void PQclear(PGresult *res)
Definition: fe-exec.c:694
ConnStatusType status
Definition: libpq-int.h:410
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
ExecStatusType resultStatus
Definition: libpq-int.h:178
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1978
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQexitPipelineMode()

int PQexitPipelineMode ( PGconn conn)

Definition at line 2926 of file fe-exec.c.

References appendPQExpBufferStr(), pg_conn::asyncStatus, pg_conn::cmd_queue_head, pg_conn::errorMessage, libpq_gettext, PGASYNC_BUSY, PGASYNC_IDLE, PGASYNC_READY, PGASYNC_READY_MORE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, and pqFlush().

Referenced by readCommandResponse(), test_disallowed_in_pipeline(), test_multi_pipelines(), test_pipeline_abort(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), and test_transaction().

2927 {
2928  if (!conn)
2929  return 0;
2930 
2931  if (conn->pipelineStatus == PQ_PIPELINE_OFF)
2932  return 1;
2933 
2934  switch (conn->asyncStatus)
2935  {
2936  case PGASYNC_READY:
2937  case PGASYNC_READY_MORE:
2938  /* there are some uncollected results */
2940  libpq_gettext("cannot exit pipeline mode with uncollected results\n"));
2941  return 0;
2942 
2943  case PGASYNC_BUSY:
2945  libpq_gettext("cannot exit pipeline mode while busy\n"));
2946  return 0;
2947 
2948  default:
2949  /* OK */
2950  break;
2951  }
2952 
2953  /* still work to process */
2954  if (conn->cmd_queue_head != NULL)
2955  {
2957  libpq_gettext("cannot exit pipeline mode with uncollected results\n"));
2958  return 0;
2959  }
2960 
2962  conn->asyncStatus = PGASYNC_IDLE;
2963 
2964  /* Flush any pending data in out buffer */
2965  if (pqFlush(conn) < 0)
2966  return 0; /* error message is setup already */
2967  return 1;
2968 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:965
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:434
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:417
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
PQExpBufferData errorMessage
Definition: libpq-int.h:571
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQfformat()

int PQfformat ( const PGresult res,
int  field_num 
)

Definition at line 3475 of file fe-exec.c.

References pg_result::attDescs, check_field_number(), and pgresAttDesc::format.

Referenced by ecpg_get_data(), ecpg_store_result(), and process_queued_fetch_requests().

3476 {
3477  if (!check_field_number(res, field_num))
3478  return 0;
3479  if (res->attDescs)
3480  return res->attDescs[field_num].format;
3481  else
3482  return 0;
3483 }
PGresAttDesc * attDescs
Definition: libpq-int.h:172
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3277

◆ PQflush()

int PQflush ( PGconn conn)

◆ PQfmod()

int PQfmod ( const PGresult res,
int  field_num 
)

Definition at line 3508 of file fe-exec.c.

References pg_result::attDescs, pgresAttDesc::atttypmod, and check_field_number().

Referenced by DescribeQuery(), and ECPGget_desc().

3509 {
3510  if (!check_field_number(res, field_num))
3511  return 0;
3512  if (res->attDescs)
3513  return res->attDescs[field_num].atttypmod;
3514  else
3515  return 0;
3516 }
PGresAttDesc * attDescs
Definition: libpq-int.h:172
int atttypmod
Definition: libpq-fe.h:267
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3277

◆ PQfn()

PGresult* PQfn ( PGconn conn,
int  fnid,
int *  result_buf,
int *  result_len,
int  result_is_int,
const PQArgBlock args,
int  nargs 
)

Definition at line 2833 of file fe-exec.c.

References appendPQExpBufferStr(), pg_conn::asyncStatus, pg_conn::errorMessage, libpq_gettext, PGASYNC_IDLE, PGINVALID_SOCKET, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqFunctionCall3(), resetPQExpBuffer(), pg_conn::result, and pg_conn::sock.

Referenced by lo_close(), lo_creat(), lo_create(), lo_lseek(), lo_lseek64(), lo_open(), lo_read(), lo_tell(), lo_tell64(), lo_truncate(), lo_truncate64(), lo_unlink(), and lo_write().

2840 {
2841  *result_len = 0;
2842 
2843  if (!conn)
2844  return NULL;
2845 
2846  /*
2847  * Since this is the beginning of a query cycle, reset the error buffer.
2848  */
2850 
2851  if (conn->pipelineStatus != PQ_PIPELINE_OFF)
2852  {
2854  libpq_gettext("PQfn not allowed in pipeline mode\n"));
2855  return NULL;
2856  }
2857 
2858  if (conn->sock == PGINVALID_SOCKET || conn->asyncStatus != PGASYNC_IDLE ||
2859  conn->result != NULL)
2860  {
2862  libpq_gettext("connection in wrong state\n"));
2863  return NULL;
2864  }
2865 
2866  return pqFunctionCall3(conn, fnid,
2867  result_buf, result_len,
2868  result_is_int,
2869  args, nargs);
2870 }
PGresult * pqFunctionCall3(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:417
PGresult * result
Definition: libpq-int.h:500
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
pgsocket sock
Definition: libpq-int.h:444
#define PGINVALID_SOCKET
Definition: port.h:33
PQExpBufferData errorMessage
Definition: libpq-int.h:571
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQfname()

char* PQfname ( const PGresult res,
int  field_num 
)

Definition at line 3334 of file fe-exec.c.

References pg_result::attDescs, check_field_number(), and pgresAttDesc::name.

Referenced by DescribeQuery(), do_header(), dumpTableData_insert(), ecpg_build_compat_sqlda(), ecpg_build_native_sqlda(), ECPGget_desc(), indexOfColumn(), libpqrcv_processTuples(), main(), PQdisplayTuples(), PQprint(), PQprintTuples(), printCrosstab(), printQuery(), readCommandResponse(), sql_exec(), sqlda_compat_empty_size(), and StoreQueryTuple().

3335 {
3336  if (!check_field_number(res, field_num))
3337  return NULL;
3338  if (res->attDescs)
3339  return res->attDescs[field_num].name;
3340  else
3341  return NULL;
3342 }
PGresAttDesc * attDescs
Definition: libpq-int.h:172
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3277
char * name
Definition: libpq-fe.h:261

◆ PQfnumber()

int PQfnumber ( const PGresult res,
const char *  field_name 
)

Definition at line 3356 of file fe-exec.c.

References pg_result::attDescs, free, i, pgresAttDesc::name, pg_result::numAttributes, and pg_tolower().

Referenced by append_depends_on_extension(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_rel_oid(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), check_for_data_types_usage(), check_for_isn_and_int8_passing_mismatch(), check_for_tables_with_oids(), check_for_user_defined_encoding_conversions(), check_for_user_defined_postfix_ops(), check_proper_datallowconn(), collectComments(), collectSecLabels(), describeOneTableDetails(), dropRoles(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpDatabase(), dumpDomain(), dumpEnumType(), dumpFunc(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoles(), dumpTableSchema(), dumpTSConfig(), dumpUserMappings(), findLastBuiltinOid_V71(), get_db_infos(), get_rel_infos(), get_tablespace_paths(), getAccessMethods(), getAggregates(), getBlobs(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getIndexes(), getInherits(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPolicies(), getProcLangs(), getPublications(), getPublicationTables(), getRules(), getSubscriptions(), getTableAttrs(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), new_9_0_populate_pg_largeobject_metadata(), old_9_6_invalidate_hash_indexes(), processExtensionTables(), report_extension_updates(), set_frozenxids(), and show_binary_results().

3357 {
3358  char *field_case;
3359  bool in_quotes;
3360  bool all_lower = true;
3361  const char *iptr;
3362  char *optr;
3363  int i;
3364 
3365  if (!res)
3366  return -1;
3367 
3368  /*
3369  * Note: it is correct to reject a zero-length input string; the proper
3370  * input to match a zero-length field name would be "".
3371  */
3372  if (field_name == NULL ||
3373  field_name[0] == '\0' ||
3374  res->attDescs == NULL)
3375  return -1;
3376 
3377  /*
3378  * Check if we can avoid the strdup() and related work because the
3379  * passed-in string wouldn't be changed before we do the check anyway.
3380  */
3381  for (iptr = field_name; *iptr; iptr++)
3382  {
3383  char c = *iptr;
3384 
3385  if (c == '"' || c != pg_tolower((unsigned char) c))
3386  {
3387  all_lower = false;
3388  break;
3389  }
3390  }
3391 
3392  if (all_lower)
3393  for (i = 0; i < res->numAttributes; i++)
3394  if (strcmp(field_name, res->attDescs[i].name) == 0)
3395  return i;
3396 
3397  /* Fall through to the normal check if that didn't work out. */
3398 
3399  /*
3400  * Note: this code will not reject partially quoted strings, eg
3401  * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
3402  * condition.
3403  */
3404  field_case = strdup(field_name);
3405  if (field_case == NULL)
3406  return -1; /* grotty */
3407 
3408  in_quotes = false;
3409  optr = field_case;
3410  for (iptr = field_case; *iptr; iptr++)
3411  {
3412  char c = *iptr;
3413 
3414  if (in_quotes)
3415  {
3416  if (c == '"')
3417  {
3418  if (iptr[1] == '"')
3419  {
3420  /* doubled quotes become a single quote */
3421  *optr++ = '"';
3422  iptr++;
3423  }
3424  else
3425  in_quotes = false;
3426  }
3427  else
3428  *optr++ = c;
3429  }
3430  else if (c == '"')
3431  in_quotes = true;
3432  else
3433  {
3434  c = pg_tolower((unsigned char) c);
3435  *optr++ = c;
3436  }
3437  }
3438  *optr = '\0';
3439 
3440  for (i = 0; i < res->numAttributes; i++)
3441  {
3442  if (strcmp(field_case, res->attDescs[i].name) == 0)
3443  {
3444  free(field_case);
3445  return i;
3446  }
3447  }
3448  free(field_case);
3449  return -1;
3450 }
unsigned char pg_tolower(unsigned char ch)
Definition: pgstrcasecmp.c:122
PGresAttDesc * attDescs
Definition: libpq-int.h:172
char * c
int numAttributes
Definition: libpq-int.h:171
#define free(a)
Definition: header.h:65
int i
char * name
Definition: libpq-fe.h:261

◆ PQfreemem()

◆ PQfreeNotify()

void PQfreeNotify ( PGnotify notify)

Definition at line 3813 of file fe-exec.c.

References PQfreemem().

Referenced by PQfreemem().

3814 {
3815  PQfreemem(notify);
3816 }
void PQfreemem(void *ptr)
Definition: fe-exec.c:3796

◆ PQfsize()

int PQfsize ( const PGresult res,
int  field_num 
)

Definition at line 3497 of file fe-exec.c.

References pg_result::attDescs, check_field_number(), and pgresAttDesc::typlen.

Referenced by ecpg_build_compat_sqlda(), and ECPGget_desc().

3498 {
3499  if (!check_field_number(res, field_num))
3500  return 0;
3501  if (res->attDescs)
3502  return res->attDescs[field_num].typlen;
3503  else
3504  return 0;
3505 }
PGresAttDesc * attDescs
Definition: libpq-int.h:172
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3277

◆ PQftable()

Oid PQftable ( const PGresult res,
int  field_num 
)

Definition at line 3453 of file fe-exec.c.

References pg_result::attDescs, check_field_number(), InvalidOid, and pgresAttDesc::tableid.

3454 {
3455  if (!check_field_number(res, field_num))
3456  return InvalidOid;
3457  if (res->attDescs)
3458  return res->attDescs[field_num].tableid;
3459  else
3460  return InvalidOid;
3461 }
PGresAttDesc * attDescs
Definition: libpq-int.h:172
#define InvalidOid
Definition: postgres_ext.h:36
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3277

◆ PQftablecol()

int PQftablecol ( const PGresult res,
int  field_num 
)

Definition at line 3464 of file fe-exec.c.

References pg_result::attDescs, check_field_number(), and pgresAttDesc::columnid.

3465 {
3466  if (!check_field_number(res, field_num))
3467  return 0;
3468  if (res->attDescs)
3469  return res->attDescs[field_num].columnid;
3470  else
3471  return 0;
3472 }
int columnid
Definition: libpq-fe.h:263
PGresAttDesc * attDescs
Definition: libpq-int.h:172
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3277

◆ PQftype()

Oid PQftype ( const PGresult res,
int  field_num 
)

Definition at line 3486 of file fe-exec.c.

References pg_result::attDescs, check_field_number(), InvalidOid, and pgresAttDesc::typid.

Referenced by DescribeQuery(), dumpTableData_insert(), ecpg_build_compat_sqlda(), ecpg_build_native_sqlda(), ecpg_store_result(), ECPGget_desc(), printCrosstab(), printQuery(), process_queued_fetch_requests(), sqlda_common_total_size(), and test_prepared().

3487 {
3488  if (!check_field_number(res, field_num))
3489  return InvalidOid;
3490  if (res->attDescs)
3491  return res->attDescs[field_num].typid;
3492  else
3493  return InvalidOid;
3494 }
PGresAttDesc * attDescs
Definition: libpq-int.h:172
#define InvalidOid
Definition: postgres_ext.h:36
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3277

◆ PQgetCopyData()

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

Definition at line 2668 of file fe-exec.c.

References appendPQExpBufferStr(), pg_conn::asyncStatus, pg_conn::errorMessage, libpq_gettext, PGASYNC_COPY_BOTH, PGASYNC_COPY_OUT, and pqGetCopyData3().

Referenced by CopyStreamReceive(), dumpTableData_copy(), ecpg_process_output(), handleCopyOut(), libpqrcv_receive(), ReceiveCopyData(), and StreamLogicalLog().

2669 {
2670  *buffer = NULL; /* for all failure cases */
2671  if (!conn)
2672  return -2;
2673  if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2674  conn->asyncStatus != PGASYNC_COPY_BOTH)
2675  {
2677  libpq_gettext("no COPY in progress\n"));
2678  return -2;
2679  }
2680  return pqGetCopyData3(conn, buffer, async);
2681 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
int pqGetCopyData3(PGconn *conn, char **buffer, int async)
PQExpBufferData errorMessage
Definition: libpq-int.h:571
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQgetisnull()

int PQgetisnull ( const PGresult res,
int  tup_num,
int  field_num 
)

Definition at line 3667 of file fe-exec.c.

References check_tuple_field_number(), pgresAttValue::len, NULL_LEN, and pg_result::tuples.

Referenced by BaseBackup(), compile_database_list(), compile_relation_list_one_db(), describeOneTableDetails(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpDatabaseConfig(), dumpDomain(), dumpFunc(), dumpRangeType(), dumpRoleMembership(), dumpRoles(), dumpTableData_insert(), dumpUserConfig(), ecpg_get_data(), ecpg_set_compat_sqlda(), ecpg_set_native_sqlda(), ECPGget_desc(), ExecQueryTuples(), getAggregates(), getBlobs(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getNamespaces(), getPolicies(), getProcLangs(), getSubscriptions(), GetTableInfo(), getTables(), getTriggers(), getTSDictionaries(), getTypes(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_create_slot(), libpqrcv_processTuples(), listTSConfigsVerbose(), listTSParsersVerbose(), make_tuple_from_result_row(), materializeResult(), postgresImportForeignSchema(), printCrosstab(), printQuery(), PrintResultsInCrosstab(), process_queued_fetch_requests(), ReceiveAndUnpackTarFile(), ReceiveTarFile(), run_simple_query(), RunIdentifySystem(), sqlda_common_total_size(), StoreQueryTuple(), storeRow(), vacuum_one_database(), and verify_heap_slot_handler().

3668 {
3669  if (!check_tuple_field_number(res, tup_num, field_num))
3670  return 1; /* pretend it is null */
3671  if (res->tuples[tup_num][field_num].len == NULL_LEN)
3672  return 1;
3673  else
3674  return 0;
3675 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3292
#define NULL_LEN
Definition: libpq-int.h:134
PGresAttValue ** tuples
Definition: libpq-int.h:173

◆ PQgetlength()

int PQgetlength ( const PGresult res,
int  tup_num,
int  field_num 
)

Definition at line 3653 of file fe-exec.c.

References check_tuple_field_number(), pgresAttValue::len, NULL_LEN, and pg_result::tuples.

Referenced by createViewAsClause(), do_field(), ecpg_get_data(), ecpg_store_result(), ECPGget_desc(), libpq_fetch_file(), libpqrcv_readtimelinehistoryfile(), PQdisplayTuples(), process_queued_fetch_requests(), and show_binary_results().

3654 {
3655  if (!check_tuple_field_number(res, tup_num, field_num))
3656  return 0;
3657  if (res->tuples[tup_num][field_num].len != NULL_LEN)
3658  return res->tuples[tup_num][field_num].len;
3659  else
3660  return 0;
3661 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3292
#define NULL_LEN
Definition: libpq-int.h:134
PGresAttValue ** tuples
Definition: libpq-int.h:173

◆ PQgetline()

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

Definition at line 2707 of file fe-exec.c.

References pqGetline3().

2708 {
2709  if (!s || maxlen <= 0)
2710  return EOF;
2711  *s = '\0';
2712  /* maxlen must be at least 3 to hold the \. terminator! */
2713  if (maxlen < 3)
2714  return EOF;
2715 
2716  if (!conn)
2717  return EOF;
2718 
2719  return pqGetline3(conn, s, maxlen);
2720 }
int pqGetline3(PGconn *conn, char *s, int maxlen)

◆ PQgetlineAsync()

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

Definition at line 2754 of file fe-exec.c.

References pqGetlineAsync3().

Referenced by pqGetline3().

2755 {
2756  if (!conn)
2757  return -1;
2758 
2759  return pqGetlineAsync3(conn, buffer, bufsize);
2760 }
int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)

◆ PQgetResult()

PGresult* PQgetResult ( PGconn conn)

Definition at line 1978 of file fe-exec.c.

References appendPQExpBuffer(), pg_conn::asyncStatus, pg_conn::cmd_queue_head, PGEventResultCreate::conn, conn, pg_conn::errorMessage, pg_result::events, getCopyResult(), i, libpq_gettext, PGEvent::name, pg_result::nEvents, parseInput(), PGEvent::passThrough, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_READY, PGASYNC_READY_MORE, PGEVT_RESULTCREATE, PGQUERY_SIMPLE, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_FATAL_ERROR, PGRES_PIPELINE_SYNC, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqCommandQueueAdvance(), pqFlush(), PQmakeEmptyPGresult(), pqPipelineProcessQueue(), pqPrepareAsyncResult(), pqReadData(), pqSaveErrorResult(), pqSaveWriteError(), pqSetResultError(), pqWait(), PGEvent::proc, PGcmdQueueEntry::queryclass, resetPQExpBuffer(), PGEventResultCreate::result, PGEvent::resultInitialized, pg_result::resultStatus, and pg_conn::write_failed.

Referenced by BaseBackup(), consumeQueryResult(), dblink_record_internal(), dumpTableData_copy(), ecpg_process_output(), EndDBCopyMode(), handleCopyIn(), handleCopyOut(), HandleEndOfCopyStream(), libpqrcv_PQgetResult(), pgfdw_get_cleanup_result(), pgfdw_get_result(), PQconnectPoll(), pqEndcopy3(), PQexecFinish(), PQexecStart(), process_queued_fetch_requests(), process_result(), ProcessResult(), readCommandResponse(), ReceiveCopyData(), ReceiveXlogStream(), storeQueryResult(), StreamLogicalLog(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), test_uniqviol(), try_complete_step(), and wait_on_slots().

1979 {
1980  PGresult *res;
1981 
1982  if (!conn)
1983  return NULL;
1984 
1985  /* Parse any available data, if our state permits. */
1986  parseInput(conn);
1987 
1988  /* If not ready to return something, block until we are. */
1989  while (conn->asyncStatus == PGASYNC_BUSY)
1990  {
1991  int flushResult;
1992 
1993  /*
1994  * If data remains unsent, send it. Else we might be waiting for the
1995  * result of a command the backend hasn't even got yet.
1996  */
1997  while ((flushResult = pqFlush(conn)) > 0)
1998  {
1999  if (pqWait(false, true, conn))
2000  {
2001  flushResult = -1;
2002  break;
2003  }
2004  }
2005 
2006  /*
2007  * Wait for some more data, and load it. (Note: if the connection has
2008  * been lost, pqWait should return immediately because the socket
2009  * should be read-ready, either with the last server data or with an
2010  * EOF indication. We expect therefore that this won't result in any
2011  * undue delay in reporting a previous write failure.)
2012  */
2013  if (flushResult ||
2014  pqWait(true, false, conn) ||
2015  pqReadData(conn) < 0)
2016  {
2017  /*
2018  * conn->errorMessage has been set by pqWait or pqReadData. We
2019  * want to append it to any already-received error message.
2020  */
2021  pqSaveErrorResult(conn);
2022  conn->asyncStatus = PGASYNC_IDLE;
2023  return pqPrepareAsyncResult(conn);
2024  }
2025 
2026  /* Parse it. */
2027  parseInput(conn);
2028 
2029  /*
2030  * If we had a write error, but nothing above obtained a query result
2031  * or detected a read error, report the write error.
2032  */
2033  if (conn->write_failed && conn->asyncStatus == PGASYNC_BUSY)
2034  {
2035  pqSaveWriteError(conn);
2036  conn->asyncStatus = PGASYNC_IDLE;
2037  return pqPrepareAsyncResult(conn);
2038  }
2039  }
2040 
2041  /* Return the appropriate thing. */
2042  switch (conn->asyncStatus)
2043  {
2044  case PGASYNC_IDLE:
2045  res = NULL; /* query is complete */
2046  if (conn->pipelineStatus != PQ_PIPELINE_OFF)
2047  {
2048  /*
2049  * We're about to return the NULL that terminates the round of
2050  * results from the current query; prepare to send the results
2051  * of the next query when we're called next. Also, since this
2052  * is the start of the results of the next query, clear any
2053  * prior error message.
2054  */
2056  pqPipelineProcessQueue(conn);
2057  }
2058  break;
2059  case PGASYNC_READY:
2060 
2061  /*
2062  * For any query type other than simple query protocol, we advance
2063  * the command queue here. This is because for simple query
2064  * protocol we can get the READY state multiple times before the
2065  * command is actually complete, since the command string can
2066  * contain many queries. In simple query protocol, the queue
2067  * advance is done by fe-protocol3 when it receives ReadyForQuery.
2068  */
2069  if (conn->cmd_queue_head &&
2071  pqCommandQueueAdvance(conn);
2072  res = pqPrepareAsyncResult(conn);
2073  if (conn->pipelineStatus != PQ_PIPELINE_OFF)
2074  {
2075  /*
2076  * We're about to send the results of the current query. Set
2077  * us idle now, and ...
2078  */
2079  conn->asyncStatus = PGASYNC_IDLE;
2080 
2081  /*
2082  * ... in cases when we're sending a pipeline-sync result,
2083  * move queue processing forwards immediately, so that next
2084  * time we're called, we're prepared to return the next result
2085  * received from the server. In all other cases, leave the
2086  * queue state change for next time, so that a terminating
2087  * NULL result is sent.
2088  *
2089  * (In other words: we don't return a NULL after a pipeline
2090  * sync.)
2091  */
2092  if (res && res->resultStatus == PGRES_PIPELINE_SYNC)
2093  pqPipelineProcessQueue(conn);
2094  }
2095  else
2096  {
2097  /* Set the state back to BUSY, allowing parsing to proceed. */
2098  conn->asyncStatus = PGASYNC_BUSY;
2099  }
2100  break;
2101  case PGASYNC_READY_MORE:
2102  res = pqPrepareAsyncResult(conn);
2103  /* Set the state back to BUSY, allowing parsing to proceed. */
2104  conn->asyncStatus = PGASYNC_BUSY;
2105  break;
2106  case PGASYNC_COPY_IN:
2107  res = getCopyResult(conn, PGRES_COPY_IN);
2108  break;
2109  case PGASYNC_COPY_OUT:
2110  res = getCopyResult(conn, PGRES_COPY_OUT);
2111  break;
2112  case PGASYNC_COPY_BOTH:
2113  res = getCopyResult(conn, PGRES_COPY_BOTH);
2114  break;
2115  default:
2117  libpq_gettext("unexpected asyncStatus: %d\n"),
2118  (int) conn->asyncStatus);
2120  break;
2121  }
2122 
2123  if (res)
2124  {
2125  int i;
2126 
2127  for (i = 0; i < res->nEvents; i++)
2128  {
2129  PGEventResultCreate evt;
2130 
2131  evt.conn = conn;
2132  evt.result = res;
2133  if (!res->events[i].proc(PGEVT_RESULTCREATE, &evt,
2134  res->events[i].passThrough))
2135  {
2137  libpq_gettext("PGEventProc \"%s\" failed during PGEVT_RESULTCREATE event\n"),
2138  res->events[i].name);
2139  pqSetResultError(res, &conn->errorMessage);
2141  break;
2142  }
2143  res->events[i].resultInitialized = true;
2144  }
2145  }
2146 
2147  return res;
2148 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:965
bool resultInitialized
Definition: libpq-int.h:165
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:434
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:417
int nEvents
Definition: libpq-int.h:189
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:804
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
PGQueryClass queryclass
Definition: libpq-int.h:322
bool write_failed
Definition: libpq-int.h:454
PGconn * conn
Definition: streamutil.c:54
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
int pqReadData(PGconn *conn)
Definition: fe-misc.c:568
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:990
static PGresult * getCopyResult(PGconn *conn, ExecStatusType copytype)
Definition: fe-exec.c:2155
static void pqPipelineProcessQueue(PGconn *conn)
Definition: fe-exec.c:2997
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:146
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1940
void pqSetResultError(PGresult *res, PQExpBuffer errorMessage)
Definition: fe-exec.c:665
void pqCommandQueueAdvance(PGconn *conn)
Definition: fe-exec.c:2976
PQExpBufferData errorMessage
Definition: libpq-int.h:571
PGEventProc proc
Definition: libpq-int.h:161
static void pqSaveWriteError(PGconn *conn)
Definition: fe-exec.c:777
int i
void * passThrough
Definition: libpq-int.h:163
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:765
PGEvent * events
Definition: libpq-int.h:188
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
char * name
Definition: libpq-int.h:162
ExecStatusType resultStatus
Definition: libpq-int.h:178
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQgetvalue()

char* PQgetvalue ( const PGresult res,
int  tup_num,
int  field_num 
)

Definition at line 3642 of file fe-exec.c.

References check_tuple_field_number(), pg_result::tuples, and pgresAttValue::value.

Referenced by _check_database_version(), add_tablespace_footer(), append_depends_on_extension(), appendQualifiedRelation(), BaseBackup(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_rel_oid(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), check_for_data_types_usage(), check_for_isn_and_int8_passing_mismatch(), check_for_tables_with_oids(), check_for_user_defined_encoding_conversions(), check_for_user_defined_postfix_ops(), check_is_install_user(), check_proper_datallowconn(), cluster_all_databases(), collectComments(), collectSecLabels(), compile_database_list(), compile_relation_list_one_db(), convertTSFunction(), createViewAsClause(), describeOneTableDetails(), describePublications(), describeRoles(), describeTableDetails(), do_field(), dropDBs(), dropRoles(), dropTablespaces(), dumpAgg(), dumpBaseType(), dumpBlobs(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpDomain(), dumpEnumType(), dumpForeignServer(), dumpFunc(), dumpGroups(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSearchPath(), dumpSequence(), dumpSequenceData(), dumpStatisticsExt(), dumpTable(), dumpTableData_insert(), dumpTableSchema(), dumpTablespaces(), dumpTSConfig(), dumpTSDictionary(), dumpUserConfig(), dumpUserMappings(), ecpg_get_data(), ecpg_is_type_an_array(), ecpg_set_compat_sqlda(), ecpg_set_native_sqlda(), ecpg_store_result(), emitShSecLabels(), ExecQueryTuples(), expand_dbname_patterns(), expand_extension_name_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), findLastBuiltinOid_V71(), get_create_object_cmd(), get_db_infos(), get_language_name(), get_loadable_libraries(), get_next_possible_free_pg_type_oid(), get_parallel_object_list(), get_rel_infos(), get_remote_estimate(), get_synchronized_snapshot(), get_tablespace_paths(), getAccessMethods(), getAggregates(), getBlobs(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPolicies(), getProcLangs(), getPublications(), getPublicationTables(), getRules(), getSubscriptions(), getTableAttrs(), GetTableInfo(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_identify_system(), libpqrcv_processTuples(), libpqrcv_readtimelinehistoryfile(), listExtensionContents(), listTSConfigsVerbose(), listTSParsersVerbose(), lo_initialize(), lookup_object_oid(), main(), make_tuple_from_result_row(), materializeResult(), new_9_0_populate_pg_largeobject_metadata(), old_9_6_invalidate_hash_indexes(), postgresAnalyzeForeignTable(), postgresImportForeignSchema(), PQconnectPoll(), PQdisplayTuples(), PQencryptPasswordConn(), PQprintTuples(), printCrosstab(), printQuery(), PrintResultsInCrosstab(), process_queued_fetch_requests(), process_result(), processExtensionTables(), readCommandResponse(), ReadEndOfStreamingResult(), ReceiveAndUnpackTarFile(), ReceiveTarFile(), ReceiveXlogStream(), reindex_all_databases(), report_extension_updates(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_simple_query(), RunIdentifySystem(), set_frozenxids(), show_binary_results(), sql_exec(), sqlda_common_total_size(), StoreQueryTuple(), storeRow(), test_pipeline_abort(), test_singlerowmode(), test_transaction(), try_complete_step(), vacuum_all_databases(), vacuum_one_database(), vacuumlo(), and verify_heap_slot_handler().

3643 {
3644  if (!check_tuple_field_number(res, tup_num, field_num))
3645  return NULL;
3646  return res->tuples[tup_num][field_num].value;
3647 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3292
PGresAttValue ** tuples
Definition: libpq-int.h:173
char * value
Definition: libpq-int.h:139

◆ pqInternalNotice()

void pqInternalNotice ( const PGNoticeHooks hooks,
const char *  fmt,
  ... 
)

Definition at line 839 of file fe-exec.c.

References generate_unaccent_rules::args, libpq_gettext, PGNoticeHooks::noticeRec, PG_DIAG_MESSAGE_PRIMARY, PG_DIAG_SEVERITY, PG_DIAG_SEVERITY_NONLOCALIZED, PGRES_NONFATAL_ERROR, PQclear(), PQmakeEmptyPGresult(), pqResultAlloc(), pqSaveMessageField(), sprintf, and vsnprintf.

Referenced by check_field_number(), check_param_number(), check_tuple_field_number(), PQcmdTuples(), pqEndcopy3(), pqGetInt(), pqParseInput3(), pqPutInt(), and PQsetvalue().

840 {
841  char msgBuf[1024];
842  va_list args;
843  PGresult *res;
844 
845  if (hooks->noticeRec == NULL)
846  return; /* nobody home to receive notice? */
847 
848  /* Format the message */
849  va_start(args, fmt);
850  vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
851  va_end(args);
852  msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
853 
854  /* Make a PGresult to pass to the notice receiver */
856  if (!res)
857  return;
858  res->noticeHooks = *hooks;
859 
860  /*
861  * Set up fields of notice.
862  */
866  /* XXX should provide a SQLSTATE too? */
867 
868  /*
869  * Result text is always just the primary message + newline. If we can't
870  * allocate it, substitute "out of memory", as in pqSetResultError.
871  */
872  res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, false);
873  if (res->errMsg)
874  sprintf(res->errMsg, "%s\n", msgBuf);
875  else
876  res->errMsg = libpq_gettext("out of memory\n");
877 
878  /*
879  * Pass to receiver, then free it.
880  */
881  res->noticeHooks.noticeRec(res->noticeHooks.noticeRecArg, res);
882  PQclear(res);
883 }
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:58
#define sprintf
Definition: port.h:218
#define vsnprintf
Definition: port.h:215
PQnoticeReceiver noticeRec
Definition: libpq-int.h:153
#define PG_DIAG_SEVERITY
Definition: postgres_ext.h:55
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:146
void pqSaveMessageField(PGresult *res, char code, const char *value)
Definition: fe-exec.c:961
#define PG_DIAG_SEVERITY_NONLOCALIZED
Definition: postgres_ext.h:56
void PQclear(PGresult *res)
Definition: fe-exec.c:694
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:539
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQisBusy()

int PQisBusy ( PGconn conn)

Definition at line 1951 of file fe-exec.c.

References pg_conn::asyncStatus, parseInput(), PGASYNC_BUSY, and pg_conn::write_failed.

Referenced by advanceConnectionState(), dblink_is_busy(), libpqrcv_PQgetResult(), pgfdw_get_cleanup_result(), pgfdw_get_result(), PQconnectPoll(), pqEndcopy3(), test_disallowed_in_pipeline(), test_pipelined_insert(), test_uniqviol(), try_complete_step(), and wait_on_slots().

1952 {
1953  if (!conn)
1954  return false;
1955 
1956  /* Parse any available data, if our state permits. */
1957  parseInput(conn);
1958 
1959  /*
1960  * PQgetResult will return immediately in all states except BUSY, or if we
1961  * had a write failure.
1962  */
1963  return conn->asyncStatus == PGASYNC_BUSY || conn->write_failed;
1964 }
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
bool write_failed
Definition: libpq-int.h:454
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1940

◆ PQisnonblocking()

int PQisnonblocking ( const PGconn conn)

Definition at line 3747 of file fe-exec.c.

References pqIsnonblocking.

Referenced by test_disallowed_in_pipeline(), and test_simple_pipeline().

3748 {
3749  return pqIsnonblocking(conn);
3750 }
#define pqIsnonblocking(conn)
Definition: libpq-int.h:830

◆ PQisthreadsafe()

int PQisthreadsafe ( void  )

Definition at line 3754 of file fe-exec.c.

3755 {
3756 #ifdef ENABLE_THREAD_SAFETY
3757  return true;
3758 #else
3759  return false;
3760 #endif
3761 }

◆ PQmakeEmptyPGresult()

PGresult* PQmakeEmptyPGresult ( PGconn conn,
ExecStatusType  status 
)

Definition at line 146 of file fe-exec.c.

References pg_result::attDescs, pg_result::binary, pg_result::client_encoding, pg_conn::client_encoding, pg_result::cmdStatus, pg_result::curBlock, pg_result::curOffset, dupEvents(), pg_result::errFields, pg_result::errMsg, pg_conn::errorMessage, pg_result::errQuery, pg_result::events, pg_conn::events, malloc, pg_result::memorySize, pg_result::nEvents, pg_conn::nEvents, pg_result::noticeHooks, pg_conn::noticeHooks, PGNoticeHooks::noticeProc, PGNoticeHooks::noticeProcArg, PGNoticeHooks::noticeRec, PGNoticeHooks::noticeRecArg, pg_result::ntups, pg_result::null_field, pg_result::numAttributes, pg_result::numParameters, pg_result::paramDescs, PG_SQL_ASCII, PGRES_COMMAND_OK, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_EMPTY_QUERY, PGRES_SINGLE_TUPLE, PGRES_TUPLES_OK, PQclear(), pqSetResultError(), pg_result::resultStatus, pg_result::spaceLeft, status(), pg_result::tupArrSize, and pg_result::tuples.

Referenced by ECPGallocate_desc(), getCopyResult(), getCopyStart(), getParamDescriptions(), getRowDescriptions(), PQcopyResult(), pqFunctionCall3(), pqGetErrorNotice3(), PQgetResult(), pqInternalNotice(), pqParseInput3(), pqPipelineProcessQueue(), pqPrepareAsyncResult(), and pqSaveErrorResult().

147 {
148  PGresult *result;
149 
150  result = (PGresult *) malloc(sizeof(PGresult));
151  if (!result)
152  return NULL;
153 
154  result->ntups = 0;
155  result->numAttributes = 0;
156  result->attDescs = NULL;
157  result->tuples = NULL;
158  result->tupArrSize = 0;
159  result->numParameters = 0;
160  result->paramDescs = NULL;
161  result->resultStatus = status;
162  result->cmdStatus[0] = '\0';
163  result->binary = 0;
164  result->events = NULL;
165  result->nEvents = 0;
166  result->errMsg = NULL;
167  result->errFields = NULL;
168  result->errQuery = NULL;
169  result->null_field[0] = '\0';
170  result->curBlock = NULL;
171  result->curOffset = 0;
172  result->spaceLeft = 0;
173  result->memorySize = sizeof(PGresult);
174 
175  if (conn)
176  {
177  /* copy connection data we might need for operations on PGresult */
178  result->noticeHooks = conn->noticeHooks;
179  result->client_encoding = conn->client_encoding;
180 
181  /* consider copying conn's errorMessage */
182  switch (status)
183  {
184  case PGRES_EMPTY_QUERY:
185  case PGRES_COMMAND_OK:
186  case PGRES_TUPLES_OK:
187  case PGRES_COPY_OUT:
188  case PGRES_COPY_IN:
189  case PGRES_COPY_BOTH:
190  case PGRES_SINGLE_TUPLE:
191  /* non-error cases */
192  break;
193  default:
194  pqSetResultError(result, &conn->errorMessage);
195  break;
196  }
197 
198  /* copy events last; result must be valid if we need to PQclear */
199  if (conn->nEvents > 0)
200  {
201  result->events = dupEvents(conn->events, conn->nEvents,
202  &result->memorySize);
203  if (!result->events)
204  {
205  PQclear(result);
206  return NULL;
207  }
208  result->nEvents = conn->nEvents;
209  }
210  }
211  else
212  {
213  /* defaults... */
214  result->noticeHooks.noticeRec = NULL;
215  result->noticeHooks.noticeRecArg = NULL;
216  result->noticeHooks.noticeProc = NULL;
217  result->noticeHooks.noticeProcArg = NULL;
218  result->client_encoding = PG_SQL_ASCII;
219  }
220 
221  return result;
222 }
size_t memorySize
Definition: libpq-int.h:213
PGMessageField * errFields
Definition: libpq-int.h:198
PGEvent * events
Definition: libpq-int.h:405
int tupArrSize
Definition: libpq-int.h:175
int spaceLeft
Definition: libpq-int.h:211
int nEvents
Definition: libpq-int.h:189
char * errMsg
Definition: libpq-int.h:197
char null_field[1]
Definition: libpq-int.h:202
PGresAttDesc * attDescs
Definition: libpq-int.h:172
PGresAttValue ** tuples
Definition: libpq-int.h:173
#define malloc(a)
Definition: header.h:50
struct pg_result PGresult
Definition: libpq-fe.h:171
PGNoticeHooks noticeHooks
Definition: libpq-int.h:187
PGNoticeHooks noticeHooks
Definition: libpq-int.h:402
int curOffset
Definition: libpq-int.h:210
void * noticeProcArg
Definition: libpq-int.h:156
PQnoticeReceiver noticeRec
Definition: libpq-int.h:153
PGresult_data * curBlock
Definition: libpq-int.h:209
int numParameters
Definition: libpq-int.h:176
int binary
Definition: libpq-int.h:180
void pqSetResultError(PGresult *res, PQExpBuffer errorMessage)
Definition: fe-exec.c:665
char * errQuery
Definition: libpq-int.h:199
int numAttributes
Definition: libpq-int.h:171
PQnoticeProcessor noticeProc
Definition: libpq-int.h:155
PQExpBufferData errorMessage
Definition: libpq-int.h:571
void PQclear(PGresult *res)
Definition: fe-exec.c:694
PGresParamDesc * paramDescs
Definition: libpq-int.h:177
int ntups
Definition: libpq-int.h:170
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:179
int nEvents
Definition: libpq-int.h:406
int client_encoding
Definition: libpq-int.h:470
static PGEvent * dupEvents(PGEvent *events, int count, size_t *memSize)
Definition: fe-exec.c:392
PGEvent * events
Definition: libpq-int.h:188
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
ExecStatusType resultStatus
Definition: libpq-int.h:178
void * noticeRecArg
Definition: libpq-int.h:154
int client_encoding
Definition: libpq-int.h:190

◆ PQnfields()

◆ PQnotifies()

PGnotify* PQnotifies ( PGconn conn)

Definition at line 2516 of file fe-exec.c.

References pgNotify::next, pg_conn::notifyHead, pg_conn::notifyTail, and parseInput().

Referenced by dblink_get_notify(), ecpg_process_output(), main(), PrintNotifications(), and try_complete_step().

2517 {
2518  PGnotify *event;
2519 
2520  if (!conn)
2521  return NULL;
2522 
2523  /* Parse any available data to see if we can extract NOTIFY messages. */
2524  parseInput(conn);
2525 
2526  event = conn->notifyHead;
2527  if (event)
2528  {
2529  conn->notifyHead = event->next;
2530  if (!conn->notifyHead)
2531  conn->notifyTail = NULL;
2532  event->next = NULL; /* don't let app see the internal state */
2533  }
2534  return event;
2535 }
PGnotify * notifyHead
Definition: libpq-int.h:421
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1940
struct pgNotify * next
Definition: libpq-fe.h:191
PGnotify * notifyTail
Definition: libpq-int.h:422

◆ PQnparams()

int PQnparams ( const PGresult res)

Definition at line 3681 of file fe-exec.c.

References pg_result::numParameters.

3682 {
3683  if (!res)
3684  return 0;
3685  return res->numParameters;
3686 }
int numParameters
Definition: libpq-int.h:176

◆ PQntuples()

int PQntuples ( const PGresult res)

Definition at line 3248 of file fe-exec.c.

References pg_result::ntups.

Referenced by add_tablespace_footer(), append_depends_on_extension(), appendQualifiedRelation(), BaseBackup(), buildMatViewRefreshDependencies(), check_for_data_types_usage(), check_for_isn_and_int8_passing_mismatch(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_for_tables_with_oids(), check_for_user_defined_encoding_conversions(), check_for_user_defined_postfix_ops(), check_is_install_user(), check_proper_datallowconn(), cluster_all_databases(), collectComments(), collectSecLabels(), compile_database_list(), compile_relation_list_one_db(), CreateReplicationSlot(), createViewAsClause(), describeOneTableDetails(), describePublications(), describeRoles(), describeTableDetails(), dropDBs(), DropReplicationSlot(), dropRoles(), dropTablespaces(), dumpBlobs(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpDatabaseConfig(), dumpDatabases(), dumpEnumType(), dumpGroups(), dumpOpclass(), dumpOpfamily(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSequence(), dumpSequenceData(), dumpTable(), dumpTableData_insert(), dumpTablespaces(), dumpTSConfig(), dumpUserConfig(), dumpUserMappings(), ecpg_is_type_an_array(), ecpg_process_output(), ecpg_store_result(), ECPGget_desc(), emitShSecLabels(), ExecQueryTuples(), ExecQueryUsingCursor(), execute_dml_stmt(), execute_foreign_modify(), ExecuteSqlQueryForSingleRow(), expand_dbname_patterns(), expand_extension_name_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), fetch_more_data(), get_create_object_cmd(), get_db_infos(), get_loadable_libraries(), get_parallel_object_list(), get_rel_infos(), get_tablespace_paths(), getAccessMethods(), getAggregates(), getBlobs(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getIndexes(), getInherits(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPolicies(), getProcLangs(), getPublications(), getPublicationTables(), getRules(), getSubscriptions(), getTableAttrs(), GetTableInfo(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_endstreaming(), libpqrcv_identify_system(), libpqrcv_processTuples(), libpqrcv_readtimelinehistoryfile(), listDbRoleSettings(), listExtensionContents(), listTables(), listTSConfigsVerbose(), listTSParsersVerbose(), lo_initialize(), lookup_object_oid(), main(), make_tuple_from_result_row(), materializeResult(), old_9_6_invalidate_hash_indexes(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresImportForeignSchema(), PQconnectPoll(), PQdisplayTuples(), PQencryptPasswordConn(), PQprint(), PQprintTuples(), printCrosstab(), printQuery(), PrintResultsInCrosstab(), process_queued_fetch_requests(), processExtensionTables(), readCommandResponse(), ReadEndOfStreamingResult(), ReceiveXlogStream(), reindex_all_databases(), report_extension_updates(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_simple_query(), RunIdentifySystem(), set_frozenxids(), show_binary_results(), sql_exec(), StoreQueryTuple(), storeRow(), test_pipeline_abort(), test_singlerowmode(), test_transaction(), try_complete_step(), vacuum_all_databases(), vacuum_one_database(), vacuumlo(), verify_btree_slot_handler(), and verify_heap_slot_handler().

3249 {
3250  if (!res)
3251  return 0;
3252  return res->ntups;
3253 }
int ntups
Definition: libpq-int.h:170

◆ PQoidStatus()

char* PQoidStatus ( const PGresult res)

Definition at line 3532 of file fe-exec.c.

References buf, and pg_result::cmdStatus.

3533 {
3534  /*
3535  * This must be enough to hold the result. Don't laugh, this is better
3536  * than what this function used to do.
3537  */
3538  static char buf[24];
3539 
3540  size_t len;
3541 
3542  if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
3543  return "";
3544 
3545  len = strspn(res->cmdStatus + 7, "0123456789");
3546  if (len > sizeof(buf) - 1)
3547  len = sizeof(buf) - 1;
3548  memcpy(buf, res->cmdStatus + 7, len);
3549  buf[len] = '\0';
3550 
3551  return buf;
3552 }
static char * buf
Definition: pg_test_fsync.c:68
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:179

◆ PQoidValue()

Oid PQoidValue ( const PGresult res)

Definition at line 3560 of file fe-exec.c.

References pg_result::cmdStatus, and InvalidOid.

Referenced by ecpg_process_output(), and PrintQueryStatus().

3561 {
3562  char *endptr = NULL;
3563  unsigned long result;
3564 
3565  if (!res ||
3566  strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
3567  res->cmdStatus[7] < '0' ||
3568  res->cmdStatus[7] > '9')
3569  return InvalidOid;
3570 
3571  result = strtoul(res->cmdStatus + 7, &endptr, 10);
3572 
3573  if (!endptr || (*endptr != ' ' && *endptr != '\0'))
3574  return InvalidOid;
3575  else
3576  return (Oid) result;
3577 }
unsigned int Oid
Definition: postgres_ext.h:31
#define InvalidOid
Definition: postgres_ext.h:36
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:179

◆ PQparamtype()

Oid PQparamtype ( const PGresult res,
int  param_num 
)

Definition at line 3692 of file fe-exec.c.

References check_param_number(), InvalidOid, pg_result::paramDescs, and pgresParamDesc::typid.

3693 {
3694  if (!check_param_number(res, param_num))
3695  return InvalidOid;
3696  if (res->paramDescs)
3697  return res->paramDescs[param_num].typid;
3698  else
3699  return InvalidOid;
3700 }
static int check_param_number(const PGresult *res, int param_num)
Definition: fe-exec.c:3315
#define InvalidOid
Definition: postgres_ext.h:36
PGresParamDesc * paramDescs
Definition: libpq-int.h:177

◆ pqPipelineFlush()

static int pqPipelineFlush ( PGconn conn)
static

Definition at line 3780 of file fe-exec.c.

References OUTBUFFER_THRESHOLD, pg_conn::outCount, pg_conn::pipelineStatus, PQ_PIPELINE_ON, and pqFlush().

Referenced by PQsendDescribe(), PQsendPrepare(), PQsendQueryGuts(), and PQsendQueryInternal().

3781 {
3782  if ((conn->pipelineStatus != PQ_PIPELINE_ON) ||
3783  (conn->outCount >= OUTBUFFER_THRESHOLD))
3784  return pqFlush(conn);
3785  return 0;
3786 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:965
int outCount
Definition: libpq-int.h:488
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:417
#define OUTBUFFER_THRESHOLD
Definition: libpq-int.h:835

◆ pqPipelineProcessQueue()

static void pqPipelineProcessQueue ( PGconn conn)
static

Definition at line 2997 of file fe-exec.c.

References appendPQExpBufferStr(), pg_conn::asyncStatus, pg_conn::cmd_queue_head, pg_conn::errorMessage, libpq_gettext, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_READY, PGASYNC_READY_MORE, PGQUERY_SYNC, PGRES_PIPELINE_ABORTED, pg_conn::pipelineStatus, PQ_PIPELINE_ABORTED, PQ_PIPELINE_OFF, pqClearAsyncResult(), PQmakeEmptyPGresult(), pqSaveErrorResult(), PGcmdQueueEntry::queryclass, pg_conn::result, and pg_conn::singleRowMode.

Referenced by pqAppendCmdQueueEntry(), and PQgetResult().

2998 {
2999  switch (conn->asyncStatus)
3000  {
3001  case PGASYNC_COPY_IN:
3002  case PGASYNC_COPY_OUT:
3003  case PGASYNC_COPY_BOTH:
3004  case PGASYNC_READY:
3005  case PGASYNC_READY_MORE:
3006  case PGASYNC_BUSY:
3007  /* client still has to process current query or results */
3008  return;
3009  case PGASYNC_IDLE:
3010  /* next query please */
3011  break;
3012  }
3013 
3014  /* Nothing to do if not in pipeline mode, or queue is empty */
3015  if (conn->pipelineStatus == PQ_PIPELINE_OFF ||
3016  conn->cmd_queue_head == NULL)
3017  return;
3018 
3019  /* Initialize async result-accumulation state */
3020  pqClearAsyncResult(conn);
3021 
3022  /*
3023  * Reset single-row processing mode. (Client has to set it up for each
3024  * query, if desired.)
3025  */
3026  conn->singleRowMode = false;
3027 
3028  if (conn->pipelineStatus == PQ_PIPELINE_ABORTED &&
3030  {
3031  /*
3032  * In an aborted pipeline we don't get anything from the server for
3033  * each result; we're just discarding commands from the queue until we
3034  * get to the next sync from the server.
3035  *
3036  * The PGRES_PIPELINE_ABORTED results tell the client that its queries
3037  * got aborted.
3038  */
3040  if (!conn->result)
3041  {
3043  libpq_gettext("out of memory\n"));
3044  pqSaveErrorResult(conn);
3045  return;
3046  }
3047  conn->asyncStatus = PGASYNC_READY;
3048  }
3049  else
3050  {
3051  /* allow parsing to continue */
3052  conn->asyncStatus = PGASYNC_BUSY;
3053  }
3054 }
bool singleRowMode
Definition: libpq-int.h:418
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:434
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:417
PGresult * result
Definition: libpq-int.h:500
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
PGQueryClass queryclass
Definition: libpq-int.h:322
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:146
PQExpBufferData errorMessage
Definition: libpq-int.h:571
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:749
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:765
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQpipelineSync()

int PQpipelineSync ( PGconn conn)

Definition at line 3077 of file fe-exec.c.

References appendPQExpBufferStr(), pg_conn::asyncStatus, pg_conn::errorMessage, libpq_gettext, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_READY, PGASYNC_READY_MORE, PGQUERY_SYNC, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqAllocCmdQueueEntry(), pqAppendCmdQueueEntry(), PQflush(), pqPutMsgEnd(), pqPutMsgStart(), pqRecycleCmdQueueEntry(), PGcmdQueueEntry::query, and PGcmdQueueEntry::queryclass.

Referenced by executeMetaCommand(), test_multi_pipelines(), test_pipeline_abort(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), and test_transaction().

3078 {
3079  PGcmdQueueEntry *entry;
3080 
3081  if (!conn)
3082  return 0;
3083 
3084  if (conn->pipelineStatus == PQ_PIPELINE_OFF)
3085  {
3087  libpq_gettext("cannot send pipeline when not in pipeline mode\n"));
3088  return 0;
3089  }
3090 
3091  switch (conn->asyncStatus)
3092  {
3093  case PGASYNC_COPY_IN:
3094  case PGASYNC_COPY_OUT:
3095  case PGASYNC_COPY_BOTH:
3096  /* should be unreachable */
3098  "internal error: cannot send pipeline while in COPY\n");
3099  return 0;
3100  case PGASYNC_READY:
3101  case PGASYNC_READY_MORE:
3102  case PGASYNC_BUSY:
3103  case PGASYNC_IDLE:
3104  /* OK to send sync */
3105  break;
3106  }
3107 
3108  entry = pqAllocCmdQueueEntry(conn);
3109  if (entry == NULL)
3110  return 0; /* error msg already set */
3111 
3112  entry->queryclass = PGQUERY_SYNC;
3113  entry->query = NULL;
3114 
3115  /* construct the Sync message */
3116  if (pqPutMsgStart('S', conn) < 0 ||
3117  pqPutMsgEnd(conn) < 0)
3118  goto sendFailed;
3119 
3120  /*
3121  * Give the data a push. In nonblock mode, don't complain if we're unable
3122  * to send it all; PQgetResult() will do any additional flushing needed.
3123  */
3124  if (PQflush(conn) < 0)
3125  goto sendFailed;
3126 
3127  /* OK, it's launched! */
3128  pqAppendCmdQueueEntry(conn, entry);
3129 
3130  return 1;
3131 
3132 sendFailed:
3133  pqRecycleCmdQueueEntry(conn, entry);
3134  /* error message should be set up already */
3135  return 0;
3136 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:417
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1296
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
PGQueryClass queryclass
Definition: libpq-int.h:322
int PQflush(PGconn *conn)
Definition: fe-exec.c:3766
PQExpBufferData errorMessage
Definition: libpq-int.h:571
static void pqAppendCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1247
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
static PGcmdQueueEntry * pqAllocCmdQueueEntry(PGconn *conn)
Definition: fe-exec.c:1213
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQprepare()

PGresult* PQprepare ( PGconn conn,
const char *  stmtName,
const char *  query,
int  nParams,
const Oid paramTypes 
)

Definition at line 2237 of file fe-exec.c.

References PQexecFinish(), PQexecStart(), and PQsendPrepare().

Referenced by DescribeQuery(), init_libpq_conn(), main(), prepare_common(), sendCommand(), and test_uniqviol().

2240 {
2241  if (!PQexecStart(conn))
2242  return NULL;
2243  if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
2244  return NULL;
2245  return PQexecFinish(conn);
2246 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2340
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2275
int PQsendPrepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:1484

◆ pqPrepareAsyncResult()

PGresult* pqPrepareAsyncResult ( PGconn conn)

Definition at line 804 of file fe-exec.c.

References pg_conn::next_result, PGRES_FATAL_ERROR, PQmakeEmptyPGresult(), and pg_conn::result.

Referenced by getCopyResult(), pqFunctionCall3(), and PQgetResult().

805 {
806  PGresult *res;
807 
808  /*
809  * conn->result is the PGresult to return. If it is NULL (which probably
810  * shouldn't happen) we assume there is an appropriate error message in
811  * conn->errorMessage.
812  */
813  res = conn->result;
814  if (!res)
816 
817  /*
818  * Replace conn->result with next_result, if any. In the normal case
819  * there isn't a next result and we're just dropping ownership of the
820  * current result. In single-row mode this restores the situation to what
821  * it was before we created the current single-row result.
822  */
823  conn->result = conn->next_result;
824  conn->next_result = NULL;
825 
826  return res;
827 }
PGresult * result
Definition: libpq-int.h:500
PGresult * next_result
Definition: libpq-int.h:501
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:146

◆ PQputCopyData()

int PQputCopyData ( PGconn conn,
const char *  buffer,
int  nbytes 
)

Definition at line 2544 of file fe-exec.c.

References appendPQExpBufferStr(), pg_conn::asyncStatus, pg_conn::errorMessage, libpq_gettext, pg_conn::outBufSize, pg_conn::outCount, parseInput(), PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, pqCheckOutBufferSpace(), pqFlush(), pqIsnonblocking, pqPutMsgEnd(), pqPutMsgStart(), and pqPutnchar().

Referenced by ExecuteSqlCommandBuf(), handleCopyIn(), libpqrcv_send(), PQputnbytes(), and sendFeedback().

2545 {
2546  if (!conn)
2547  return -1;
2548  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2549  conn->asyncStatus != PGASYNC_COPY_BOTH)
2550  {
2552  libpq_gettext("no COPY in progress\n"));
2553  return -1;
2554  }
2555 
2556  /*
2557  * Process any NOTICE or NOTIFY messages that might be pending in the
2558  * input buffer. Since the server might generate many notices during the
2559  * COPY, we want to clean those out reasonably promptly to prevent
2560  * indefinite expansion of the input buffer. (Note: the actual read of
2561  * input data into the input buffer happens down inside pqSendSome, but
2562  * it's not authorized to get rid of the data again.)
2563  */
2564  parseInput(conn);
2565 
2566  if (nbytes > 0)
2567  {
2568  /*
2569  * Try to flush any previously sent data in preference to growing the
2570  * output buffer. If we can't enlarge the buffer enough to hold the
2571  * data, return 0 in the nonblock case, else hard error. (For
2572  * simplicity, always assume 5 bytes of overhead.)
2573  */
2574  if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2575  {
2576  if (pqFlush(conn) < 0)
2577  return -1;
2578  if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2579  conn))
2580  return pqIsnonblocking(conn) ? 0 : -1;
2581  }
2582  /* Send the data (too simple to delegate to fe-protocol files) */
2583  if (pqPutMsgStart('d', conn) < 0 ||
2584  pqPutnchar(buffer, nbytes, conn) < 0 ||
2585  pqPutMsgEnd(conn) < 0)
2586  return -1;
2587  }
2588  return 1;
2589 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:965
int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:290
#define pqIsnonblocking(conn)
Definition: libpq-int.h:830
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
int outCount
Definition: libpq-int.h:488
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1940
PQExpBufferData errorMessage
Definition: libpq-int.h:571
int outBufSize
Definition: libpq-int.h:487
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:205
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQputCopyEnd()

int PQputCopyEnd ( PGconn conn,
const char *  errormsg 
)

Definition at line 2600 of file fe-exec.c.

References appendPQExpBufferStr(), pg_conn::asyncStatus, pg_conn::cmd_queue_head, pg_conn::errorMessage, libpq_gettext, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGQUERY_SIMPLE, pqFlush(), pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), and PGcmdQueueEntry::queryclass.

Referenced by CheckCopyStreamStop(), EndDBCopyMode(), handleCopyIn(), HandleEndOfCopyStream(), libpqrcv_endstreaming(), PQexecStart(), prepareToTerminate(), and ProcessXLogDataMsg().

2601 {
2602  if (!conn)
2603  return -1;
2604  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2605  conn->asyncStatus != PGASYNC_COPY_BOTH)
2606  {
2608  libpq_gettext("no COPY in progress\n"));
2609  return -1;
2610  }
2611 
2612  /*
2613  * Send the COPY END indicator. This is simple enough that we don't
2614  * bother delegating it to the fe-protocol files.
2615  */
2616  if (errormsg)
2617  {
2618  /* Send COPY FAIL */
2619  if (pqPutMsgStart('f', conn) < 0 ||
2620  pqPuts(errormsg, conn) < 0 ||
2621  pqPutMsgEnd(conn) < 0)
2622  return -1;
2623  }
2624  else
2625  {
2626  /* Send COPY DONE */
2627  if (pqPutMsgStart('c', conn) < 0 ||
2628  pqPutMsgEnd(conn) < 0)
2629  return -1;
2630  }
2631 
2632  /*
2633  * If we sent the COPY command in extended-query mode, we must issue a
2634  * Sync as well.
2635  */
2636  if (conn->cmd_queue_head &&
2638  {
2639  if (pqPutMsgStart('S', conn) < 0 ||
2640  pqPutMsgEnd(conn) < 0)
2641  return -1;
2642  }
2643 
2644  /* Return to active duty */
2645  if (conn->asyncStatus == PGASYNC_COPY_BOTH)
2646  conn->asyncStatus = PGASYNC_COPY_OUT;
2647  else
2648  conn->asyncStatus = PGASYNC_BUSY;
2649 
2650  /* Try to flush data */
2651  if (pqFlush(conn) < 0)
2652  return -1;
2653 
2654  return 1;
2655 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:965
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:434
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
PGQueryClass queryclass
Definition: libpq-int.h:322
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:155
PQExpBufferData errorMessage
Definition: libpq-int.h:571
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQputline()

int PQputline ( PGconn conn,
const char *  s 
)

Definition at line 2771 of file fe-exec.c.

References PQputnbytes().

Referenced by initGenerateDataClientSide().

2772 {
2773  return PQputnbytes(conn, s, strlen(s));
2774 }
int PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2781

◆ PQputnbytes()

int PQputnbytes ( PGconn conn,
const char *  buffer,
int  nbytes 
)

Definition at line 2781 of file fe-exec.c.

References PQputCopyData().

Referenced by PQputline().

2782 {
2783  if (PQputCopyData(conn, buffer, nbytes) > 0)
2784  return 0;
2785  else
2786  return EOF;
2787 }
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2544

◆ pqRecycleCmdQueueEntry()

static void pqRecycleCmdQueueEntry ( PGconn conn,
PGcmdQueueEntry entry 
)
static

Definition at line 1296 of file fe-exec.c.

References Assert, pg_conn::cmd_queue_recycle, free, PGcmdQueueEntry::next, and PGcmdQueueEntry::query.

Referenced by pqCommandQueueAdvance(), PQpipelineSync(), PQsendDescribe(), PQsendPrepare(), PQsendQueryGuts(), and PQsendQueryInternal().

1297 {
1298  if (entry == NULL)
1299  return;
1300 
1301  /* recyclable entries should not have a follow-on command */
1302  Assert(entry->next == NULL);
1303 
1304  if (entry->query)
1305  {
1306  free(entry->query);
1307  entry->query = NULL;
1308  }
1309 
1310  entry->next = conn->cmd_queue_recycle;
1311  conn->cmd_queue_recycle = entry;
1312 }
struct PGcmdQueueEntry * next
Definition: libpq-int.h:324
#define free(a)
Definition: header.h:65
#define Assert(condition)
Definition: c.h:804
PGcmdQueueEntry * cmd_queue_recycle
Definition: libpq-int.h:441

◆ PQresStatus()

char* PQresStatus ( ExecStatusType  status)

Definition at line 3186 of file fe-exec.c.

References lengthof, libpq_gettext, pgresStatus, and status().

Referenced by process_result(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), and try_complete_step().

3187 {
3188  if ((unsigned int) status >= lengthof(pgresStatus))
3189  return libpq_gettext("invalid ExecStatusType code");
3190  return pgresStatus[status];
3191 }
#define lengthof(array)
Definition: c.h:734
char *const pgresStatus[]
Definition: fe-exec.c:32
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQresultAlloc()

void* PQresultAlloc ( PGresult res,
size_t  nBytes 
)

Definition at line 523 of file fe-exec.c.

References pqResultAlloc().

Referenced by PQsetResultAttrs().

524 {
525  return pqResultAlloc(res, nBytes, true);
526 }
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:539

◆ pqResultAlloc()

void* pqResultAlloc ( PGresult res,
size_t  nBytes,
bool  isBinary 
)

Definition at line 539 of file fe-exec.c.

References pg_result::curBlock, pg_result::curOffset, malloc, pg_result::memorySize, pgresult_data::next, pg_result::null_field, PGRESULT_ALIGN_BOUNDARY, PGRESULT_BLOCK_OVERHEAD, PGRESULT_DATA_BLOCKSIZE, PGRESULT_SEP_ALLOC_THRESHOLD, pgresult_data::space, and pg_result::spaceLeft.

Referenced by getCopyStart(), getParamDescriptions(), getRowDescriptions(), pqInternalNotice(), PQresultAlloc(), pqResultStrdup(), pqRowProcessor(), pqSaveMessageField(), and PQsetvalue().

540 {
541  char *space;
542  PGresult_data *block;
543 
544  if (!res)
545  return NULL;
546 
547  if (nBytes <= 0)
548  return res->null_field;
549 
550  /*
551  * If alignment is needed, round up the current position to an alignment
552  * boundary.
553  */
554  if (isBinary)
555  {
556  int offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
557 
558  if (offset)
559  {
560  res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
561  res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
562  }
563  }
564 
565  /* If there's enough space in the current block, no problem. */
566  if (nBytes <= (size_t) res->spaceLeft)
567  {
568  space = res->curBlock->space + res->curOffset;
569  res->curOffset += nBytes;
570  res->spaceLeft -= nBytes;
571  return space;
572  }
573 
574  /*
575  * If the requested object is very large, give it its own block; this
576  * avoids wasting what might be most of the current block to start a new
577  * block. (We'd have to special-case requests bigger than the block size
578  * anyway.) The object is always given binary alignment in this case.
579  */
580  if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
581  {
582  size_t alloc_size = nBytes + PGRESULT_BLOCK_OVERHEAD;
583 
584  block = (PGresult_data *) malloc(alloc_size);
585  if (!block)
586  return NULL;
587  res->memorySize += alloc_size;
588  space = block->space + PGRESULT_BLOCK_OVERHEAD;
589  if (res->curBlock)
590  {
591  /*
592  * Tuck special block below the active block, so that we don't
593  * have to waste the free space in the active block.
594  */
595  block->next = res->curBlock->next;
596  res->curBlock->next = block;
597  }
598  else
599  {
600  /* Must set up the new block as the first active block. */
601  block->next = NULL;
602  res->curBlock = block;
603  res->spaceLeft = 0; /* be sure it's marked full */
604  }
605  return space;
606  }
607 
608  /* Otherwise, start a new block. */
610  if (!block)
611  return NULL;
613  block->next = res->curBlock;
614  res->curBlock = block;
615  if (isBinary)
616  {
617  /* object needs full alignment */
620  }
621  else
622  {
623  /* we can cram it right after the overhead pointer */
624  res->curOffset = sizeof(PGresult_data);
626  }
627 
628  space = block->space + res->curOffset;
629  res->curOffset += nBytes;
630  res->spaceLeft -= nBytes;
631  return space;
632 }
size_t memorySize
Definition: libpq-int.h:213
char space[1]
Definition: libpq-int.h:107
PGresult_data * next
Definition: libpq-int.h:106
union pgresult_data PGresult_data
Definition: libpq-int.h:102
int spaceLeft
Definition: libpq-int.h:211
char null_field[1]
Definition: libpq-int.h:202
#define malloc(a)
Definition: header.h:50
#define PGRESULT_ALIGN_BOUNDARY
Definition: fe-exec.c:134
int curOffset
Definition: libpq-int.h:210
#define PGRESULT_BLOCK_OVERHEAD
Definition: fe-exec.c:135
PGresult_data * curBlock
Definition: libpq-int.h:209
#define PGRESULT_SEP_ALLOC_THRESHOLD
Definition: fe-exec.c:136
#define PGRESULT_DATA_BLOCKSIZE
Definition: fe-exec.c:133

◆ PQresultErrorField()

char* PQresultErrorField ( const PGresult res,
int  fieldcode 
)

Definition at line 3233 of file fe-exec.c.

References pgMessageField::code, pgMessageField::contents, pg_result::errFields, and pgMessageField::next.

Referenced by BaseBackup(), CreateReplicationSlot(), dblink_res_error(), ecpg_raise_backend(), ECPGnoticeReceiver(), GetTableInfo(), libpqrcv_exec(), minimal_error_message(), pgfdw_report_error(), pgpassfileWarning(), pqBuildErrorMessage3(), PQconnectPoll(), SetResultVariables(), should_processing_continue(), TableCommandResultHandler(), test_pipeline_abort(), and try_complete_step().

3234 {
3235  PGMessageField *pfield;
3236 
3237  if (!res)
3238  return NULL;
3239  for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
3240  {
3241  if (pfield->code == fieldcode)
3242  return pfield->contents;
3243  }
3244  return NULL;
3245 }
PGMessageField * errFields
Definition: libpq-int.h:198
struct pgMessageField * next
Definition: libpq-int.h:145
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:147

◆ PQresultErrorMessage()

char* PQresultErrorMessage ( const PGresult res)

◆ PQresultMemorySize()

size_t PQresultMemorySize ( const PGresult res)

Definition at line 639 of file fe-exec.c.

References pg_result::memorySize.

640 {
641  if (!res)
642  return 0;
643  return res->memorySize;
644 }
size_t memorySize
Definition: libpq-int.h:213

◆ PQresultStatus()

ExecStatusType PQresultStatus ( const PGresult res)

Definition at line 3178 of file fe-exec.c.

References PGRES_FATAL_ERROR, and pg_result::resultStatus.

Referenced by _doSetSessionAuth(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), AcceptResult(), BaseBackup(), check_loadable_libraries(), check_prepare_conn(), ClearOrSaveResult(), close_cursor(), compile_database_list(), compile_relation_list_one_db(), create_cursor(), CreateReplicationSlot(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_record_internal(), deallocate_query(), DescribeQuery(), do_sql_command(), DropReplicationSlot(), dumpTableData_copy(), ecpg_check_PQresult(), ecpg_is_type_an_array(), ecpg_process_output(), EndDBCopyMode(), ExecQueryUsingCursor(), execute_dml_stmt(), execute_foreign_modify(), executeCommand(), executeMaintenanceCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlQuery(), ExecuteSqlStatement(), executeStatement(), fetch_more_data(), get_create_object_cmd(), get_remote_estimate(), GetConnection(), GetTableInfo(), handleCopyIn(), handleCopyOut(), HandleEndOfCopyStream(), init_libpq_conn(), initGenerateDataClientSide(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_connect(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_exec(), libpqrcv_identify_system(), libpqrcv_PQexec(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_startstreaming(), lo_close(), lo_creat(), lo_create(), lo_lseek(), lo_lseek64(), lo_open(), lo_read(), lo_tell(), lo_tell64(), lo_truncate(), lo_truncate64(), lo_unlink(), lo_write(), lockTableForWorker(), lookup_object_oid(), main(), materializeResult(), pgfdw_exec_cleanup_query(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresImportForeignSchema(), postgresReScanForeignScan(), PQconnectPoll(), PQencryptPasswordConn(), prepare_foreign_modify(), PrintQueryResults(), PrintResultsInCrosstab(), process_queued_fetch_requests(), process_result(), ProcessResult(), PSQLexecWatch(), readCommandResponse(), ReceiveCopyData(), ReceiveXlogStream(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_permutation(), run_simple_command(), run_simple_query(), RunIdentifySystem(), sendCommand(), SendQuery(), should_processing_continue(), sql_conn(), sql_exec(), storeQueryResult(), StreamLogicalLog(), TableCommandResultHandler(), test_disallowed_in_pipeline(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), test_uniqviol(), try_complete_step(), tryExecuteStatement(), vacuumlo(), verify_btree_slot_handler(), and verify_heap_slot_handler().

3179 {
3180  if (!res)
3181  return PGRES_FATAL_ERROR;
3182  return res->resultStatus;
3183 }
ExecStatusType resultStatus
Definition: libpq-int.h:178

◆ pqResultStrdup()

char* pqResultStrdup ( PGresult res,
const char *  str 
)

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

References pqResultAlloc().

Referenced by getRowDescriptions(), pqGetErrorNotice3(), PQsetResultAttrs(), and pqSetResultError().

652 {
653  char *space = (char *) pqResultAlloc(res, strlen(str) + 1, false);
654 
655  if (space)
656  strcpy(space, str);
657  return space;
658 }
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:539

◆ PQresultVerboseErrorMessage()

char* PQresultVerboseErrorMessage ( const PGresult res,
PGVerbosity  verbosity,
PGContextVisibility  show_context 
)

Definition at line 3202 of file fe-exec.c.

References PQExpBufferData::data, initPQExpBuffer(), libpq_gettext, PGRES_FATAL_ERROR, PGRES_NONFATAL_ERROR, pqBuildErrorMessage3(), PQExpBufferDataBroken, pg_result::resultStatus, and termPQExpBuffer().

Referenced by exec_command_errverbose().

3205 {
3206  PQExpBufferData workBuf;
3207 
3208  /*
3209  * Because the caller is expected to free the result string, we must
3210  * strdup any constant result. We use plain strdup and document that
3211  * callers should expect NULL if out-of-memory.
3212  */
3213  if (!res ||
3214  (res->resultStatus != PGRES_FATAL_ERROR &&
3216  return strdup(libpq_gettext("PGresult is not an error result\n"));
3217 
3218  initPQExpBuffer(&workBuf);
3219 
3220  pqBuildErrorMessage3(&workBuf, res, verbosity, show_context);
3221 
3222  /* If insufficient memory to format the message, fail cleanly */
3223  if (PQExpBufferDataBroken(workBuf))
3224  {
3225  termPQExpBuffer(&workBuf);
3226  return strdup(libpq_gettext("out of memory\n"));
3227  }
3228 
3229  return workBuf.data;
3230 }
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
ExecStatusType resultStatus
Definition: libpq-int.h:178
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ pqRowProcessor()

int pqRowProcessor ( PGconn conn,
const char **  errmsgp 
)

Definition at line 1107 of file fe-exec.c.

References pg_conn::asyncStatus, pg_result::attDescs, pgresAttDesc::format, i, pgresAttValue::len, pgDataValue::len, pg_conn::next_result, pg_result::null_field, NULL_LEN, pg_result::numAttributes, PG_COPYRES_ATTRS, PG_COPYRES_EVENTS, PG_COPYRES_NOTICEHOOKS, PGASYNC_READY_MORE, PGRES_SINGLE_TUPLE, pqAddTuple(), PQclear(), PQcopyResult(), pqResultAlloc(), pg_conn::result, pg_result::resultStatus, pg_conn::rowBuf, pg_conn::singleRowMode, val, pgresAttValue::value, and value.

Referenced by getAnotherTuple().

1108 {
1109  PGresult *res = conn->result;
1110  int nfields = res->numAttributes;
1111  const PGdataValue *columns = conn->rowBuf;
1112  PGresAttValue *tup;
1113  int i;
1114 
1115  /*
1116  * In single-row mode, make a new PGresult that will hold just this one
1117  * row; the original conn->result is left unchanged so that it can be used
1118  * again as the template for future rows.
1119  */
1120  if (conn->singleRowMode)
1121  {
1122  /* Copy everything that should be in the result at this point */
1123  res = PQcopyResult(res,
1126  if (!res)
1127  return 0;
1128  }
1129 
1130  /*
1131  * Basically we just allocate space in the PGresult for each field and
1132  * copy the data over.
1133  *
1134  * Note: on malloc failure, we return 0 leaving *errmsgp still NULL, which
1135  * caller will take to mean "out of memory". This is preferable to trying
1136  * to set up such a message here, because evidently there's not enough
1137  * memory for gettext() to do anything.
1138  */
1139  tup = (PGresAttValue *)
1140  pqResultAlloc(res, nfields * sizeof(PGresAttValue), true);
1141  if (tup == NULL)
1142  goto fail;
1143 
1144  for (i = 0; i < nfields; i++)
1145  {
1146  int clen = columns[i].len;
1147 
1148  if (clen < 0)
1149  {
1150  /* null field */
1151  tup[i].len = NULL_LEN;
1152  tup[i].value = res->null_field;
1153  }
1154  else
1155  {
1156  bool isbinary = (res->attDescs[i].format != 0);
1157  char *val;
1158 
1159  val = (char *) pqResultAlloc(res, clen + 1, isbinary);
1160  if (val == NULL)
1161  goto fail;
1162 
1163  /* copy and zero-terminate the data (even if it's binary) */
1164  memcpy(val, columns[i].value, clen);
1165  val[clen] = '\0';
1166 
1167  tup[i].len = clen;
1168  tup[i].value = val;
1169  }
1170  }
1171 
1172  /* And add the tuple to the PGresult's tuple array */
1173  if (!pqAddTuple(res, tup, errmsgp))
1174  goto fail;
1175 
1176  /*
1177  * Success. In single-row mode, make the result available to the client
1178  * immediately.
1179  */
1180  if (conn->singleRowMode)
1181  {
1182  /* Change result status to special single-row value */
1184  /* Stash old result for re-use later */
1185  conn->next_result = conn->result;
1186  conn->result = res;
1187  /* And mark the result ready to return */
1189  }
1190 
1191  return 1;
1192 
1193 fail:
1194  /* release locally allocated PGresult, if we made one */
1195  if (res != conn->result)
1196  PQclear(res);
1197  return 0;
1198 }
bool singleRowMode
Definition: libpq-int.h:418
PGresult * PQcopyResult(const PGresult *src, int flags)
Definition: fe-exec.c:299
#define NULL_LEN
Definition: libpq-int.h:134
char null_field[1]
Definition: libpq-int.h:202
PGresAttDesc * attDescs
Definition: libpq-int.h:172
PGresult * result
Definition: libpq-int.h:500
PGresult * next_result
Definition: libpq-int.h:501
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
#define PG_COPYRES_EVENTS
Definition: libpq-fe.h:45
static bool pqAddTuple(PGresult *res, PGresAttValue *tup, const char **errmsgp)
Definition: fe-exec.c:894
#define PG_COPYRES_NOTICEHOOKS
Definition: libpq-fe.h:46
PGdataValue * rowBuf
Definition: libpq-int.h:496
int numAttributes
Definition: libpq-int.h:171
#define PG_COPYRES_ATTRS
Definition: libpq-fe.h:43
static struct @143 value
void PQclear(PGresult *res)
Definition: fe-exec.c:694
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:539
int i
char * value
Definition: libpq-int.h:139
ExecStatusType resultStatus
Definition: libpq-int.h:178
long val
Definition: informix.c:664

◆ pqSaveErrorResult()

void pqSaveErrorResult ( PGconn conn)

Definition at line 765 of file fe-exec.c.

References PGRES_FATAL_ERROR, pqClearAsyncResult(), PQmakeEmptyPGresult(), and pg_conn::result.

Referenced by getAnotherTuple(), getCopyResult(), getParamDescriptions(), getRowDescriptions(), handleSyncLoss(), pqFunctionCall3(), PQgetResult(), pqParseInput3(), pqPipelineProcessQueue(), and pqSaveWriteError().

766 {
767  pqClearAsyncResult(conn);
769 }
PGresult * result
Definition: libpq-int.h:500
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:146
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:749

◆ pqSaveMessageField()

void pqSaveMessageField ( PGresult res,
char  code,
const char *  value 
)

Definition at line 961 of file fe-exec.c.

References pgMessageField::code, pgMessageField::contents, pg_result::errFields, pgMessageField::next, offsetof, and pqResultAlloc().

Referenced by pqGetErrorNotice3(), and pqInternalNotice().

962 {
963  PGMessageField *pfield;
964 
965  pfield = (PGMessageField *)
966  pqResultAlloc(res,
967  offsetof(PGMessageField, contents) +
968  strlen(value) + 1,
969  true);
970  if (!pfield)
971  return; /* out of memory? */
972  pfield->code = code;
973  strcpy(pfield->contents, value);
974  pfield->next = res->errFields;
975  res->errFields = pfield;
976 }
PGMessageField * errFields
Definition: libpq-int.h:198
struct pgMessageField * next
Definition: libpq-int.h:145
static struct @143 value
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:539
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:147
#define offsetof(type, field)
Definition: c.h:727

◆ pqSaveParameterStatus()

void pqSaveParameterStatus ( PGconn conn,
const char *  name,
const char *  value 
)

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

References pg_conn::client_encoding, pg_conn::default_transaction_read_only, free, pg_conn::in_hot_standby, malloc, pgParameterStatus::name, pgParameterStatus::next, PG_BOOL_NO, PG_BOOL_YES, pg_char_to_encoding(), PG_SQL_ASCII, pg_conn::pstatus, static_client_encoding, static_std_strings, pg_conn::std_strings, pg_conn::sversion, and pgParameterStatus::value.

Referenced by getParameterStatus().

983 {
984  pgParameterStatus *pstatus;
985  pgParameterStatus *prev;
986 
987  /*
988  * Forget any old information about the parameter
989  */
990  for (pstatus = conn->pstatus, prev = NULL;
991  pstatus != NULL;
992  prev = pstatus, pstatus = pstatus->next)
993  {
994  if (strcmp(pstatus->name, name) == 0)
995  {
996  if (prev)
997  prev->next = pstatus->next;
998  else
999  conn->pstatus = pstatus->next;
1000  free(pstatus); /* frees name and value strings too */
1001  break;
1002  }
1003  }
1004 
1005  /*
1006  * Store new info as a single malloc block
1007  */
1008  pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
1009  strlen(name) + strlen(value) + 2);
1010  if (pstatus)
1011  {
1012  char *ptr;
1013 
1014  ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
1015  pstatus->name = ptr;
1016  strcpy(ptr, name);
1017  ptr += strlen(name) + 1;
1018  pstatus->value = ptr;
1019  strcpy(ptr, value);
1020  pstatus->next = conn->pstatus;
1021  conn->pstatus = pstatus;
1022  }
1023 
1024  /*
1025  * Save values of settings that are of interest to libpq in fields of the
1026  * PGconn object. We keep client_encoding and standard_conforming_strings
1027  * in static variables as well, so that PQescapeString and PQescapeBytea
1028  * can behave somewhat sanely (at least in single-connection-using
1029  * programs).
1030  */
1031  if (strcmp(name, "client_encoding") == 0)
1032  {
1034  /* if we don't recognize the encoding name, fall back to SQL_ASCII */
1035  if (conn->client_encoding < 0)
1036  conn->client_encoding = PG_SQL_ASCII;
1038  }
1039  else if (strcmp(name, "standard_conforming_strings") == 0)
1040  {
1041  conn->std_strings = (strcmp(value, "on") == 0);
1043  }
1044  else if (strcmp(name, "server_version") == 0)
1045  {
1046  /* We convert the server version to numeric form. */
1047  int cnt;
1048  int vmaj,
1049  vmin,
1050  vrev;
1051 
1052  cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
1053 
1054  if (cnt == 3)
1055  {
1056  /* old style, e.g. 9.6.1 */
1057  conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
1058  }
1059  else if (cnt == 2)
1060  {
1061  if (vmaj >= 10)
1062  {
1063  /* new style, e.g. 10.1 */
1064  conn->sversion = 100 * 100 * vmaj + vmin;
1065  }
1066  else
1067  {
1068  /* old style without minor version, e.g. 9.6devel */
1069  conn->sversion = (100 * vmaj + vmin) * 100;
1070  }
1071  }
1072  else if (cnt == 1)
1073  {
1074  /* new style without minor version, e.g. 10devel */
1075  conn->sversion = 100 * 100 * vmaj;
1076  }
1077  else
1078  conn->sversion = 0; /* unknown */
1079  }
1080  else if (strcmp(name, "default_transaction_read_only") == 0)
1081  {
1083  (strcmp(value, "on") == 0) ? PG_BOOL_YES : PG_BOOL_NO;
1084  }
1085  else if (strcmp(name, "in_hot_standby") == 0)
1086  {
1087  conn->in_hot_standby =
1088  (strcmp(value, "on") == 0) ? PG_BOOL_YES : PG_BOOL_NO;
1089  }
1090 }
static bool static_std_strings
Definition: fe-exec.c:52
int pg_char_to_encoding(const char *name)
Definition: encnames.c:550
#define malloc(a)
Definition: header.h:50
int sversion
Definition: libpq-int.h:449
PGTernaryBool default_transaction_read_only
Definition: libpq-int.h:472
struct pgParameterStatus pgParameterStatus
static int static_client_encoding
Definition: fe-exec.c:51
PGTernaryBool in_hot_standby
Definition: libpq-int.h:473
pgParameterStatus * pstatus
Definition: libpq-int.h:469
bool std_strings
Definition: libpq-int.h:471
static struct @143 value
#define free(a)
Definition: header.h:65
struct pgParameterStatus * next
Definition: libpq-int.h:261
const char * name
Definition: encode.c:561
int client_encoding
Definition: libpq-int.h:470

◆ pqSaveWriteError()

static void pqSaveWriteError ( PGconn conn)
static

Definition at line 777 of file fe-exec.c.

References appendPQExpBufferStr(), pg_conn::errorMessage, libpq_gettext, pqSaveErrorResult(), and pg_conn::write_err_msg.

Referenced by PQgetResult().

778 {
779  /*
780  * If write_err_msg is null because of previous strdup failure, do what we
781  * can. (It's likely our machinations here will get OOM failures as well,
782  * but might as well try.)
783  */
784  if (conn->write_err_msg)
785  {
787  /* Avoid possibly appending the same message twice */
788  conn->write_err_msg[0] = '\0';
789  }
790  else
792  libpq_gettext("write to server failed\n"));
793 
794  pqSaveErrorResult(conn);
795 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
char * write_err_msg
Definition: libpq-int.h:455
PQExpBufferData errorMessage
Definition: libpq-int.h:571
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:765
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQsendDescribe()

static int PQsendDescribe ( PGconn conn,
char  desc_type,
const char *  desc_target 
)
static

Definition at line 2450 of file fe-exec.c.

References PGQUERY_DESCRIBE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqAllocCmdQueueEntry(), pqAppendCmdQueueEntry(), pqPipelineFlush(), pqPutc(), pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), pqRecycleCmdQueueEntry(), PQsendQueryStart(), and PGcmdQueueEntry::queryclass.

Referenced by PQdescribePortal(), PQdescribePrepared(), PQsendDescribePortal(), and PQsendDescribePrepared().

2451 {
2452  PGcmdQueueEntry *entry = NULL;
2453 
2454  /* Treat null desc_target as empty string */
2455  if (!desc_target)
2456  desc_target = "";
2457 
2458  if (!PQsendQueryStart(conn, true))
2459  return 0;
2460 
2461  entry = pqAllocCmdQueueEntry(conn);
2462  if (entry == NULL)
2463  return 0; /* error msg already set */
2464 
2465  /* construct the Describe message */
2466  if (pqPutMsgStart('D', conn) < 0 ||
2467  pqPutc(desc_type, conn) < 0 ||
2468  pqPuts(desc_target, conn) < 0 ||
2469  pqPutMsgEnd(conn) < 0)
2470  goto sendFailed;
2471 
2472  /* construct the Sync message */
2473  if (conn->pipelineStatus == PQ_PIPELINE_OFF)
2474  {
2475  if (pqPutMsgStart('S', conn) < 0 ||
2476  pqPutMsgEnd(conn) < 0)
2477  goto sendFailed;
2478  }
2479 
2480  /* remember we are doing a Describe */
2481  entry->queryclass = PGQUERY_DESCRIBE;
2482 
2483  /*
2484  * Give the data a push (in pipeline mode, only if we're past the size
2485  * threshold). In nonblock mode, don't complain if we're unable to send
2486  * it all; PQgetResult() will do any additional flushing needed.
2487  */
2488  if (pqPipelineFlush(conn) < 0)
2489  goto sendFailed;
2490 
2491  /* OK, it's launched! */
2492  pqAppendCmdQueueEntry(conn, entry);
2493 
2494  return 1;
2495 
2496 sendFailed:
2497  pqRecycleCmdQueueEntry(conn, entry);
2498  /* error message should be set up already */
2499  return 0;
2500 }
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:417
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1296
PGQueryClass queryclass
Definition: libpq-int.h:322
static int pqPipelineFlush(PGconn *conn)
Definition: fe-exec.c:3780
static bool PQsendQueryStart(PGconn *conn, bool newQuery)
Definition: fe-exec.c:1626
int pqPutc(char c, PGconn *conn)
Definition: fe-misc.c:95
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:155
static void pqAppendCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1247
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
static PGcmdQueueEntry * pqAllocCmdQueueEntry(PGconn *conn)
Definition: fe-exec.c:1213

◆ PQsendDescribePortal()

int PQsendDescribePortal ( PGconn conn,
const char *  portal 
)

Definition at line 2435 of file fe-exec.c.

References PQsendDescribe().

Referenced by test_prepared().

2436 {
2437  return PQsendDescribe(conn, 'P', portal);
2438 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2450

◆ PQsendDescribePrepared()

int PQsendDescribePrepared ( PGconn conn,
const char *  stmt 
)

Definition at line 2422 of file fe-exec.c.

References PQsendDescribe().

Referenced by test_prepared().

2423 {
2424  return PQsendDescribe(conn, 'S', stmt);
2425 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2450

◆ PQsendFlushRequest()

int PQsendFlushRequest ( PGconn conn)

Definition at line 3144 of file fe-exec.c.

References appendPQExpBufferStr(), pg_conn::asyncStatus, CONNECTION_OK, pg_conn::errorMessage, libpq_gettext, PGASYNC_IDLE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqPutMsgEnd(), pqPutMsgStart(), and pg_conn::status.

Referenced by test_nosync(), and test_uniqviol().

3145 {
3146  if (!conn)
3147  return 0;
3148 
3149  /* Don't try to send if we know there's no live connection. */
3150  if (conn->status != CONNECTION_OK)
3151  {
3153  libpq_gettext("no connection to the server\n"));
3154  return 0;
3155  }
3156 
3157  /* Can't send while already busy, either, unless enqueuing for later */
3158  if (conn->asyncStatus != PGASYNC_IDLE &&
3160  {
3162  libpq_gettext("another command is already in progress\n"));
3163  return 0;
3164  }
3165 
3166  if (pqPutMsgStart('H', conn) < 0 ||
3167  pqPutMsgEnd(conn) < 0)
3168  {
3169  return 0;
3170  }
3171 
3172  return 1;
3173 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:417
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
PQExpBufferData errorMessage
Definition: libpq-int.h:571
ConnStatusType status
Definition: libpq-int.h:410
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQsendPrepare()

int PQsendPrepare ( PGconn conn,
const char *  stmtName,
const char *  query,
int  nParams,
const Oid paramTypes 
)

Definition at line 1484 of file fe-exec.c.

References appendPQExpBuffer(), appendPQExpBufferStr(), pg_conn::errorMessage, i, libpq_gettext, PGQUERY_PREPARE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, PQ_QUERY_PARAM_MAX_LIMIT, pqAllocCmdQueueEntry(), pqAppendCmdQueueEntry(), pqPipelineFlush(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), pqRecycleCmdQueueEntry(), PQsendQueryStart(), PGcmdQueueEntry::query, and PGcmdQueueEntry::queryclass.

Referenced by PQprepare(), prepare_foreign_modify(), sendCommand(), test_pipelined_insert(), test_prepared(), and test_transaction().

1487 {
1488  PGcmdQueueEntry *entry = NULL;
1489 
1490  if (!PQsendQueryStart(conn, true))
1491  return 0;
1492 
1493  /* check the arguments */
1494  if (!stmtName)
1495  {
1497  libpq_gettext("statement name is a null pointer\n"));
1498  return 0;
1499  }
1500  if (!query)
1501  {
1503  libpq_gettext("command string is a null pointer\n"));
1504  return 0;
1505  }
1506  if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1507  {
1509  libpq_gettext("number of parameters must be between 0 and %d\n"),
1510  PQ_QUERY_PARAM_MAX_LIMIT);
1511  return 0;
1512  }
1513 
1514  entry = pqAllocCmdQueueEntry(conn);
1515  if (entry == NULL)
1516  return 0; /* error msg already set */
1517 
1518  /* construct the Parse message */
1519  if (pqPutMsgStart('P', conn) < 0 ||
1520  pqPuts(stmtName, conn) < 0 ||
1521  pqPuts(query, conn) < 0)
1522  goto sendFailed;
1523 
1524  if (nParams > 0 && paramTypes)
1525  {
1526  int i;
1527 
1528  if (pqPutInt(nParams, 2, conn) < 0)
1529  goto sendFailed;
1530  for (i = 0; i < nParams; i++)
1531  {
1532  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1533  goto sendFailed;
1534  }
1535  }
1536  else
1537  {
1538  if (pqPutInt(0, 2, conn) < 0)
1539  goto sendFailed;
1540  }
1541  if (pqPutMsgEnd(conn) < 0)
1542  goto sendFailed;
1543 
1544  /* Add a Sync, unless in pipeline mode. */
1545  if (conn->pipelineStatus == PQ_PIPELINE_OFF)
1546  {
1547  if (pqPutMsgStart('S', conn) < 0 ||
1548  pqPutMsgEnd(conn) < 0)
1549  goto sendFailed;
1550  }
1551 
1552  /* remember we are doing just a Parse */
1553  entry->queryclass = PGQUERY_PREPARE;
1554 
1555  /* and remember the query text too, if possible */
1556  /* if insufficient memory, query just winds up NULL */
1557  entry->query = strdup(query);
1558 
1559  /*
1560  * Give the data a push (in pipeline mode, only if we're past the size
1561  * threshold). In nonblock mode, don't complain if we're unable to send
1562  * it all; PQgetResult() will do any additional flushing needed.
1563  */
1564  if (pqPipelineFlush(conn) < 0)
1565  goto sendFailed;
1566 
1567  /* OK, it's launched! */
1568  pqAppendCmdQueueEntry(conn, entry);
1569 
1570  return 1;
1571 
1572 sendFailed:
1573  pqRecycleCmdQueueEntry(conn, entry);
1574  /* error message should be set up already */
1575  return 0;
1576 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:417
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1296
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:256
PGQueryClass queryclass
Definition: libpq-int.h:322
static int pqPipelineFlush(PGconn *conn)
Definition: fe-exec.c:3780
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
static bool PQsendQueryStart(PGconn *conn, bool newQuery)
Definition: fe-exec.c:1626
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:155
PQExpBufferData errorMessage
Definition: libpq-int.h:571
#define PQ_QUERY_PARAM_MAX_LIMIT
Definition: libpq-fe.h:441
static void pqAppendCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1247
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
int i
static PGcmdQueueEntry * pqAllocCmdQueueEntry(PGconn *conn)
Definition: fe-exec.c:1213
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQsendQuery()

int PQsendQuery ( PGconn conn,
const char *  query 
)

Definition at line 1326 of file fe-exec.c.

References PQsendQueryInternal().

Referenced by BaseBackup(), dblink_send_query(), do_sql_command(), fetch_more_data_begin(), libpqrcv_PQexec(), pgfdw_exec_cleanup_query(), pgfdw_exec_query(), PQexec(), run_command(), run_permutation(), run_reindex_command(), run_vacuum_command(), sendCommand(), storeQueryResult(), and test_pipeline_abort().

1327 {
1328  return PQsendQueryInternal(conn, query, true);
1329 }
static int PQsendQueryInternal(PGconn *conn, const char *query, bool newQuery)
Definition: fe-exec.c:1338

◆ PQsendQueryContinue()

int PQsendQueryContinue ( PGconn conn,
const char *  query 
)

Definition at line 1332 of file fe-exec.c.

References PQsendQueryInternal().

Referenced by PQconnectPoll().

1333 {
1334  return PQsendQueryInternal(conn, query, false);
1335 }
static int PQsendQueryInternal(PGconn *conn, const char *query, bool newQuery)
Definition: fe-exec.c:1338

◆ PQsendQueryGuts()

static int PQsendQueryGuts ( PGconn conn,
const char *  command,
const char *  stmtName,
int  nParams,
const Oid paramTypes,
const char *const *  paramValues,
const int *  paramLengths,
const int *  paramFormats,
int  resultFormat 
)
static

Definition at line 1707 of file fe-exec.c.

References appendPQExpBufferStr(), pg_conn::errorMessage, i, libpq_gettext, PGQUERY_EXTENDED, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqAllocCmdQueueEntry(), pqAppendCmdQueueEntry(), pqPipelineFlush(), pqPutc(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), pqPuts(), pqRecycleCmdQueueEntry(), PGcmdQueueEntry::query, and PGcmdQueueEntry::queryclass.

Referenced by PQsendQueryParams(), and PQsendQueryPrepared().

1716 {
1717  int i;
1718  PGcmdQueueEntry *entry;
1719 
1720  entry = pqAllocCmdQueueEntry(conn);
1721  if (entry == NULL)
1722  return 0; /* error msg already set */
1723 
1724  /*
1725  * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync
1726  * (if not in pipeline mode), using specified statement name and the
1727  * unnamed portal.
1728  */
1729 
1730  if (command)
1731  {
1732  /* construct the Parse message */
1733  if (pqPutMsgStart('P', conn) < 0 ||
1734  pqPuts(stmtName, conn) < 0 ||
1735  pqPuts(command, conn) < 0)
1736  goto sendFailed;
1737  if (nParams > 0 && paramTypes)
1738  {
1739  if (pqPutInt(nParams, 2, conn) < 0)
1740  goto sendFailed;
1741  for (i = 0; i < nParams; i++)
1742  {
1743  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1744  goto sendFailed;
1745  }
1746  }
1747  else
1748  {
1749  if (pqPutInt(0, 2, conn) < 0)
1750  goto sendFailed;
1751  }
1752  if (pqPutMsgEnd(conn) < 0)
1753  goto sendFailed;
1754  }
1755 
1756  /* Construct the Bind message */
1757  if (pqPutMsgStart('B', conn) < 0 ||
1758  pqPuts("", conn) < 0 ||
1759  pqPuts(stmtName, conn) < 0)
1760  goto sendFailed;
1761 
1762  /* Send parameter formats */
1763  if (nParams > 0 && paramFormats)
1764  {
1765  if (pqPutInt(nParams, 2, conn) < 0)
1766  goto sendFailed;
1767  for (i = 0; i < nParams; i++)
1768  {
1769  if (pqPutInt(paramFormats[i], 2, conn) < 0)
1770  goto sendFailed;
1771  }
1772  }
1773  else
1774  {
1775  if (pqPutInt(0, 2, conn) < 0)
1776  goto sendFailed;
1777  }
1778 
1779  if (pqPutInt(nParams, 2, conn) < 0)
1780  goto sendFailed;
1781 
1782  /* Send parameters */
1783  for (i = 0; i < nParams; i++)
1784  {
1785  if (paramValues && paramValues[i])
1786  {
1787  int nbytes;
1788 
1789  if (paramFormats && paramFormats[i] != 0)
1790  {
1791  /* binary parameter */
1792  if (paramLengths)
1793  nbytes = paramLengths[i];
1794  else
1795  {
1797  libpq_gettext("length must be given for binary parameter\n"));
1798  goto sendFailed;
1799  }
1800  }
1801  else
1802  {
1803  /* text parameter, do not use paramLengths */
1804  nbytes = strlen(paramValues[i]);
1805  }
1806  if (pqPutInt(nbytes, 4, conn) < 0 ||
1807  pqPutnchar(paramValues[i], nbytes, conn) < 0)
1808  goto sendFailed;
1809  }
1810  else
1811  {
1812  /* take the param as NULL */
1813  if (pqPutInt(-1, 4, conn) < 0)
1814  goto sendFailed;
1815  }
1816  }
1817  if (pqPutInt(1, 2, conn) < 0 ||
1818  pqPutInt(resultFormat, 2, conn))
1819  goto sendFailed;
1820  <