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, int offset)
 
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 *buffer, int length)
 
int PQgetlineAsync (PGconn *conn, char *buffer, int bufsize)
 
int PQputline (PGconn *conn, const char *string)
 
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 const PGresult OOM_result
 
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 4310 of file fe-exec.c.

◆ ISOCTDIGIT

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

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

◆ OCTVAL

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

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

◆ PGRESULT_ALIGN_BOUNDARY

#define PGRESULT_ALIGN_BOUNDARY   MAXIMUM_ALIGNOF /* from configure */

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

◆ PGRESULT_BLOCK_OVERHEAD

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

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

◆ PGRESULT_DATA_BLOCKSIZE

#define PGRESULT_DATA_BLOCKSIZE   2048

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

◆ PGRESULT_SEP_ALLOC_THRESHOLD

#define PGRESULT_SEP_ALLOC_THRESHOLD   (PGRESULT_DATA_BLOCKSIZE / 2)

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

Function Documentation

◆ check_field_number()

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

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

3340 {
3341  if (!res)
3342  return false; /* no way to display error message... */
3343  if (field_num < 0 || field_num >= res->numAttributes)
3344  {
3346  "column number %d is out of range 0..%d",
3347  field_num, res->numAttributes - 1);
3348  return false;
3349  }
3350  return true;
3351 }
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:933
PGNoticeHooks noticeHooks
Definition: libpq-int.h:188
int numAttributes
Definition: libpq-int.h:172

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

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

◆ check_param_number()

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

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

3378 {
3379  if (!res)
3380  return false; /* no way to display error message... */
3381  if (param_num < 0 || param_num >= res->numParameters)
3382  {
3384  "parameter number %d is out of range 0..%d",
3385  param_num, res->numParameters - 1);
3386  return false;
3387  }
3388 
3389  return true;
3390 }
int numParameters
Definition: libpq-int.h:177

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

Referenced by PQparamtype().

◆ check_tuple_field_number()

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

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

3356 {
3357  if (!res)
3358  return false; /* no way to display error message... */
3359  if (tup_num < 0 || tup_num >= res->ntups)
3360  {
3362  "row number %d is out of range 0..%d",
3363  tup_num, res->ntups - 1);
3364  return false;
3365  }
3366  if (field_num < 0 || field_num >= res->numAttributes)
3367  {
3369  "column number %d is out of range 0..%d",
3370  field_num, res->numAttributes - 1);
3371  return false;
3372  }
3373  return true;
3374 }
int ntups
Definition: libpq-int.h:171

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

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

◆ dupEvents()

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

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

406 {
407  PGEvent *newEvents;
408  size_t msize;
409  int i;
410 
411  if (!events || count <= 0)
412  return NULL;
413 
414  msize = count * sizeof(PGEvent);
415  newEvents = (PGEvent *) malloc(msize);
416  if (!newEvents)
417  return NULL;
418 
419  for (i = 0; i < count; i++)
420  {
421  newEvents[i].proc = events[i].proc;
422  newEvents[i].passThrough = events[i].passThrough;
423  newEvents[i].data = NULL;
424  newEvents[i].resultInitialized = false;
425  newEvents[i].name = strdup(events[i].name);
426  if (!newEvents[i].name)
427  {
428  while (--i >= 0)
429  free(newEvents[i].name);
430  free(newEvents);
431  return NULL;
432  }
433  msize += strlen(events[i].name) + 1;
434  }
435 
436  *memSize += msize;
437  return newEvents;
438 }
const char * name
Definition: encode.c:561
#define free(a)
Definition: header.h:65
#define malloc(a)
Definition: header.h:50
int i
Definition: isn.c:73
struct PGEvent PGEvent
void * passThrough
Definition: libpq-int.h:164
PGEventProc proc
Definition: libpq-int.h:162

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

Referenced by PQcopyResult(), and PQmakeEmptyPGresult().

◆ get_hex()

static char get_hex ( char  c)
inlinestatic

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

4164 {
4165  int res = -1;
4166 
4167  if (c > 0 && c < 127)
4168  res = hexlookup[(unsigned char) c];
4169 
4170  return (char) res;
4171 }
static const int8 hexlookup[128]
Definition: fe-exec.c:4151
char * c

References hexlookup, and res.

Referenced by PQunescapeBytea().

◆ getCopyResult()

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

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

2188 {
2189  /*
2190  * If the server connection has been lost, don't pretend everything is
2191  * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
2192  * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
2193  * error in the earlier steps in PQgetResult). The text returned in the
2194  * result is whatever is in conn->errorMessage; we hope that was filled
2195  * with something relevant when the lost connection was detected.
2196  */
2197  if (conn->status != CONNECTION_OK)
2198  {
2201  return pqPrepareAsyncResult(conn);
2202  }
2203 
2204  /* If we have an async result for the COPY, return that */
2205  if (conn->result && conn->result->resultStatus == copytype)
2206  return pqPrepareAsyncResult(conn);
2207 
2208  /* Otherwise, invent a suitable PGresult */
2209  return PQmakeEmptyPGresult(conn, copytype);
2210 }
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:800
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:157
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:846
@ CONNECTION_OK
Definition: libpq-fe.h:60
@ PGASYNC_IDLE
Definition: libpq-int.h:220
PGconn * conn
Definition: streamutil.c:54
PGresult * result
Definition: libpq-int.h:511
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:414
ConnStatusType status
Definition: libpq-int.h:413
ExecStatusType resultStatus
Definition: libpq-int.h:179

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

Referenced by PQgetResult().

◆ parseInput()

static void parseInput ( PGconn conn)
static

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

1990 {
1992 }
void pqParseInput3(PGconn *conn)
Definition: fe-protocol3.c:61

References conn, and pqParseInput3().

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

◆ pqAddTuple()

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

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

989 {
990  if (res->ntups >= res->tupArrSize)
991  {
992  /*
993  * Try to grow the array.
994  *
995  * We can use realloc because shallow copying of the structure is
996  * okay. Note that the first time through, res->tuples is NULL. While
997  * ANSI says that realloc() should act like malloc() in that case,
998  * some old C libraries (like SunOS 4.1.x) coredump instead. On
999  * failure realloc is supposed to return NULL without damaging the
1000  * existing allocation. Note that the positions beyond res->ntups are
1001  * garbage, not necessarily NULL.
1002  */
1003  int newSize;
1004  PGresAttValue **newTuples;
1005 
1006  /*
1007  * Since we use integers for row numbers, we can't support more than
1008  * INT_MAX rows. Make sure we allow that many, though.
1009  */
1010  if (res->tupArrSize <= INT_MAX / 2)
1011  newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
1012  else if (res->tupArrSize < INT_MAX)
1013  newSize = INT_MAX;
1014  else
1015  {
1016  *errmsgp = libpq_gettext("PGresult cannot support more than INT_MAX tuples");
1017  return false;
1018  }
1019 
1020  /*
1021  * Also, on 32-bit platforms we could, in theory, overflow size_t even
1022  * before newSize gets to INT_MAX. (In practice we'd doubtless hit
1023  * OOM long before that, but let's check.)
1024  */
1025 #if INT_MAX >= (SIZE_MAX / 2)
1026  if (newSize > SIZE_MAX / sizeof(PGresAttValue *))
1027  {
1028  *errmsgp = libpq_gettext("size_t overflow");
1029  return false;
1030  }
1031 #endif
1032 
1033  if (res->tuples == NULL)
1034  newTuples = (PGresAttValue **)
1035  malloc(newSize * sizeof(PGresAttValue *));
1036  else
1037  newTuples = (PGresAttValue **)
1038  realloc(res->tuples, newSize * sizeof(PGresAttValue *));
1039  if (!newTuples)
1040  return false; /* malloc or realloc failed */
1041  res->memorySize +=
1042  (newSize - res->tupArrSize) * sizeof(PGresAttValue *);
1043  res->tupArrSize = newSize;
1044  res->tuples = newTuples;
1045  }
1046  res->tuples[res->ntups] = tup;
1047  res->ntups++;
1048  return true;
1049 }
#define realloc(a, b)
Definition: header.h:60
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
#define libpq_gettext(x)
Definition: libpq-int.h:882
size_t memorySize
Definition: libpq-int.h:214
PGresAttValue ** tuples
Definition: libpq-int.h:174
int tupArrSize
Definition: libpq-int.h:176

References if(), libpq_gettext, malloc, pg_result::memorySize, pg_result::ntups, realloc, res, pg_result::tupArrSize, and pg_result::tuples.

Referenced by pqRowProcessor(), and PQsetvalue().

◆ pqAllocCmdQueueEntry()

static PGcmdQueueEntry* pqAllocCmdQueueEntry ( PGconn conn)
static

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

1309 {
1310  PGcmdQueueEntry *entry;
1311 
1312  if (conn->cmd_queue_recycle == NULL)
1313  {
1314  entry = (PGcmdQueueEntry *) malloc(sizeof(PGcmdQueueEntry));
1315  if (entry == NULL)
1316  {
1317  libpq_append_conn_error(conn, "out of memory");
1318  return NULL;
1319  }
1320  }
1321  else
1322  {
1323  entry = conn->cmd_queue_recycle;
1324  conn->cmd_queue_recycle = entry->next;
1325  }
1326  entry->next = NULL;
1327  entry->query = NULL;
1328 
1329  return entry;
1330 }
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition: fe-misc.c:1312
struct PGcmdQueueEntry * next
Definition: libpq-int.h:327
PGcmdQueueEntry * cmd_queue_recycle
Definition: libpq-int.h:444

References pg_conn::cmd_queue_recycle, conn, libpq_append_conn_error(), malloc, PGcmdQueueEntry::next, and PGcmdQueueEntry::query.

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

◆ pqAppendCmdQueueEntry()

static void pqAppendCmdQueueEntry ( PGconn conn,
PGcmdQueueEntry entry 
)
static

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

1342 {
1343  Assert(entry->next == NULL);
1344 
1345  if (conn->cmd_queue_head == NULL)
1346  conn->cmd_queue_head = entry;
1347  else
1348  conn->cmd_queue_tail->next = entry;
1349 
1350  conn->cmd_queue_tail = entry;
1351 
1352  switch (conn->pipelineStatus)
1353  {
1354  case PQ_PIPELINE_OFF:
1355  case PQ_PIPELINE_ON:
1356 
1357  /*
1358  * When not in pipeline aborted state, if there's a result ready
1359  * to be consumed, let it be so (that is, don't change away from
1360  * READY or READY_MORE); otherwise set us busy to wait for
1361  * something to arrive from the server.
1362  */
1363  if (conn->asyncStatus == PGASYNC_IDLE)
1365  break;
1366 
1367  case PQ_PIPELINE_ABORTED:
1368 
1369  /*
1370  * In aborted pipeline state, we don't expect anything from the
1371  * server (since we don't send any queries that are queued).
1372  * Therefore, if IDLE then do what PQgetResult would do to let
1373  * itself consume commands from the queue; if we're in any other
1374  * state, we don't have to do anything.
1375  */
1376  if (conn->asyncStatus == PGASYNC_IDLE ||
1379  break;
1380  }
1381 }
static void pqPipelineProcessQueue(PGconn *conn)
Definition: fe-exec.c:3036
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:158
@ PQ_PIPELINE_ABORTED
Definition: libpq-fe.h:160
@ PQ_PIPELINE_ON
Definition: libpq-fe.h:159
@ PGASYNC_BUSY
Definition: libpq-int.h:221
@ PGASYNC_PIPELINE_IDLE
Definition: libpq-int.h:230
Assert(fmt[strlen(fmt) - 1] !='\n')
PGcmdQueueEntry * cmd_queue_tail
Definition: libpq-int.h:438
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:420
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:437

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

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

◆ PQbinaryTuples()

int PQbinaryTuples ( const PGresult res)

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

3327 {
3328  if (!res)
3329  return 0;
3330  return res->binary;
3331 }
int binary
Definition: libpq-int.h:181

References pg_result::binary, and res.

Referenced by HandleCopyResult().

◆ PQclear()

void PQclear ( PGresult res)

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

719 {
720  PGresult_data *block;
721  int i;
722 
723  /* As a convenience, do nothing for a NULL pointer */
724  if (!res)
725  return;
726  /* Also, do nothing if the argument is OOM_result */
727  if ((const PGresult *) res == &OOM_result)
728  return;
729 
730  /* Close down any events we may have */
731  for (i = 0; i < res->nEvents; i++)
732  {
733  /* only send DESTROY to successfully-initialized event procs */
735  {
737 
738  evt.result = res;
739  (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
740  res->events[i].passThrough);
741  }
742  free(res->events[i].name);
743  }
744 
745  free(res->events);
746 
747  /* Free all the subsidiary blocks */
748  while ((block = res->curBlock) != NULL)
749  {
750  res->curBlock = block->next;
751  free(block);
752  }
753 
754  /* Free the top-level tuple pointer array */
755  free(res->tuples);
756 
757  /* zero out the pointer fields to catch programming errors */
758  res->attDescs = NULL;
759  res->tuples = NULL;
760  res->paramDescs = NULL;
761  res->errFields = NULL;
762  res->events = NULL;
763  res->nEvents = 0;
764  /* res->curBlock was zeroed out earlier */
765 
766  /* Free the PGresult structure itself */
767  free(res);
768 }
static const PGresult OOM_result
Definition: fe-exec.c:48
@ PGEVT_RESULTDESTROY
Definition: libpq-events.h:34
char * name
Definition: libpq-int.h:163
bool resultInitialized
Definition: libpq-int.h:166
int nEvents
Definition: libpq-int.h:190
PGresAttDesc * attDescs
Definition: libpq-int.h:173
PGMessageField * errFields
Definition: libpq-int.h:199
PGresParamDesc * paramDescs
Definition: libpq-int.h:178
PGEvent * events
Definition: libpq-int.h:189
PGresult_data * curBlock
Definition: libpq-int.h:210
PGresult_data * next
Definition: libpq-int.h:107

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

Referenced by pqClearAsyncResult(), PQcopyResult(), PQexecFinish(), PQexecStart(), pqInternalNotice(), PQmakeEmptyPGresult(), and pqRowProcessor().

◆ pqClearAsyncResult()

void pqClearAsyncResult ( PGconn conn)

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

777 {
778  PQclear(conn->result);
779  conn->result = NULL;
780  conn->error_result = false;
782  conn->next_result = NULL;
783 }
void PQclear(PGresult *res)
Definition: fe-exec.c:718
PGresult * next_result
Definition: libpq-int.h:513
bool error_result
Definition: libpq-int.h:512

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

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

◆ PQcmdStatus()

char* PQcmdStatus ( PGresult res)

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

3582 {
3583  if (!res)
3584  return NULL;
3585  return res->cmdStatus;
3586 }
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:180

References pg_result::cmdStatus, and res.

Referenced by dblink_exec(), ecpg_process_output(), ExecQueryAndProcessResults(), materializeResult(), PrintQueryResult(), PrintQueryStatus(), and test_pipelined_insert().

◆ PQcmdTuples()

char* PQcmdTuples ( PGresult res)

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

3652 {
3653  char *p,
3654  *c;
3655 
3656  if (!res)
3657  return "";
3658 
3659  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3660  {
3661  p = res->cmdStatus + 7;
3662  /* INSERT: skip oid and space */
3663  while (*p && *p != ' ')
3664  p++;
3665  if (*p == 0)
3666  goto interpret_error; /* no space? */
3667  p++;
3668  }
3669  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3670  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3671  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3672  p = res->cmdStatus + 7;
3673  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0 ||
3674  strncmp(res->cmdStatus, "MERGE ", 6) == 0)
3675  p = res->cmdStatus + 6;
3676  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3677  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3678  p = res->cmdStatus + 5;
3679  else
3680  return "";
3681 
3682  /* check that we have an integer (at least one digit, nothing else) */
3683  for (c = p; *c; c++)
3684  {
3685  if (!isdigit((unsigned char) *c))
3686  goto interpret_error;
3687  }
3688  if (c == p)
3689  goto interpret_error;
3690 
3691  return p;
3692 
3693 interpret_error:
3695  "could not interpret result from server: %s",
3696  res->cmdStatus);
3697  return "";
3698 }

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

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

◆ pqCommandQueueAdvance()

void pqCommandQueueAdvance ( PGconn conn)

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

3012 {
3013  PGcmdQueueEntry *prevquery;
3014 
3015  if (conn->cmd_queue_head == NULL)
3016  return;
3017 
3018  /* delink from queue */
3019  prevquery = conn->cmd_queue_head;
3021 
3022  /* If the queue is now empty, reset the tail too */
3023  if (conn->cmd_queue_head == NULL)
3024  conn->cmd_queue_tail = NULL;
3025 
3026  /* and make it recyclable */
3027  prevquery->next = NULL;
3028  pqRecycleCmdQueueEntry(conn, prevquery);
3029 }
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1388

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

Referenced by PQgetResult(), and pqParseInput3().

◆ PQconsumeInput()

int PQconsumeInput ( PGconn conn)

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

1954 {
1955  if (!conn)
1956  return 0;
1957 
1958  /*
1959  * for non-blocking connections try to flush the send-queue, otherwise we
1960  * may never get a response for something that may not have already been
1961  * sent because it's in our write buffer!
1962  */
1963  if (pqIsnonblocking(conn))
1964  {
1965  if (pqFlush(conn) < 0)
1966  return 0;
1967  }
1968 
1969  /*
1970  * Load more data, if available. We do this no matter what state we are
1971  * in, since we are probably getting called because the application wants
1972  * to get rid of a read-select condition. Note that we will NOT block
1973  * waiting for more input.
1974  */
1975  if (pqReadData(conn) < 0)
1976  return 0;
1977 
1978  /* Parsing of the data waits till later. */
1979  return 1;
1980 }
int pqReadData(PGconn *conn)
Definition: fe-misc.c:566
int pqFlush(PGconn *conn)
Definition: fe-misc.c:954
#define pqIsnonblocking(conn)
Definition: libpq-int.h:871

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

Referenced by advanceConnectionState(), CopyStreamReceive(), dblink_get_notify(), dblink_is_busy(), do_sql_command_end(), 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().

◆ PQcopyResult()

PGresult* PQcopyResult ( const PGresult src,
int  flags 
)

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

316 {
317  PGresult *dest;
318  int i;
319 
320  if (!src)
321  return NULL;
322 
324  if (!dest)
325  return NULL;
326 
327  /* Always copy these over. Is cmdStatus really useful here? */
328  dest->client_encoding = src->client_encoding;
329  strcpy(dest->cmdStatus, src->cmdStatus);
330 
331  /* Wants attrs? */
332  if (flags & (PG_COPYRES_ATTRS | PG_COPYRES_TUPLES))
333  {
334  if (!PQsetResultAttrs(dest, src->numAttributes, src->attDescs))
335  {
336  PQclear(dest);
337  return NULL;
338  }
339  }
340 
341  /* Wants to copy tuples? */
342  if (flags & PG_COPYRES_TUPLES)
343  {
344  int tup,
345  field;
346 
347  for (tup = 0; tup < src->ntups; tup++)
348  {
349  for (field = 0; field < src->numAttributes; field++)
350  {
351  if (!PQsetvalue(dest, tup, field,
352  src->tuples[tup][field].value,
353  src->tuples[tup][field].len))
354  {
355  PQclear(dest);
356  return NULL;
357  }
358  }
359  }
360  }
361 
362  /* Wants to copy notice hooks? */
363  if (flags & PG_COPYRES_NOTICEHOOKS)
364  dest->noticeHooks = src->noticeHooks;
365 
366  /* Wants to copy PGEvents? */
367  if ((flags & PG_COPYRES_EVENTS) && src->nEvents > 0)
368  {
369  dest->events = dupEvents(src->events, src->nEvents,
370  &dest->memorySize);
371  if (!dest->events)
372  {
373  PQclear(dest);
374  return NULL;
375  }
376  dest->nEvents = src->nEvents;
377  }
378 
379  /* Okay, trigger PGEVT_RESULTCOPY event */
380  for (i = 0; i < dest->nEvents; i++)
381  {
382  /* We don't fire events that had some previous failure */
383  if (src->events[i].resultInitialized)
384  {
385  PGEventResultCopy evt;
386 
387  evt.src = src;
388  evt.dest = dest;
389  if (dest->events[i].proc(PGEVT_RESULTCOPY, &evt,
390  dest->events[i].passThrough))
391  dest->events[i].resultInitialized = true;
392  }
393  }
394 
395  return dest;
396 }
int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs)
Definition: fe-exec.c:246
static PGEvent * dupEvents(PGEvent *events, int count, size_t *memSize)
Definition: fe-exec.c:405
int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len)
Definition: fe-exec.c:449
@ PGEVT_RESULTCOPY
Definition: libpq-events.h:33
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:100
#define PG_COPYRES_TUPLES
Definition: libpq-fe.h:46
#define PG_COPYRES_ATTRS
Definition: libpq-fe.h:45
#define PG_COPYRES_EVENTS
Definition: libpq-fe.h:47
#define PG_COPYRES_NOTICEHOOKS
Definition: libpq-fe.h:48
const PGresult * src
Definition: libpq-events.h:60
PGresult * dest
Definition: libpq-events.h:61
int client_encoding
Definition: libpq-int.h:191
char * value
Definition: libpq-int.h:140

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

Referenced by pqRowProcessor().

◆ PQdescribePortal()

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

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

2438 {
2439  if (!PQexecStart(conn))
2440  return NULL;
2441  if (!PQsendDescribe(conn, 'P', portal))
2442  return NULL;
2443  return PQexecFinish(conn);
2444 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2373
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2307
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2482

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

◆ PQdescribePrepared()

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

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

2419 {
2420  if (!PQexecStart(conn))
2421  return NULL;
2422  if (!PQsendDescribe(conn, 'S', stmt))
2423  return NULL;
2424  return PQexecFinish(conn);
2425 }

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

Referenced by DescribeQuery(), and ECPGdescribe().

◆ PQendcopy()

int PQendcopy ( PGconn conn)

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

2832 {
2833  if (!conn)
2834  return 0;
2835 
2836  return pqEndcopy3(conn);
2837 }
int pqEndcopy3(PGconn *conn)

References conn, and pqEndcopy3().

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

◆ PQenterPipelineMode()

int PQenterPipelineMode ( PGconn conn)

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

2925 {
2926  if (!conn)
2927  return 0;
2928 
2929  /* succeed with no action if already in pipeline mode */
2931  return 1;
2932 
2933  if (conn->asyncStatus != PGASYNC_IDLE)
2934  {
2935  libpq_append_conn_error(conn, "cannot enter pipeline mode, connection not idle");
2936  return 0;
2937  }
2938 
2940 
2941  return 1;
2942 }

References pg_conn::asyncStatus, conn, libpq_append_conn_error(), 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_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), and test_uniqviol().

◆ PQescapeBytea()

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

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

4303 {
4304  return PQescapeByteaInternal(NULL, from, from_length, to_length,
4306  false /* can't use hex */ );
4307 }
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:4190
static bool static_std_strings
Definition: fe-exec.c:59

References PQescapeByteaInternal(), and static_std_strings.

◆ PQescapeByteaConn()

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

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

4289 {
4290  if (!conn)
4291  return NULL;
4292 
4293  if (conn->cmd_queue_head == NULL)
4295 
4296  return PQescapeByteaInternal(conn, from, from_length, to_length,
4297  conn->std_strings,
4298  (conn->sversion >= 90000));
4299 }
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:855
bool std_strings
Definition: libpq-int.h:474
int sversion
Definition: libpq-int.h:452

References pg_conn::cmd_queue_head, conn, pqClearConnErrorState, PQescapeByteaInternal(), pg_conn::std_strings, and pg_conn::sversion.

◆ 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 4190 of file fe-exec.c.

4193 {
4194  const unsigned char *vp;
4195  unsigned char *rp;
4196  unsigned char *result;
4197  size_t i;
4198  size_t len;
4199  size_t bslash_len = (std_strings ? 1 : 2);
4200 
4201  /*
4202  * empty string has 1 char ('\0')
4203  */
4204  len = 1;
4205 
4206  if (use_hex)
4207  {
4208  len += bslash_len + 1 + 2 * from_length;
4209  }
4210  else
4211  {
4212  vp = from;
4213  for (i = from_length; i > 0; i--, vp++)
4214  {
4215  if (*vp < 0x20 || *vp > 0x7e)
4216  len += bslash_len + 3;
4217  else if (*vp == '\'')
4218  len += 2;
4219  else if (*vp == '\\')
4220  len += bslash_len + bslash_len;
4221  else
4222  len++;
4223  }
4224  }
4225 
4226  *to_length = len;
4227  rp = result = (unsigned char *) malloc(len);
4228  if (rp == NULL)
4229  {
4230  if (conn)
4231  libpq_append_conn_error(conn, "out of memory");
4232  return NULL;
4233  }
4234 
4235  if (use_hex)
4236  {
4237  if (!std_strings)
4238  *rp++ = '\\';
4239  *rp++ = '\\';
4240  *rp++ = 'x';
4241  }
4242 
4243  vp = from;
4244  for (i = from_length; i > 0; i--, vp++)
4245  {
4246  unsigned char c = *vp;
4247 
4248  if (use_hex)
4249  {
4250  *rp++ = hextbl[(c >> 4) & 0xF];
4251  *rp++ = hextbl[c & 0xF];
4252  }
4253  else if (c < 0x20 || c > 0x7e)
4254  {
4255  if (!std_strings)
4256  *rp++ = '\\';
4257  *rp++ = '\\';
4258  *rp++ = (c >> 6) + '0';
4259  *rp++ = ((c >> 3) & 07) + '0';
4260  *rp++ = (c & 07) + '0';
4261  }
4262  else if (c == '\'')
4263  {
4264  *rp++ = '\'';
4265  *rp++ = '\'';
4266  }
4267  else if (c == '\\')
4268  {
4269  if (!std_strings)
4270  {
4271  *rp++ = '\\';
4272  *rp++ = '\\';
4273  }
4274  *rp++ = '\\';
4275  *rp++ = '\\';
4276  }
4277  else
4278  *rp++ = c;
4279  }
4280  *rp = '\0';
4281 
4282  return result;
4283 }
static const char hextbl[]
Definition: fe-exec.c:4149
const void size_t len

References conn, hextbl, i, len, libpq_append_conn_error(), and malloc.

Referenced by PQescapeBytea(), and PQescapeByteaConn().

◆ PQescapeIdentifier()

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

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

4144 {
4145  return PQescapeInternal(conn, str, len, true);
4146 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:4015

References conn, len, PQescapeInternal(), and generate_unaccent_rules::str.

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

◆ PQescapeInternal()

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

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

4016 {
4017  const char *s;
4018  char *result;
4019  char *rp;
4020  int num_quotes = 0; /* single or double, depending on as_ident */
4021  int num_backslashes = 0;
4022  int input_len;
4023  int result_size;
4024  char quote_char = as_ident ? '"' : '\'';
4025 
4026  /* We must have a connection, else fail immediately. */
4027  if (!conn)
4028  return NULL;
4029 
4030  if (conn->cmd_queue_head == NULL)
4032 
4033  /* Scan the string for characters that must be escaped. */
4034  for (s = str; (s - str) < len && *s != '\0'; ++s)
4035  {
4036  if (*s == quote_char)
4037  ++num_quotes;
4038  else if (*s == '\\')
4039  ++num_backslashes;
4040  else if (IS_HIGHBIT_SET(*s))
4041  {
4042  int charlen;
4043 
4044  /* Slow path for possible multibyte characters */
4045  charlen = pg_encoding_mblen(conn->client_encoding, s);
4046 
4047  /* Multibyte character overruns allowable length. */
4048  if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
4049  {
4050  libpq_append_conn_error(conn, "incomplete multibyte character");
4051  return NULL;
4052  }
4053 
4054  /* Adjust s, bearing in mind that for loop will increment it. */
4055  s += charlen - 1;
4056  }
4057  }
4058 
4059  /* Allocate output buffer. */
4060  input_len = s - str;
4061  result_size = input_len + num_quotes + 3; /* two quotes, plus a NUL */
4062  if (!as_ident && num_backslashes > 0)
4063  result_size += num_backslashes + 2;
4064  result = rp = (char *) malloc(result_size);
4065  if (rp == NULL)
4066  {
4067  libpq_append_conn_error(conn, "out of memory");
4068  return NULL;
4069  }
4070 
4071  /*
4072  * If we are escaping a literal that contains backslashes, we use the
4073  * escape string syntax so that the result is correct under either value
4074  * of standard_conforming_strings. We also emit a leading space in this
4075  * case, to guard against the possibility that the result might be
4076  * interpolated immediately following an identifier.
4077  */
4078  if (!as_ident && num_backslashes > 0)
4079  {
4080  *rp++ = ' ';
4081  *rp++ = 'E';
4082  }
4083 
4084  /* Opening quote. */
4085  *rp++ = quote_char;
4086 
4087  /*
4088  * Use fast path if possible.
4089  *
4090  * We've already verified that the input string is well-formed in the
4091  * current encoding. If it contains no quotes and, in the case of
4092  * literal-escaping, no backslashes, then we can just copy it directly to
4093  * the output buffer, adding the necessary quotes.
4094  *
4095  * If not, we must rescan the input and process each character
4096  * individually.
4097  */
4098  if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
4099  {
4100  memcpy(rp, str, input_len);
4101  rp += input_len;
4102  }
4103  else
4104  {
4105  for (s = str; s - str < input_len; ++s)
4106  {
4107  if (*s == quote_char || (!as_ident && *s == '\\'))
4108  {
4109  *rp++ = *s;
4110  *rp++ = *s;
4111  }
4112  else if (!IS_HIGHBIT_SET(*s))
4113  *rp++ = *s;
4114  else
4115  {
4117 
4118  while (1)
4119  {
4120  *rp++ = *s;
4121  if (--i == 0)
4122  break;
4123  ++s; /* for loop will provide the final increment */
4124  }
4125  }
4126  }
4127  }
4128 
4129  /* Closing quote and terminating NUL. */
4130  *rp++ = quote_char;
4131  *rp = '\0';
4132 
4133  return result;
4134 }
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1094
int client_encoding
Definition: libpq-int.h:473
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:2130

References pg_conn::client_encoding, pg_conn::cmd_queue_head, conn, i, IS_HIGHBIT_SET, len, libpq_append_conn_error(), malloc, pg_encoding_mblen(), pqClearConnErrorState, and generate_unaccent_rules::str.

Referenced by PQescapeIdentifier(), and PQescapeLiteral().

◆ PQescapeLiteral()

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

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

4138 {
4139  return PQescapeInternal(conn, str, len, false);
4140 }

References conn, len, PQescapeInternal(), and generate_unaccent_rules::str.

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

◆ PQescapeString()

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

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

4001 {
4002  return PQescapeStringInternal(NULL, to, from, length, NULL,
4005 }
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:3904
static int static_client_encoding
Definition: fe-exec.c:58

References PQescapeStringInternal(), static_client_encoding, and static_std_strings.

Referenced by get_comma_elts(), and quote_postgres().

◆ PQescapeStringConn()

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

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

3981 {
3982  if (!conn)
3983  {
3984  /* force empty-string result */
3985  *to = '\0';
3986  if (error)
3987  *error = 1;
3988  return 0;
3989  }
3990 
3991  if (conn->cmd_queue_head == NULL)
3993 
3994  return PQescapeStringInternal(conn, to, from, length, error,
3996  conn->std_strings);
3997 }
static void error(void)
Definition: sql-dyntest.c:147

References pg_conn::client_encoding, pg_conn::cmd_queue_head, conn, error(), pqClearConnErrorState, PQescapeStringInternal(), and pg_conn::std_strings.

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

◆ 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 3904 of file fe-exec.c.

3908 {
3909  const char *source = from;
3910  char *target = to;
3911  size_t remaining = length;
3912 
3913  if (error)
3914  *error = 0;
3915 
3916  while (remaining > 0 && *source != '\0')
3917  {
3918  char c = *source;
3919  int len;
3920  int i;
3921 
3922  /* Fast path for plain ASCII */
3923  if (!IS_HIGHBIT_SET(c))
3924  {
3925  /* Apply quoting if needed */
3926  if (SQL_STR_DOUBLE(c, !std_strings))
3927  *target++ = c;
3928  /* Copy the character */
3929  *target++ = c;
3930  source++;
3931  remaining--;
3932  continue;
3933  }
3934 
3935  /* Slow path for possible multibyte characters */
3937 
3938  /* Copy the character */
3939  for (i = 0; i < len; i++)
3940  {
3941  if (remaining == 0 || *source == '\0')
3942  break;
3943  *target++ = *source++;
3944  remaining--;
3945  }
3946 
3947  /*
3948  * If we hit premature end of string (ie, incomplete multibyte
3949  * character), try to pad out to the correct length with spaces. We
3950  * may not be able to pad completely, but we will always be able to
3951  * insert at least one pad space (since we'd not have quoted a
3952  * multibyte character). This should be enough to make a string that
3953  * the server will error out on.
3954  */
3955  if (i < len)
3956  {
3957  if (error)
3958  *error = 1;
3959  if (conn)
3960  libpq_append_conn_error(conn, "incomplete multibyte character");
3961  for (; i < len; i++)
3962  {
3963  if (((size_t) (target - to)) / 2 >= length)
3964  break;
3965  *target++ = ' ';
3966  }
3967  break;
3968  }
3969  }
3970 
3971  /* Write the terminating NUL character. */
3972  *target = '\0';
3973 
3974  return target - to;
3975 }
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:1102
int remaining
Definition: informix.c:667
int32 encoding
Definition: pg_database.h:41
static rewind_source * source
Definition: pg_rewind.c:81

References conn, encoding, error(), i, IS_HIGHBIT_SET, len, libpq_append_conn_error(), pg_encoding_mblen(), remaining, source, and SQL_STR_DOUBLE.

Referenced by PQescapeString(), and PQescapeStringConn().

◆ PQexec()

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

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

2226 {
2227  if (!PQexecStart(conn))
2228  return NULL;
2229  if (!PQsendQuery(conn, query))
2230  return NULL;
2231  return PQexecFinish(conn);
2232 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1418

References conn, 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(), ECPGsetcommit(), ECPGtrans(), ExecQueryUsingCursor(), executeCommand(), executeMaintenanceCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlQuery(), ExecuteSqlStatement(), executeStatement(), get_create_object_cmd(), GetConnection(), GetSlotInformation(), GetTableInfo(), init_libpq_conn(), initGenerateDataClientSide(), libpq_traverse_files(), lo_initialize(), lockTableForWorker(), lookup_object_oid(), main(), pgfdw_xact_callback(), PQencryptPasswordConn(), PQsetClientEncoding(), PSQLexec(), 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().

◆ PQexecFinish()

static PGresult * PQexecFinish ( PGconn conn)
static

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

2374 {
2375  PGresult *result;
2376  PGresult *lastResult;
2377 
2378  /*
2379  * For backwards compatibility, return the last result if there are more
2380  * than one. (We used to have logic here to concatenate successive error
2381  * messages, but now that happens automatically, since conn->errorMessage
2382  * will continue to accumulate errors throughout this loop.)
2383  *
2384  * We have to stop if we see copy in/out/both, however. We will resume
2385  * parsing after application performs the data transfer.
2386  *
2387  * Also stop if the connection is lost (else we'll loop infinitely).
2388  */
2389  lastResult = NULL;
2390  while ((result = PQgetResult(conn)) != NULL)
2391  {
2392  PQclear(lastResult);
2393  lastResult = result;
2394  if (result->resultStatus == PGRES_COPY_IN ||
2395  result->resultStatus == PGRES_COPY_OUT ||
2396  result->resultStatus == PGRES_COPY_BOTH ||
2398  break;
2399  }
2400 
2401  return lastResult;
2402 }
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2031
@ CONNECTION_BAD
Definition: libpq-fe.h:61
@ PGRES_COPY_IN
Definition: libpq-fe.h:104
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:109
@ PGRES_COPY_OUT
Definition: libpq-fe.h:103

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

◆ 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 2239 of file fe-exec.c.

2247 {
2248  if (!PQexecStart(conn))
2249  return NULL;
2250  if (!PQsendQueryParams(conn, command,
2251  nParams, paramTypes, paramValues, paramLengths,
2252  paramFormats, resultFormat))
2253  return NULL;
2254  return PQexecFinish(conn);
2255 }
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:1494

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

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

◆ 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 2286 of file fe-exec.c.

2293 {
2294  if (!PQexecStart(conn))
2295  return NULL;
2296  if (!PQsendQueryPrepared(conn, stmtName,
2297  nParams, paramValues, paramLengths,
2298  paramFormats, resultFormat))
2299  return NULL;
2300  return PQexecFinish(conn);
2301 }
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:1635

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

Referenced by ecpg_execute(), and try_complete_step().

◆ PQexecStart()

static bool PQexecStart ( PGconn conn)
static

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

2308 {
2309  PGresult *result;
2310 
2311  if (!conn)
2312  return false;
2313 
2314  /*
2315  * Since this is the beginning of a query cycle, reset the error state.
2316  * However, in pipeline mode with something already queued, the error
2317  * buffer belongs to that command and we shouldn't clear it.
2318  */
2319  if (conn->cmd_queue_head == NULL)
2321 
2323  {
2324  libpq_append_conn_error(conn, "synchronous command execution functions are not allowed in pipeline mode");
2325  return false;
2326  }
2327 
2328  /*
2329  * Silently discard any prior query result that application didn't eat.
2330  * This is probably poor design, but it's here for backward compatibility.
2331  */
2332  while ((result = PQgetResult(conn)) != NULL)
2333  {
2334  ExecStatusType resultStatus = result->resultStatus;
2335 
2336  PQclear(result); /* only need its status */
2337  if (resultStatus == PGRES_COPY_IN)
2338  {
2339  /* get out of a COPY IN state */
2340  if (PQputCopyEnd(conn,
2341  libpq_gettext("COPY terminated by new PQexec")) < 0)
2342  return false;
2343  /* keep waiting to swallow the copy's failure message */
2344  }
2345  else if (resultStatus == PGRES_COPY_OUT)
2346  {
2347  /*
2348  * Get out of a COPY OUT state: we just switch back to BUSY and
2349  * allow the remaining COPY data to be dropped on the floor.
2350  */
2352  /* keep waiting to swallow the copy's completion message */
2353  }
2354  else if (resultStatus == PGRES_COPY_BOTH)
2355  {
2356  /* We don't allow PQexec during COPY BOTH */
2357  libpq_append_conn_error(conn, "PQexec not allowed during COPY BOTH");
2358  return false;
2359  }
2360  /* check for loss of connection, too */
2361  if (conn->status == CONNECTION_BAD)
2362  return false;
2363  }
2364 
2365  /* OK to send a command */
2366  return true;
2367 }
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2631
ExecStatusType
Definition: libpq-fe.h:95

References pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, CONNECTION_BAD, libpq_append_conn_error(), libpq_gettext, PGASYNC_BUSY, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, PQclear(), pqClearConnErrorState, PQgetResult(), PQputCopyEnd(), pg_result::resultStatus, and pg_conn::status.

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

◆ PQexitPipelineMode()

int PQexitPipelineMode ( PGconn conn)

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

2956 {
2957  if (!conn)
2958  return 0;
2959 
2961  (conn->asyncStatus == PGASYNC_IDLE ||
2963  conn->cmd_queue_head == NULL)
2964  return 1;
2965 
2966  switch (conn->asyncStatus)
2967  {
2968  case PGASYNC_READY:
2969  case PGASYNC_READY_MORE:
2970  /* there are some uncollected results */
2971  libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
2972  return 0;
2973 
2974  case PGASYNC_BUSY:
2975  libpq_append_conn_error(conn, "cannot exit pipeline mode while busy");
2976  return 0;
2977 
2978  case PGASYNC_IDLE:
2979  case PGASYNC_PIPELINE_IDLE:
2980  /* OK */
2981  break;
2982 
2983  case PGASYNC_COPY_IN:
2984  case PGASYNC_COPY_OUT:
2985  case PGASYNC_COPY_BOTH:
2986  libpq_append_conn_error(conn, "cannot exit pipeline mode while in COPY");
2987  }
2988 
2989  /* still work to process */
2990  if (conn->cmd_queue_head != NULL)
2991  {
2992  libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
2993  return 0;
2994  }
2995 
2998 
2999  /* Flush any pending data in out buffer */
3000  if (pqFlush(conn) < 0)
3001  return 0; /* error message is setup already */
3002  return 1;
3003 }
@ PGASYNC_COPY_OUT
Definition: libpq-int.h:228
@ PGASYNC_READY_MORE
Definition: libpq-int.h:224
@ PGASYNC_READY
Definition: libpq-int.h:222
@ PGASYNC_COPY_BOTH
Definition: libpq-int.h:229
@ PGASYNC_COPY_IN
Definition: libpq-int.h:227

References pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, libpq_append_conn_error(), PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_PIPELINE_IDLE, PGASYNC_READY, PGASYNC_READY_MORE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, and pqFlush().

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

◆ PQfformat()

int PQfformat ( const PGresult res,
int  field_num 
)

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

3538 {
3539  if (!check_field_number(res, field_num))
3540  return 0;
3541  if (res->attDescs)
3542  return res->attDescs[field_num].format;
3543  else
3544  return 0;
3545 }
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3339

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

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

◆ PQflush()

◆ PQfmod()

int PQfmod ( const PGresult res,
int  field_num 
)

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

3571 {
3572  if (!check_field_number(res, field_num))
3573  return 0;
3574  if (res->attDescs)
3575  return res->attDescs[field_num].atttypmod;
3576  else
3577  return 0;
3578 }
int atttypmod
Definition: libpq-fe.h:269

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

Referenced by DescribeQuery(), and ECPGget_desc().

◆ 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 2862 of file fe-exec.c.

2869 {
2870  *result_len = 0;
2871 
2872  if (!conn)
2873  return NULL;
2874 
2875  /*
2876  * Since this is the beginning of a query cycle, reset the error state.
2877  * However, in pipeline mode with something already queued, the error
2878  * buffer belongs to that command and we shouldn't clear it.
2879  */
2880  if (conn->cmd_queue_head == NULL)
2882 
2884  {
2885  libpq_append_conn_error(conn, "%s not allowed in pipeline mode", "PQfn");
2886  return NULL;
2887  }
2888 
2891  {
2892  libpq_append_conn_error(conn, "connection in wrong state");
2893  return NULL;
2894  }
2895 
2896  return pqFunctionCall3(conn, fnid,
2897  result_buf, result_len,
2898  result_is_int,
2899  args, nargs);
2900 }
PGresult * pqFunctionCall3(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
#define pgHavePendingResult(conn)
Definition: libpq-int.h:864
#define PGINVALID_SOCKET
Definition: port.h:31
pgsocket sock
Definition: libpq-int.h:447

References generate_unaccent_rules::args, pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, libpq_append_conn_error(), PGASYNC_IDLE, pgHavePendingResult, PGINVALID_SOCKET, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqClearConnErrorState, pqFunctionCall3(), 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().

◆ PQfname()

char* PQfname ( const PGresult res,
int  field_num 
)

◆ PQfnumber()

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

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

3419 {
3420  char *field_case;
3421  bool in_quotes;
3422  bool all_lower = true;
3423  const char *iptr;
3424  char *optr;
3425  int i;
3426 
3427  if (!res)
3428  return -1;
3429 
3430  /*
3431  * Note: it is correct to reject a zero-length input string; the proper
3432  * input to match a zero-length field name would be "".
3433  */
3434  if (field_name == NULL ||
3435  field_name[0] == '\0' ||
3436  res->attDescs == NULL)
3437  return -1;
3438 
3439  /*
3440  * Check if we can avoid the strdup() and related work because the
3441  * passed-in string wouldn't be changed before we do the check anyway.
3442  */
3443  for (iptr = field_name; *iptr; iptr++)
3444  {
3445  char c = *iptr;
3446 
3447  if (c == '"' || c != pg_tolower((unsigned char) c))
3448  {
3449  all_lower = false;
3450  break;
3451  }
3452  }
3453 
3454  if (all_lower)
3455  for (i = 0; i < res->numAttributes; i++)
3456  if (strcmp(field_name, res->attDescs[i].name) == 0)
3457  return i;
3458 
3459  /* Fall through to the normal check if that didn't work out. */
3460 
3461  /*
3462  * Note: this code will not reject partially quoted strings, eg
3463  * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
3464  * condition.
3465  */
3466  field_case = strdup(field_name);
3467  if (field_case == NULL)
3468  return -1; /* grotty */
3469 
3470  in_quotes = false;
3471  optr = field_case;
3472  for (iptr = field_case; *iptr; iptr++)
3473  {
3474  char c = *iptr;
3475 
3476  if (in_quotes)
3477  {
3478  if (c == '"')
3479  {
3480  if (iptr[1] == '"')
3481  {
3482  /* doubled quotes become a single quote */
3483  *optr++ = '"';
3484  iptr++;
3485  }
3486  else
3487  in_quotes = false;
3488  }
3489  else
3490  *optr++ = c;
3491  }
3492  else if (c == '"')
3493  in_quotes = true;
3494  else
3495  {
3496  c = pg_tolower((unsigned char) c);
3497  *optr++ = c;
3498  }
3499  }
3500  *optr = '\0';
3501 
3502  for (i = 0; i < res->numAttributes; i++)
3503  {
3504  if (strcmp(field_case, res->attDescs[i].name) == 0)
3505  {
3506  free(field_case);
3507  return i;
3508  }
3509  }
3510  free(field_case);
3511  return -1;
3512 }
unsigned char pg_tolower(unsigned char ch)
Definition: pgstrcasecmp.c:122

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

Referenced by append_depends_on_extension(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), check_for_data_types_usage(), check_for_incompatible_polymorphics(), check_for_isn_and_int8_passing_mismatch(), check_for_pg_role_prefix(), 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(), dumpRoleMembership(), dumpRoles(), dumpTableSchema(), dumpTSConfig(), dumpUserMappings(), get_db_infos(), get_rel_infos(), get_tablespace_paths(), getAccessMethods(), getAggregates(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getIndexes(), getInherits(), getLOs(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPolicies(), getProcLangs(), getPublicationNamespaces(), getPublications(), getPublicationTables(), getRules(), getSubscriptions(), getTableAttrs(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), old_9_6_invalidate_hash_indexes(), processExtensionTables(), report_extension_updates(), set_frozenxids(), and show_binary_results().

◆ PQfreemem()

◆ PQfreeNotify()

void PQfreeNotify ( PGnotify notify)

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

3883 {
3884  PQfreemem(notify);
3885 }
void PQfreemem(void *ptr)
Definition: fe-exec.c:3865

References PQfreemem().

◆ PQfsize()

int PQfsize ( const PGresult res,
int  field_num 
)

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

3560 {
3561  if (!check_field_number(res, field_num))
3562  return 0;
3563  if (res->attDescs)
3564  return res->attDescs[field_num].typlen;
3565  else
3566  return 0;
3567 }

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

Referenced by ecpg_build_compat_sqlda(), and ECPGget_desc().

◆ PQftable()

Oid PQftable ( const PGresult res,
int  field_num 
)

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

3516 {
3517  if (!check_field_number(res, field_num))
3518  return InvalidOid;
3519  if (res->attDescs)
3520  return res->attDescs[field_num].tableid;
3521  else
3522  return InvalidOid;
3523 }
#define InvalidOid
Definition: postgres_ext.h:36

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

◆ PQftablecol()

int PQftablecol ( const PGresult res,
int  field_num 
)

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

3527 {
3528  if (!check_field_number(res, field_num))
3529  return 0;
3530  if (res->attDescs)
3531  return res->attDescs[field_num].columnid;
3532  else
3533  return 0;
3534 }
int columnid
Definition: libpq-fe.h:265

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

◆ PQftype()

Oid PQftype ( const PGresult res,
int  field_num 
)

◆ PQgetCopyData()

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

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

2699 {
2700  *buffer = NULL; /* for all failure cases */
2701  if (!conn)
2702  return -2;
2703  if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2705  {
2706  libpq_append_conn_error(conn, "no COPY in progress");
2707  return -2;
2708  }
2709  return pqGetCopyData3(conn, buffer, async);
2710 }
int pqGetCopyData3(PGconn *conn, char **buffer, int async)

References pg_conn::asyncStatus, conn, libpq_append_conn_error(), PGASYNC_COPY_BOTH, PGASYNC_COPY_OUT, and pqGetCopyData3().

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

◆ PQgetisnull()

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

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

3731 {
3732  if (!check_tuple_field_number(res, tup_num, field_num))
3733  return 1; /* pretend it is null */
3734  if (res->tuples[tup_num][field_num].len == NULL_LEN)
3735  return 1;
3736  else
3737  return 0;
3738 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3354
#define NULL_LEN
Definition: libpq-int.h:135

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

Referenced by addFooterToPublicationDesc(), BaseBackup(), compile_database_list(), compile_relation_list_one_db(), describeOneTableDetails(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpDatabase(), dumpDomain(), dumpFunc(), dumpRangeType(), dumpRoles(), dumpTableData_insert(), ecpg_get_data(), ecpg_set_compat_sqlda(), ecpg_set_native_sqlda(), ECPGget_desc(), ExecQueryTuples(), get_db_infos(), getAggregates(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getLOs(), getNamespaces(), getPolicies(), getProcLangs(), getPublicationTables(), GetSlotInformation(), 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(), PrintResultInCrosstab(), process_queued_fetch_requests(), run_simple_query(), RunIdentifySystem(), sqlda_common_total_size(), StoreQueryTuple(), storeRow(), vacuum_one_database(), and verify_heap_slot_handler().

◆ PQgetlength()

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

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

3717 {
3718  if (!check_tuple_field_number(res, tup_num, field_num))
3719  return 0;
3720  if (res->tuples[tup_num][field_num].len != NULL_LEN)
3721  return res->tuples[tup_num][field_num].len;
3722  else
3723  return 0;
3724 }

References check_tuple_field_number(), pgresAttValue::len, NULL_LEN, res, 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().

◆ PQgetline()

int PQgetline ( PGconn conn,
char *  buffer,
int  length 
)

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

2737 {
2738  if (!buffer || length <= 0)
2739  return EOF;
2740  *buffer = '\0';
2741  /* length must be at least 3 to hold the \. terminator! */
2742  if (length < 3)
2743  return EOF;
2744 
2745  if (!conn)
2746  return EOF;
2747 
2748  return pqGetline3(conn, buffer, length);
2749 }
int pqGetline3(PGconn *conn, char *s, int maxlen)

References conn, and pqGetline3().

◆ PQgetlineAsync()

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

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

2784 {
2785  if (!conn)
2786  return -1;
2787 
2788  return pqGetlineAsync3(conn, buffer, bufsize);
2789 }
int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)

References conn, and pqGetlineAsync3().

Referenced by pqGetline3().

◆ PQgetResult()

PGresult* PQgetResult ( PGconn conn)

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

2032 {
2033  PGresult *res;
2034 
2035  if (!conn)
2036  return NULL;
2037 
2038  /* Parse any available data, if our state permits. */
2039  parseInput(conn);
2040 
2041  /* If not ready to return something, block until we are. */
2042  while (conn->asyncStatus == PGASYNC_BUSY)
2043  {
2044  int flushResult;
2045 
2046  /*
2047  * If data remains unsent, send it. Else we might be waiting for the
2048  * result of a command the backend hasn't even got yet.
2049  */
2050  while ((flushResult = pqFlush(conn)) > 0)
2051  {
2052  if (pqWait(false, true, conn))
2053  {
2054  flushResult = -1;
2055  break;
2056  }
2057  }
2058 
2059  /*
2060  * Wait for some more data, and load it. (Note: if the connection has
2061  * been lost, pqWait should return immediately because the socket
2062  * should be read-ready, either with the last server data or with an
2063  * EOF indication. We expect therefore that this won't result in any
2064  * undue delay in reporting a previous write failure.)
2065  */
2066  if (flushResult ||
2067  pqWait(true, false, conn) ||
2068  pqReadData(conn) < 0)
2069  {
2070  /* Report the error saved by pqWait or pqReadData */
2073  return pqPrepareAsyncResult(conn);
2074  }
2075 
2076  /* Parse it. */
2077  parseInput(conn);
2078 
2079  /*
2080  * If we had a write error, but nothing above obtained a query result
2081  * or detected a read error, report the write error.
2082  */
2084  {
2087  return pqPrepareAsyncResult(conn);
2088  }
2089  }
2090 
2091  /* Return the appropriate thing. */
2092  switch (conn->asyncStatus)
2093  {
2094  case PGASYNC_IDLE:
2095  res = NULL; /* query is complete */
2096  break;
2097  case PGASYNC_PIPELINE_IDLE:
2099 
2100  /*
2101  * We're about to return the NULL that terminates the round of
2102  * results from the current query; prepare to send the results
2103  * of the next query, if any, when we're called next. If there's
2104  * no next element in the command queue, this gets us in IDLE
2105  * state.
2106  */
2108  res = NULL; /* query is complete */
2109  break;
2110 
2111  case PGASYNC_READY:
2112 
2113  /*
2114  * For any query type other than simple query protocol, we advance
2115  * the command queue here. This is because for simple query
2116  * protocol we can get the READY state multiple times before the
2117  * command is actually complete, since the command string can
2118  * contain many queries. In simple query protocol, the queue
2119  * advance is done by fe-protocol3 when it receives ReadyForQuery.
2120  */
2121  if (conn->cmd_queue_head &&
2126  {
2127  /*
2128  * We're about to send the results of the current query. Set
2129  * us idle now, and ...
2130  */
2132 
2133  /*
2134  * ... in cases when we're sending a pipeline-sync result,
2135  * move queue processing forwards immediately, so that next
2136  * time we're called, we're prepared to return the next result
2137  * received from the server. In all other cases, leave the
2138  * queue state change for next time, so that a terminating
2139  * NULL result is sent.
2140  *
2141  * (In other words: we don't return a NULL after a pipeline
2142  * sync.)
2143  */
2146  }
2147  else
2148  {
2149  /* Set the state back to BUSY, allowing parsing to proceed. */
2151  }
2152  break;
2153  case PGASYNC_READY_MORE:
2155  /* Set the state back to BUSY, allowing parsing to proceed. */
2157  break;
2158  case PGASYNC_COPY_IN:
2160  break;
2161  case PGASYNC_COPY_OUT:
2163  break;
2164  case PGASYNC_COPY_BOTH:
2166  break;
2167  default:
2168  libpq_append_conn_error(conn, "unexpected asyncStatus: %d", (int) conn->asyncStatus);
2170  conn->asyncStatus = PGASYNC_IDLE; /* try to restore valid state */
2172  break;
2173  }
2174 
2175  /* Time to fire PGEVT_RESULTCREATE events, if there are any */
2176  if (res && res->nEvents > 0)
2178 
2179  return res;
2180 }
static void pqSaveWriteError(PGconn *conn)
Definition: fe-exec.c:817
static PGresult * getCopyResult(PGconn *conn, ExecStatusType copytype)
Definition: fe-exec.c:2187
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1989
void pqCommandQueueAdvance(PGconn *conn)
Definition: fe-exec.c:3011
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:979
int PQfireResultCreateEvents(PGconn *conn, PGresult *res)
Definition: libpq-events.c:185
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:111
@ PGQUERY_SIMPLE
Definition: libpq-int.h:312
PGQueryClass queryclass
Definition: libpq-int.h:325
bool write_failed
Definition: libpq-int.h:457

References Assert(), pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, getCopyResult(), libpq_append_conn_error(), pg_result::nEvents, parseInput(), PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_PIPELINE_IDLE, PGASYNC_READY, PGASYNC_READY_MORE, PGQUERY_SIMPLE, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_PIPELINE_SYNC, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqCommandQueueAdvance(), PQfireResultCreateEvents(), pqFlush(), pqPipelineProcessQueue(), pqPrepareAsyncResult(), pqReadData(), pqSaveErrorResult(), pqSaveWriteError(), pqWait(), PGcmdQueueEntry::queryclass, res, pg_result::resultStatus, and pg_conn::write_failed.

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

◆ PQgetvalue()

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

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

3706 {
3707  if (!check_tuple_field_number(res, tup_num, field_num))
3708  return NULL;
3709  return res->tuples[tup_num][field_num].value;
3710 }

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

Referenced by _check_database_version(), add_tablespace_footer(), addFooterToPublicationDesc(), append_depends_on_extension(), appendQualifiedRelation(), BaseBackup(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), check_for_data_types_usage(), check_for_incompatible_polymorphics(), check_for_isn_and_int8_passing_mismatch(), check_for_pg_role_prefix(), 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(), collectRoleNames(), collectSecLabels(), compile_database_list(), compile_relation_list_one_db(), convertTSFunction(), createViewAsClause(), describeOneTableDetails(), describePublications(), describeRoles(), describeTableDetails(), do_field(), dropDBs(), dropRoles(), dropTablespaces(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpDomain(), dumpEnumType(), dumpForeignServer(), dumpFunc(), dumpLOs(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSearchPath(), dumpSequence(), dumpSequenceData(), dumpStatisticsExt(), dumpTable(), dumpTableAttach(), dumpTableData_insert(), dumpTableSchema(), dumpTablespaces(), dumpTSConfig(), dumpTSDictionary(), dumpUserConfig(), dumpUserMappings(), ecpg_get_data(), ecpg_set_compat_sqlda(), ecpg_set_native_sqlda(), ecpg_store_result(), emitShSecLabels(), exec_command_password(), ExecQueryTuples(), expand_dbname_patterns(), expand_extension_name_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), 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(), getAdditionalACLs(), getAggregates(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getLOs(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPolicies(), getProcLangs(), getPublicationNamespaces(), getPublications(), getPublicationTables(), getRules(), GetSlotInformation(), 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(), listSchemas(), listTSConfigsVerbose(), listTSParsersVerbose(), lo_initialize(), lookup_object_oid(), main(), make_tuple_from_result_row(), materializeResult(), old_9_6_invalidate_hash_indexes(), postgresAnalyzeForeignTable(), postgresImportForeignSchema(), PQconnectPoll(), PQdisplayTuples(), PQencryptPasswordConn(), PQprintTuples(), printCrosstab(), printQuery(), PrintResultInCrosstab(), process_queued_fetch_requests(), process_result(), processExtensionTables(), readCommandResponse(), ReadEndOfStreamingResult(), 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().

◆ pqInternalNotice()

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

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

934 {
935  char msgBuf[1024];
936  va_list args;
937  PGresult *res;
938 
939  if (hooks->noticeRec == NULL)
940  return; /* nobody home to receive notice? */
941 
942  /* Format the message */
943  va_start(args, fmt);
944  vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
945  va_end(args);
946  msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
947 
948  /* Make a PGresult to pass to the notice receiver */
950  if (!res)
951  return;
952  res->noticeHooks = *hooks;
953 
954  /*
955  * Set up fields of notice.
956  */
960  /* XXX should provide a SQLSTATE too? */
961 
962  /*
963  * Result text is always just the primary message + newline. If we can't
964  * allocate it, substitute "out of memory", as in pqSetResultError.
965  */
966  res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, false);
967  if (res->errMsg)
968  sprintf(res->errMsg, "%s\n", msgBuf);
969  else
970  res->errMsg = libpq_gettext("out of memory\n");
971 
972  /*
973  * Pass to receiver, then free it.
974  */
976  PQclear(res);
977 }
void pqSaveMessageField(PGresult *res, char code, const char *value)
Definition: fe-exec.c:1055
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:560
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:107
static void const char * fmt
va_end(args)
va_start(args, fmt)
#define vsnprintf
Definition: port.h:237
#define sprintf
Definition: port.h:240
#define PG_DIAG_SEVERITY_NONLOCALIZED
Definition: postgres_ext.h:55
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:57
#define PG_DIAG_SEVERITY
Definition: postgres_ext.h:54
PQnoticeReceiver noticeRec
Definition: libpq-int.h:154
void * noticeRecArg
Definition: libpq-int.h:155
char * errMsg
Definition: libpq-int.h:198

References generate_unaccent_rules::args, pg_result::errMsg, fmt, libpq_gettext, pg_result::noticeHooks, PGNoticeHooks::noticeRec, PGNoticeHooks::noticeRecArg, PG_DIAG_MESSAGE_PRIMARY, PG_DIAG_SEVERITY, PG_DIAG_SEVERITY_NONLOCALIZED, PGRES_NONFATAL_ERROR, PQclear(), PQmakeEmptyPGresult(), pqResultAlloc(), pqSaveMessageField(), res, sprintf, va_end(), va_start(), and vsnprintf.

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

◆ PQisBusy()

int PQisBusy ( PGconn conn)

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

2001 {
2002  if (!conn)
2003  return false;
2004 
2005  /* Parse any available data, if our state permits. */
2006  parseInput(conn);
2007 
2008  /*
2009  * PQgetResult will return immediately in all states except BUSY. Also,
2010  * if we've detected read EOF and dropped the connection, we can expect
2011  * that PQgetResult will fail immediately. Note that we do *not* check
2012  * conn->write_failed here --- once that's become set, we know we have
2013  * trouble, but we need to keep trying to read until we have a complete
2014  * server message or detect read EOF.
2015  */
2017 }

References pg_conn::asyncStatus, conn, CONNECTION_BAD, parseInput(), PGASYNC_BUSY, and pg_conn::status.

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

◆ PQisnonblocking()

int PQisnonblocking ( const PGconn conn)

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

3813 {
3814  if (!conn || conn->status == CONNECTION_BAD)
3815  return false;
3816  return pqIsnonblocking(conn);
3817 }

References conn, CONNECTION_BAD, pqIsnonblocking, and pg_conn::status.

Referenced by test_disallowed_in_pipeline(), and test_simple_pipeline().

◆ PQisthreadsafe()

int PQisthreadsafe ( void  )

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

3822 {
3823 #ifdef ENABLE_THREAD_SAFETY
3824  return true;
3825 #else
3826  return false;
3827 #endif
3828 }

◆ PQmakeEmptyPGresult()

PGresult* PQmakeEmptyPGresult ( PGconn conn,
ExecStatusType  status 
)

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

158 {
159  PGresult *result;
160 
161  result = (PGresult *) malloc(sizeof(PGresult));
162  if (!result)
163  return NULL;
164 
165  result->ntups = 0;
166  result->numAttributes = 0;
167  result->attDescs = NULL;
168  result->tuples = NULL;
169  result->tupArrSize = 0;
170  result->numParameters = 0;
171  result->paramDescs = NULL;
172  result->resultStatus = status;
173  result->cmdStatus[0] = '\0';
174  result->binary = 0;
175  result->events = NULL;
176  result->nEvents = 0;
177  result->errMsg = NULL;
178  result->errFields = NULL;
179  result->errQuery = NULL;
180  result->null_field[0] = '\0';
181  result->curBlock = NULL;
182  result->curOffset = 0;
183  result->spaceLeft = 0;
184  result->memorySize = sizeof(PGresult);
185 
186  if (conn)
187  {
188  /* copy connection data we might need for operations on PGresult */
189  result->noticeHooks = conn->noticeHooks;
191 
192  /* consider copying conn's errorMessage */
193  switch (status)
194  {
195  case PGRES_EMPTY_QUERY:
196  case PGRES_COMMAND_OK:
197  case PGRES_TUPLES_OK:
198  case PGRES_COPY_OUT:
199  case PGRES_COPY_IN:
200  case PGRES_COPY_BOTH:
201  case PGRES_SINGLE_TUPLE:
202  /* non-error cases */
203  break;
204  default:
205  /* we intentionally do not use or modify errorReported here */
206  pqSetResultError(result, &conn->errorMessage, 0);
207  break;
208  }
209 
210  /* copy events last; result must be valid if we need to PQclear */
211  if (conn->nEvents > 0)
212  {
213  result->events = dupEvents(conn->events, conn->nEvents,
214  &result->memorySize);
215  if (!result->events)
216  {
217  PQclear(result);
218  return NULL;
219  }
220  result->nEvents = conn->nEvents;
221  }
222  }
223  else
224  {
225  /* defaults... */
226  result->noticeHooks.noticeRec = NULL;
227  result->noticeHooks.noticeRecArg = NULL;
228  result->noticeHooks.noticeProc = NULL;
229  result->noticeHooks.noticeProcArg = NULL;
230  result->client_encoding = PG_SQL_ASCII;
231  }
232 
233  return result;
234 }
void pqSetResultError(PGresult *res, PQExpBuffer errorMessage, int offset)
Definition: fe-exec.c:689
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:97
@ PGRES_SINGLE_TUPLE
Definition: libpq-fe.h:110
@ PGRES_EMPTY_QUERY
Definition: libpq-fe.h:96
struct pg_result PGresult
Definition: libpq-fe.h:173
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
void * noticeProcArg
Definition: libpq-int.h:157
PQnoticeProcessor noticeProc
Definition: libpq-int.h:156
PQExpBufferData errorMessage
Definition: libpq-int.h:588
int nEvents
Definition: libpq-int.h:409
PGNoticeHooks noticeHooks
Definition: libpq-int.h:405
PGEvent * events
Definition: libpq-int.h:408
int curOffset
Definition: libpq-int.h:211
char null_field[1]
Definition: libpq-int.h:203
int spaceLeft
Definition: libpq-int.h:212
char * errQuery
Definition: libpq-int.h:200

References pg_result::attDescs, pg_result::binary, pg_result::client_encoding, pg_conn::client_encoding, pg_result::cmdStatus, conn, 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(), pqInternalNotice(), pqParseInput3(), pqPipelineProcessQueue(), and pqPrepareAsyncResult().

◆ PQnfields()

◆ PQnotifies()

PGnotify* PQnotifies ( PGconn conn)

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

2549 {
2550  PGnotify *event;
2551 
2552  if (!conn)
2553  return NULL;
2554 
2555  /* Parse any available data to see if we can extract NOTIFY messages. */
2556  parseInput(conn);
2557 
2558  event = conn->notifyHead;
2559  if (event)
2560  {
2561  conn->notifyHead = event->next;
2562  if (!conn->notifyHead)
2563  conn->notifyTail = NULL;
2564  event->next = NULL; /* don't let app see the internal state */
2565  }
2566  return event;
2567 }
struct pgNotify * next
Definition: libpq-fe.h:193
PGnotify * notifyHead
Definition: libpq-int.h:424
PGnotify * notifyTail
Definition: libpq-int.h:425

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

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

◆ PQnparams()

int PQnparams ( const PGresult res)

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

3745 {
3746  if (!res)
3747  return 0;
3748  return res->numParameters;
3749 }

References pg_result::numParameters, and res.

◆ PQntuples()

int PQntuples ( const PGresult res)

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

3311 {
3312  if (!res)
3313  return 0;
3314  return res->ntups;
3315 }

References pg_result::ntups, and res.

Referenced by add_tablespace_footer(), addFooterToPublicationDesc(), append_depends_on_extension(), appendQualifiedRelation(), BaseBackup(), buildMatViewRefreshDependencies(), check_for_data_types_usage(), check_for_incompatible_polymorphics(), 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(), collectRoleNames(), collectSecLabels(), compile_database_list(), compile_relation_list_one_db(), CreateReplicationSlot(), createViewAsClause(), describeOneTableDetails(), describePublications(), describeRoles(), describeTableDetails(), dropDBs(), DropReplicationSlot(), dropRoles(), dropTablespaces(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpEnumType(), dumpLOs(), dumpOpclass(), dumpOpfamily(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSequence(), dumpSequenceData(), dumpTable(), dumpTableData_insert(), dumpTablespaces(), dumpTSConfig(), dumpUserConfig(), dumpUserMappings(), 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(), getAdditionalACLs(), getAggregates(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getIndexes(), getInherits(), getLOs(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPolicies(), getProcLangs(), getPublicationNamespaces(), getPublications(), getPublicationTables(), getRules(), GetSlotInformation(), 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(), listSchemas(), 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(), PrintResultInCrosstab(), 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().

◆ PQoidStatus()

char* PQoidStatus ( const PGresult res)

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

3595 {
3596  /*
3597  * This must be enough to hold the result. Don't laugh, this is better
3598  * than what this function used to do.
3599  */
3600  static char buf[24];
3601 
3602  size_t len;
3603 
3604  if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
3605  return "";
3606 
3607  len = strspn(res->cmdStatus + 7, "0123456789");
3608  if (len > sizeof(buf) - 1)
3609  len = sizeof(buf) - 1;
3610  memcpy(buf, res->cmdStatus + 7, len);
3611  buf[len] = '\0';
3612 
3613  return buf;
3614 }
static char * buf
Definition: pg_test_fsync.c:67

References buf, pg_result::cmdStatus, len, and res.

◆ PQoidValue()

Oid PQoidValue ( const PGresult res)

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

3623 {
3624  char *endptr = NULL;
3625  unsigned long result;
3626 
3627  if (!res ||
3628  strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
3629  res->cmdStatus[7] < '0' ||
3630  res->cmdStatus[7] > '9')
3631  return InvalidOid;
3632 
3633  result = strtoul(res->cmdStatus + 7, &endptr, 10);
3634 
3635  if (!endptr || (*endptr != ' ' && *endptr != '\0'))
3636  return InvalidOid;
3637  else
3638  return (Oid) result;
3639 }
unsigned int Oid
Definition: postgres_ext.h:31

References pg_result::cmdStatus, InvalidOid, and res.

Referenced by ecpg_process_output(), and PrintQueryStatus().

◆ PQparamtype()

Oid PQparamtype ( const PGresult res,
int  param_num 
)

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

3756 {
3757  if (!check_param_number(res, param_num))
3758  return InvalidOid;
3759  if (res->paramDescs)
3760  return res->paramDescs[param_num].typid;
3761  else
3762  return InvalidOid;
3763 }
static int check_param_number(const PGresult *res, int param_num)
Definition: fe-exec.c:3377

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

◆ pqPipelineFlush()

static int pqPipelineFlush ( PGconn conn)
static

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

3850 {
3851  if ((conn->pipelineStatus != PQ_PIPELINE_ON) ||
3853  return pqFlush(conn);
3854  return 0;
3855 }
#define OUTBUFFER_THRESHOLD
Definition: libpq-int.h:876
int outCount
Definition: libpq-int.h:491

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

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

◆ pqPipelineProcessQueue()

static void pqPipelineProcessQueue ( PGconn conn)
static

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

3037 {
3038  switch (conn->asyncStatus)
3039  {
3040  case PGASYNC_COPY_IN:
3041  case PGASYNC_COPY_OUT:
3042  case PGASYNC_COPY_BOTH:
3043  case PGASYNC_READY:
3044  case PGASYNC_READY_MORE:
3045  case PGASYNC_BUSY:
3046  /* client still has to process current query or results */
3047  return;
3048 
3049  case PGASYNC_IDLE:
3050  /*
3051  * If we're in IDLE mode and there's some command in the queue,
3052  * get us into PIPELINE_IDLE mode and process normally. Otherwise
3053  * there's nothing for us to do.
3054  */
3055  if (conn->cmd_queue_head != NULL)
3056  {
3058  break;
3059  }
3060  return;
3061 
3062  case PGASYNC_PIPELINE_IDLE:
3064  /* next query please */
3065  break;
3066  }
3067 
3068  /*
3069  * Reset single-row processing mode. (Client has to set it up for each
3070  * query, if desired.)
3071  */
3072  conn->singleRowMode = false;
3073 
3074  /*
3075  * If there are no further commands to process in the queue, get us in
3076  * "real idle" mode now.
3077  */
3078  if (conn->cmd_queue_head == NULL)
3079  {
3081  return;
3082  }
3083 
3084  /*
3085  * Reset the error state. This and the next couple of steps correspond to
3086  * what PQsendQueryStart didn't do for this query.
3087  */
3089 
3090  /* Initialize async result-accumulation state */
3092 
3095  {
3096  /*
3097  * In an aborted pipeline we don't get anything from the server for
3098  * each result; we're just discarding commands from the queue until we
3099  * get to the next sync from the server.
3100  *
3101  * The PGRES_PIPELINE_ABORTED results tell the client that its queries
3102  * got aborted.
3103  */
3105  if (!conn->result)
3106  {
3107  libpq_append_conn_error(conn, "out of memory");
3109  return;
3110  }
3112  }
3113  else
3114  {
3115  /* allow parsing to continue */
3117  }
3118 }
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:776
@ PGRES_PIPELINE_ABORTED
Definition: libpq-fe.h:112
@ PGQUERY_SYNC
Definition: libpq-int.h:316
bool singleRowMode
Definition: libpq-int.h:421

References Assert(), pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, libpq_append_conn_error(), PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_PIPELINE_IDLE, PGASYNC_READY, PGASYNC_READY_MORE, PGQUERY_SYNC, PGRES_PIPELINE_ABORTED, pg_conn::pipelineStatus, PQ_PIPELINE_ABORTED, PQ_PIPELINE_OFF, pqClearAsyncResult(), pqClearConnErrorState, PQmakeEmptyPGresult(), pqSaveErrorResult(), PGcmdQueueEntry::queryclass, pg_conn::result, and pg_conn::singleRowMode.

Referenced by pqAppendCmdQueueEntry(), and PQgetResult().

◆ PQpipelineSync()

int PQpipelineSync ( PGconn conn)

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

3142 {
3143  PGcmdQueueEntry *entry;
3144 
3145  if (!conn)
3146  return 0;
3147 
3149  {
3150  libpq_append_conn_error(conn, "cannot send pipeline when not in pipeline mode");
3151  return 0;
3152  }
3153 
3154  switch (conn->asyncStatus)
3155  {
3156  case PGASYNC_COPY_IN:
3157  case PGASYNC_COPY_OUT:
3158  case PGASYNC_COPY_BOTH:
3159  /* should be unreachable */
3161  "internal error: cannot send pipeline while in COPY\n");
3162  return 0;
3163  case PGASYNC_READY:
3164  case PGASYNC_READY_MORE:
3165  case PGASYNC_BUSY:
3166  case PGASYNC_IDLE:
3167  case PGASYNC_PIPELINE_IDLE:
3168  /* OK to send sync */
3169  break;
3170  }
3171 
3172  entry = pqAllocCmdQueueEntry(conn);
3173  if (entry == NULL)
3174  return 0; /* error msg already set */
3175 
3176  entry->queryclass = PGQUERY_SYNC;
3177  entry->query = NULL;
3178 
3179  /* construct the Sync message */
3180  if (pqPutMsgStart('S', conn) < 0 ||
3181  pqPutMsgEnd(conn) < 0)
3182  goto sendFailed;
3183 
3184  /*
3185  * Give the data a push. In nonblock mode, don't complain if we're unable
3186  * to send it all; PQgetResult() will do any additional flushing needed.
3187  */
3188  if (PQflush(conn) < 0)
3189  goto sendFailed;
3190 
3191  /* OK, it's launched! */
3192  pqAppendCmdQueueEntry(conn, entry);
3193 
3194  return 1;
3195 
3196 sendFailed:
3197  pqRecycleCmdQueueEntry(conn, entry);
3198  /* error message should be set up already */
3199  return 0;
3200 }
int PQflush(PGconn *conn)
Definition: fe-exec.c:3833
static void pqAppendCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1341
static PGcmdQueueEntry * pqAllocCmdQueueEntry(PGconn *conn)
Definition: fe-exec.c:1308
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:459
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:518
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367

References appendPQExpBufferStr(), pg_conn::asyncStatus, conn, pg_conn::errorMessage, libpq_append_conn_error(), PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_PIPELINE_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 discardUntilSync(), executeMetaCommand(), test_multi_pipelines(), test_pipeline_abort(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), and test_transaction().

◆ PQprepare()

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

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

2272 {
2273  if (!PQexecStart(conn))
2274  return NULL;
2275  if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
2276  return NULL;
2277  return PQexecFinish(conn);
2278 }
int PQsendPrepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:1538

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

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

◆ pqPrepareAsyncResult()

PGresult* pqPrepareAsyncResult ( PGconn conn)

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

847 {
848  PGresult *res;
849 
850  res = conn->result;
851  if (res)
852  {
853  /*
854  * If the pre-existing result is an ERROR (presumably something
855  * received from the server), assume that it represents whatever is in
856  * conn->errorMessage, and advance errorReported.
857  */
860  }
861  else
862  {
863  /*
864  * We get here after internal-to-libpq errors. We should probably
865  * always have error_result = true, but if we don't, gin up some error
866  * text.
867  */
868  if (!conn->error_result)
869  libpq_append_conn_error(conn, "no error text available");
870 
871  /* Paranoia: be sure errorReported offset is sane */
872  if (conn->errorReported < 0 ||
874  conn->errorReported = 0;
875 
876  /*
877  * Make a PGresult struct for the error. We temporarily lie about the
878  * result status, so that PQmakeEmptyPGresult doesn't uselessly copy
879  * all of conn->errorMessage.
880  */
882  if (res)
883  {
884  /*
885  * Report whatever new error text we have, and advance
886  * errorReported.
887  */
891  }
892  else
893  {
894  /*
895  * Ouch, not enough memory for a PGresult. Fortunately, we have a
896  * card up our sleeve: we can use the static OOM_result. Casting
897  * away const here is a bit ugly, but it seems best to declare
898  * OOM_result as const, in hopes it will be allocated in read-only
899  * storage.
900  */
902 
903  /*
904  * Don't advance errorReported. Perhaps we'll be able to report
905  * the text later.
906  */
907  }
908  }
909 
910  /*
911  * Replace conn->result with next_result, if any. In the normal case
912  * there isn't a next result and we're just dropping ownership of the
913  * current result. In single-row mode this restores the situation to what
914  * it was before we created the current single-row result.
915  */
917  conn->error_result = false; /* next_result is never an error */
918  conn->next_result = NULL;
919 
920  return res;
921 }
#define unconstify(underlying_type, expr)
Definition: c.h:1181
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:108
int errorReported
Definition: libpq-int.h:589

References conn, pg_conn::error_result, pg_conn::errorMessage, pg_conn::errorReported, PQExpBufferData::len, libpq_append_conn_error(), pg_conn::next_result, OOM_result, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PQmakeEmptyPGresult(), pqSetResultError(), res, pg_conn::result, pg_result::resultStatus, and unconstify.

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

◆ PQputCopyData()

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

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

2577 {
2578  if (!conn)
2579  return -1;
2580  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2582  {
2583  libpq_append_conn_error(conn, "no COPY in progress");
2584  return -1;
2585  }
2586 
2587  /*
2588  * Process any NOTICE or NOTIFY messages that might be pending in the
2589  * input buffer. Since the server might generate many notices during the
2590  * COPY, we want to clean those out reasonably promptly to prevent
2591  * indefinite expansion of the input buffer. (Note: the actual read of
2592  * input data into the input buffer happens down inside pqSendSome, but
2593  * it's not authorized to get rid of the data again.)
2594  */
2595  parseInput(conn);
2596 
2597  if (nbytes > 0)
2598  {
2599  /*
2600  * Try to flush any previously sent data in preference to growing the
2601  * output buffer. If we can't enlarge the buffer enough to hold the
2602  * data, return 0 in the nonblock case, else hard error. (For
2603  * simplicity, always assume 5 bytes of overhead.)
2604  */
2605  if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2606  {
2607  if (pqFlush(conn) < 0)
2608  return -1;
2609  if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2610  conn))
2611  return pqIsnonblocking(conn) ? 0 : -1;
2612  }
2613  /* Send the data (too simple to delegate to fe-protocol files) */
2614  if (pqPutMsgStart('d', conn) < 0 ||
2615  pqPutnchar(buffer, nbytes, conn) < 0 ||
2616  pqPutMsgEnd(conn) < 0)
2617  return -1;
2618  }
2619  return 1;
2620 }
int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:288
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:203
int outBufSize
Definition: libpq-int.h:490

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

◆ PQputCopyEnd()

int PQputCopyEnd ( PGconn conn,
const char *  errormsg 
)

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

2632 {
2633  if (!conn)
2634  return -1;
2635  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2637  {
2638  libpq_append_conn_error(conn, "no COPY in progress");
2639  return -1;
2640  }
2641 
2642  /*
2643  * Send the COPY END indicator. This is simple enough that we don't
2644  * bother delegating it to the fe-protocol files.
2645  */
2646  if (errormsg)
2647  {
2648  /* Send COPY FAIL */
2649  if (pqPutMsgStart('f', conn) < 0 ||
2650  pqPuts(errormsg, conn) < 0 ||
2651  pqPutMsgEnd(conn) < 0)
2652  return -1;
2653  }
2654  else
2655  {
2656  /* Send COPY DONE */
2657  if (pqPutMsgStart('c', conn) < 0 ||
2658  pqPutMsgEnd(conn) < 0)
2659  return -1;
2660  }
2661 
2662  /*
2663  * If we sent the COPY command in extended-query mode, we must issue a
2664  * Sync as well.
2665  */
2666  if (conn->cmd_queue_head &&
2668  {
2669  if (pqPutMsgStart('S', conn) < 0 ||
2670  pqPutMsgEnd(conn) < 0)
2671  return -1;
2672  }
2673 
2674  /* Return to active duty */
2677  else
2679 
2680  /* Try to flush data */
2681  if (pqFlush(conn) < 0)
2682  return -1;
2683 
2684  return 1;
2685 }
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:153

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

◆ PQputline()

int PQputline ( PGconn conn,
const char *  string 
)

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

2801 {
2802  return PQputnbytes(conn, string, strlen(string));
2803 }
int PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2810

References conn, and PQputnbytes().

Referenced by initGenerateDataClientSide().

◆ PQputnbytes()

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

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

2811 {
2812  if (PQputCopyData(conn, buffer, nbytes) > 0)
2813  return 0;
2814  else
2815  return EOF;
2816 }
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2576

References conn, and PQputCopyData().

Referenced by PQputline().

◆ pqRecycleCmdQueueEntry()

static void pqRecycleCmdQueueEntry ( PGconn conn,
PGcmdQueueEntry entry 
)
static

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

1389 {
1390  if (entry == NULL)
1391  return;
1392 
1393  /* recyclable entries should not have a follow-on command */
1394  Assert(entry->next == NULL);
1395 
1396  if (entry->query)
1397  {
1398  free(entry->query);
1399  entry->query = NULL;
1400  }
1401 
1402  entry->next = conn->cmd_queue_recycle;
1403  conn->cmd_queue_recycle = entry;
1404 }

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

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

◆ PQresStatus()

char* PQresStatus ( ExecStatusType  status)

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

3249 {
3250  if ((unsigned int) status >= lengthof(pgresStatus))
3251  return libpq_gettext("invalid ExecStatusType code");
3252  return pgresStatus[status];
3253 }
#define lengthof(array)
Definition: c.h:724
char *const pgresStatus[]
Definition: fe-exec.c:32

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

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

◆ PQresultAlloc()

void* PQresultAlloc ( PGresult res,
size_t  nBytes 
)

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

541 {
542  /* Fail if argument is NULL or OOM_result */
543  if (!res || (const PGresult *) res == &OOM_result)
544  return NULL;
545 
546  return pqResultAlloc(res, nBytes, true);
547 }

References OOM_result, pqResultAlloc(), and res.

Referenced by PQsetResultAttrs().

◆ pqResultAlloc()

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

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

561 {
562  char *space;
563  PGresult_data *block;
564 
565  if (!res)
566  return NULL;
567 
568  if (nBytes <= 0)
569  return res->null_field;
570 
571  /*
572  * If alignment is needed, round up the current position to an alignment
573  * boundary.
574  */
575  if (isBinary)
576  {
577  int offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
578 
579  if (offset)
580  {
583  }
584  }
585 
586  /* If there's enough space in the current block, no problem. */
587  if (nBytes <= (size_t) res->spaceLeft)
588  {
589  space = res->curBlock->space + res->curOffset;
590  res->curOffset += nBytes;
591  res->spaceLeft -= nBytes;
592  return space;
593  }
594 
595  /*
596  * If the requested object is very large, give it its own block; this
597  * avoids wasting what might be most of the current block to start a new
598  * block. (We'd have to special-case requests bigger than the block size
599  * anyway.) The object is always given binary alignment in this case.
600  */
601  if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
602  {
603  size_t alloc_size = nBytes + PGRESULT_BLOCK_OVERHEAD;
604 
605  block = (PGresult_data *) malloc(alloc_size);
606  if (!block)
607  return NULL;
608  res->memorySize += alloc_size;
609  space = block->space + PGRESULT_BLOCK_OVERHEAD;
610  if (res->curBlock)
611  {
612  /*
613  * Tuck special block below the active block, so that we don't
614  * have to waste the free space in the active block.
615  */
616  block->next = res->curBlock->next;
617  res->curBlock->next = block;
618  }
619  else
620  {
621  /* Must set up the new block as the first active block. */
622  block->next = NULL;
623  res->curBlock = block;
624  res->spaceLeft = 0; /* be sure it's marked full */
625  }
626  return space;
627  }
628 
629  /* Otherwise, start a new block. */
631  if (!block)
632  return NULL;
634  block->next = res->curBlock;
635  res->curBlock = block;
636  if (isBinary)
637  {
638  /* object needs full alignment */
641  }
642  else
643  {
644  /* we can cram it right after the overhead pointer */
645  res->curOffset = sizeof(PGresult_data);
647  }
648 
649  space = block->space + res->curOffset;
650  res->curOffset += nBytes;
651  res->spaceLeft -= nBytes;
652  return space;
653 }
#define PGRESULT_DATA_BLOCKSIZE
Definition: fe-exec.c:140
#define PGRESULT_BLOCK_OVERHEAD
Definition: fe-exec.c:142
#define PGRESULT_SEP_ALLOC_THRESHOLD
Definition: fe-exec.c:143
#define PGRESULT_ALIGN_BOUNDARY
Definition: fe-exec.c:141
union pgresult_data PGresult_data
Definition: libpq-int.h:103
char space[1]
Definition: libpq-int.h:108

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, res, pgresult_data::space, and pg_result::spaceLeft.

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

◆ PQresultErrorField()

char* PQresultErrorField ( const PGresult res,
int  fieldcode 
)

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

3296 {
3297  PGMessageField *pfield;
3298 
3299  if (!res)
3300  return NULL;
3301  for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
3302  {
3303  if (pfield->code == fieldcode)
3304  return pfield->contents;
3305  }
3306  return NULL;
3307 }
struct pgMessageField * next
Definition: libpq-int.h:146
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:148

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

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

◆ PQresultErrorMessage()

◆ PQresultMemorySize()

size_t PQresultMemorySize ( const PGresult res)

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

661 {
662  if (!res)
663  return 0;
664  return res->memorySize;
665 }

References pg_result::memorySize, and res.

◆ PQresultStatus()

ExecStatusType PQresultStatus ( const PGresult res)

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

3241 {
3242  if (!res)
3243  return PGRES_FATAL_ERROR;
3244  return res->resultStatus;
3245 }

References PGRES_FATAL_ERROR, res, and pg_result::resultStatus.

Referenced by _doSetSessionAuth(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), AcceptResult(), advanceConnectionState(), 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(), discardUntilSync(), do_sql_command_end(), DropReplicationSlot(), dumpTableData_copy(), ecpg_check_PQresult(), ecpg_process_output(), EndDBCopyMode(), ExecQueryAndProcessResults(), 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(), GetSlotInformation(), GetTableInfo(), handleCopyIn(), handleCopyOut(), HandleCopyResult(), 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(), PrintQueryResult(), PrintResultInCrosstab(), process_queued_fetch_requests(), process_result(), 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_pipeline_idle(), 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().

◆ pqResultStrdup()

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

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

673 {
674  char *space = (char *) pqResultAlloc(res, strlen(str) + 1, false);
675 
676  if (space)
677  strcpy(space, str);
678  return space;
679 }

References pqResultAlloc(), res, and generate_unaccent_rules::str.

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

◆ PQresultVerboseErrorMessage()

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

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

3267 {
3268  PQExpBufferData workBuf;
3269 
3270  /*
3271  * Because the caller is expected to free the result string, we must
3272  * strdup any constant result. We use plain strdup and document that
3273  * callers should expect NULL if out-of-memory.
3274  */
3275  if (!res ||
3278  return strdup(libpq_gettext("PGresult is not an error result\n"));
3279 
3280  initPQExpBuffer(&workBuf);
3281 
3282  pqBuildErrorMessage3(&workBuf, res, verbosity, show_context);
3283 
3284  /* If insufficient memory to format the message, fail cleanly */
3285  if (PQExpBufferDataBroken(workBuf))
3286  {
3287  termPQExpBuffer(&workBuf);
3288  return strdup(libpq_gettext("out of memory\n"));
3289  }
3290 
3291  return workBuf.data;
3292 }
void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
Definition: fe-protocol3.c:997
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67

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

Referenced by exec_command_errverbose().

◆ pqRowProcessor()

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

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

1203 {
1204  PGresult *res = conn->result;
1205  int nfields = res->numAttributes;
1206  const PGdataValue *columns = conn->rowBuf;
1207  PGresAttValue *tup;
1208  int i;
1209 
1210  /*
1211  * In single-row mode, make a new PGresult that will hold just this one
1212  * row; the original conn->result is left unchanged so that it can be used
1213  * again as the template for future rows.
1214  */
1215  if (conn->singleRowMode)
1216  {
1217  /* Copy everything that should be in the result at this point */
1218  res = PQcopyResult(res,
1221  if (!res)
1222  return 0;
1223  }
1224 
1225  /*
1226  * Basically we just allocate space in the PGresult for each field and
1227  * copy the data over.
1228  *
1229  * Note: on malloc failure, we return 0 leaving *errmsgp still NULL, which
1230  * caller will take to mean "out of memory". This is preferable to trying
1231  * to set up such a message here, because evidently there's not enough
1232  * memory for gettext() to do anything.
1233  */
1234  tup = (PGresAttValue *)
1235  pqResultAlloc(res, nfields * sizeof(PGresAttValue), true);
1236  if (tup == NULL)
1237  goto fail;
1238 
1239  for (i = 0; i < nfields; i++)
1240  {
1241  int clen = columns[i].len;
1242 
1243  if (clen < 0)
1244  {
1245  /* null field */
1246  tup[i].len = NULL_LEN;
1247  tup[i].value = res->null_field;
1248  }
1249  else
1250  {
1251  bool isbinary = (res->attDescs[i].format != 0);
1252  char *val;
1253 
1254  val = (char *) pqResultAlloc(res, clen + 1, isbinary);
1255  if (val == NULL)
1256  goto fail;
1257 
1258  /* copy and zero-terminate the data (even if it's binary) */
1259  memcpy(val, columns[i].value, clen);
1260  val[clen] = '\0';
1261 
1262  tup[i].len = clen;
1263  tup[i].value = val;
1264  }
1265  }
1266 
1267  /* And add the tuple to the PGresult's tuple array */
1268  if (!pqAddTuple(res, tup, errmsgp))
1269  goto fail;
1270 
1271  /*
1272  * Success. In single-row mode, make the result available to the client
1273  * immediately.
1274  */
1275  if (conn->singleRowMode)
1276  {
1277  /* Change result status to special single-row value */
1279  /* Stash old result for re-use later */
1281  conn->result = res;
1282  /* And mark the result ready to return */
1284  }
1285 
1286  return 1;
1287 
1288 fail:
1289  /* release locally allocated PGresult, if we made one */
1290  if (res != conn->result)
1291  PQclear(res);
1292  return 0;
1293 }
PGresult * PQcopyResult(const PGresult *src, int flags)
Definition: fe-exec.c:315
static bool pqAddTuple(PGresult *res, PGresAttValue *tup, const char **errmsgp)
Definition: fe-exec.c:988
static struct @143 value
long val
Definition: informix.c:664
PGdataValue * rowBuf
Definition: libpq-int.h:499

References pg_conn::asyncStatus, pg_result::attDescs, conn, 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(), res, pg_conn::result, pg_result::resultStatus, pg_conn::rowBuf, pg_conn::singleRowMode, val, value, and pgresAttValue::value.

Referenced by getAnotherTuple().

◆ pqSaveErrorResult()

void pqSaveErrorResult ( PGconn conn)

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

801 {
802  /* Drop any pending result ... */
804  /* ... and set flag to remember to make an error result later */
805  conn->error_result = true;
806 }

References conn, pg_conn::error_result, and pqClearAsyncResult().

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

◆ pqSaveMessageField()

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

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

1056 {
1057  PGMessageField *pfield;
1058 
1059  pfield = (PGMessageField *)
1061  offsetof(PGMessageField, contents) +
1062  strlen(value) + 1,
1063  true);
1064  if (!pfield)
1065  return; /* out of memory? */
1066  pfield->code = code;
1067  strcpy(pfield->contents, value);
1068  pfield->next = res->errFields;
1069  res->errFields = pfield;
1070 }

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

Referenced by pqGetErrorNotice3(), and pqInternalNotice().

◆ pqSaveParameterStatus()

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

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

1077 {
1078  pgParameterStatus *pstatus;
1079  pgParameterStatus *prev;
1080 
1081  /*
1082  * Forget any old information about the parameter
1083  */
1084  for (pstatus = conn->pstatus, prev = NULL;
1085  pstatus != NULL;
1086  prev = pstatus, pstatus = pstatus->next)
1087  {
1088  if (strcmp(pstatus->name, name) == 0)
1089  {
1090  if (prev)
1091  prev->next = pstatus->next;
1092  else
1093  conn->pstatus = pstatus->next;
1094  free(pstatus); /* frees name and value strings too */
1095  break;
1096  }
1097  }
1098 
1099  /*
1100  * Store new info as a single malloc block
1101  */
1102  pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
1103  strlen(name) + strlen(value) + 2);
1104  if (pstatus)
1105  {
1106  char *ptr;
1107 
1108  ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
1109  pstatus->name = ptr;
1110  strcpy(ptr, name);
1111  ptr += strlen(name) + 1;
1112  pstatus->value = ptr;
1113  strcpy(ptr, value);
1114  pstatus->next = conn->pstatus;
1115  conn->pstatus = pstatus;
1116  }
1117 
1118  /*
1119  * Save values of settings that are of interest to libpq in fields of the
1120  * PGconn object. We keep client_encoding and standard_conforming_strings
1121  * in static variables as well, so that PQescapeString and PQescapeBytea
1122  * can behave somewhat sanely (at least in single-connection-using
1123  * programs).
1124  */
1125  if (strcmp(name, "client_encoding") == 0)
1126  {
1128  /* if we don't recognize the encoding name, fall back to SQL_ASCII */
1129  if (conn->client_encoding < 0)
1132  }
1133  else if (strcmp(name, "standard_conforming_strings") == 0)
1134  {
1135  conn->std_strings = (strcmp(value, "on") == 0);
1137  }
1138  else if (strcmp(name, "server_version") == 0)
1139  {
1140  /* We convert the server version to numeric form. */
1141  int cnt;
1142  int vmaj,
1143  vmin,
1144  vrev;
1145 
1146  cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
1147 
1148  if (cnt == 3)
1149  {
1150  /* old style, e.g. 9.6.1 */
1151  conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
1152  }
1153  else if (cnt == 2)
1154  {
1155  if (vmaj >= 10)
1156  {
1157  /* new style, e.g. 10.1 */
1158  conn->sversion = 100 * 100 * vmaj + vmin;
1159  }
1160  else
1161  {
1162  /* old style without minor version, e.g. 9.6devel */
1163  conn->sversion = (100 * vmaj + vmin) * 100;
1164  }
1165  }
1166  else if (cnt == 1)
1167  {
1168  /* new style without minor version, e.g. 10devel */
1169  conn->sversion = 100 * 100 * vmaj;
1170  }
1171  else
1172  conn->sversion = 0; /* unknown */
1173  }
1174  else if (strcmp(name, "default_transaction_read_only") == 0)
1175  {
1177  (strcmp(value, "on") == 0) ? PG_BOOL_YES : PG_BOOL_NO;
1178  }
1179  else if (strcmp(name, "in_hot_standby") == 0)
1180  {
1181  conn->in_hot_standby =
1182  (strcmp(value, "on") == 0) ? PG_BOOL_YES : PG_BOOL_NO;
1183  }
1184 }
int pg_char_to_encoding(const char *name)
Definition: encnames.c:550
struct pgParameterStatus pgParameterStatus
@ PG_BOOL_YES
Definition: libpq-int.h:249
@ PG_BOOL_NO
Definition: libpq-int.h:250
struct pgParameterStatus * next
Definition: libpq-int.h:263
PGTernaryBool in_hot_standby
Definition: libpq-int.h:476
PGTernaryBool default_transaction_read_only
Definition: libpq-int.h:475
pgParameterStatus * pstatus
Definition: libpq-int.h:472

References pg_conn::client_encoding, conn, pg_conn::default_transaction_read_only, free, pg_conn::in_hot_standby, malloc, name, 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, value, and pgParameterStatus::value.

Referenced by getParameterStatus().

◆ pqSaveWriteError()

static void pqSaveWriteError ( PGconn conn)
static

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

818 {
819  /*
820  * If write_err_msg is null because of previous strdup failure, do what we
821  * can. (It's likely our machinations here will get OOM failures as well,
822  * but might as well try.)
823  */
824  if (conn->write_err_msg)
825  {
827  /* Avoid possibly appending the same message twice */
828  conn->write_err_msg[0] = '\0';
829  }
830  else
831  libpq_append_conn_error(conn, "write to server failed");
832 
834 }
char * write_err_msg
Definition: libpq-int.h:458

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

Referenced by PQgetResult().

◆ PQsendDescribe()

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

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

2483 {
2484  PGcmdQueueEntry *entry = NULL;
2485 
2486  /* Treat null desc_target as empty string */
2487  if (!desc_target)
2488  desc_target = "";
2489 
2490  if (!PQsendQueryStart(conn, true))
2491  return 0;
2492 
2493  entry = pqAllocCmdQueueEntry(conn);
2494  if (entry == NULL)
2495  return 0; /* error msg already set */
2496 
2497  /* construct the Describe message */
2498  if (pqPutMsgStart('D', conn) < 0 ||
2499  pqPutc(desc_type, conn) < 0 ||
2500  pqPuts(desc_target, conn) < 0 ||
2501  pqPutMsgEnd(conn) < 0)
2502  goto sendFailed;
2503 
2504  /* construct the Sync message */
2506  {
2507  if (pqPutMsgStart('S', conn) < 0 ||
2508  pqPutMsgEnd(conn) < 0)
2509  goto sendFailed;
2510  }
2511 
2512  /* remember we are doing a Describe */
2513  entry->queryclass = PGQUERY_DESCRIBE;
2514 
2515  /*
2516  * Give the data a push (in pipeline mode, only if we're past the size
2517  * threshold). In nonblock mode, don't complain if we're unable to send
2518  * it all; PQgetResult() will do any additional flushing needed.
2519  */
2520  if (pqPipelineFlush(conn) < 0)
2521  goto sendFailed;
2522 
2523  /* OK, it's launched! */
2524  pqAppendCmdQueueEntry(conn, entry);
2525 
2526  return 1;
2527 
2528 sendFailed:
2529  pqRecycleCmdQueueEntry(conn, entry);
2530  /* error message should be set up already */
2531  return 0;
2532 }
static int pqPipelineFlush(PGconn *conn)
Definition: fe-exec.c:3849
static bool PQsendQueryStart(PGconn *conn, bool newQuery)
Definition: fe-exec.c:1675
int pqPutc(char c, PGconn *conn)
Definition: fe-misc.c:93
@ PGQUERY_DESCRIBE
Definition: libpq-int.h:315

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

◆ PQsendDescribePortal()

int PQsendDescribePortal ( PGconn conn,
const char *  portal 
)

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

2468 {
2469  return PQsendDescribe(conn, 'P', portal);
2470 }

References conn, and PQsendDescribe().

Referenced by test_prepared().

◆ PQsendDescribePrepared()

int PQsendDescribePrepared ( PGconn conn,
const char *  stmt 
)

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

2455 {
2456  return PQsendDescribe(conn, 'S', stmt);
2457 }

References conn, and PQsendDescribe().

Referenced by test_prepared().

◆ PQsendFlushRequest()

int PQsendFlushRequest ( PGconn conn)

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

3209 {
3210  if (!conn)
3211  return 0;
3212 
3213  /* Don't try to send if we know there's no live connection. */
3214  if (conn->status != CONNECTION_OK)
3215  {
3216  libpq_append_conn_error(conn, "no connection to the server");
3217  return 0;
3218  }
3219 
3220  /* Can't send while already busy, either, unless enqueuing for later */
3221  if (conn->asyncStatus != PGASYNC_IDLE &&
3223  {
3224  libpq_append_conn_error(conn, "another command is already in progress");
3225  return 0;
3226  }
3227 
3228  if (pqPutMsgStart('H', conn) < 0 ||
3229  pqPutMsgEnd(conn) < 0)
3230  {
3231  return 0;
3232  }
3233 
3234  return 1;
3235 }

References pg_conn::asyncStatus, conn, CONNECTION_OK, libpq_append_conn_error(), PGASYNC_IDLE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqPutMsgEnd(), pqPutMsgStart(), and pg_conn::status.

Referenced by test_nosync(), test_pipeline_idle(), test_singlerowmode(), and test_uniqviol().

◆ PQsendPrepare()

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

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

1541 {
1542  PGcmdQueueEntry *entry = NULL;
1543 
1544  if (!PQsendQueryStart(conn, true))
1545  return 0;
1546 
1547  /* check the arguments */
1548  if (!stmtName)
1549  {
1550  libpq_append_conn_error(conn, "statement name is a null pointer");
1551  return 0;
1552  }
1553  if (!query)
1554  {
1555  libpq_append_conn_error(conn, "command string is a null pointer");
1556  return 0;
1557  }
1558  if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1559  {
1560  libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1562  return 0;
1563  }
1564 
1565  entry = pqAllocCmdQueueEntry(conn);
1566  if (entry == NULL)
1567  return 0; /* error msg already set */
1568 
1569  /* construct the Parse message */
1570  if (pqPutMsgStart('P', conn) < 0 ||
1571  pqPuts(stmtName, conn) < 0 ||
1572  pqPuts(query, conn) < 0)
1573  goto sendFailed;
1574 
1575  if (nParams > 0 && paramTypes)
1576  {
1577  int i;
1578 
1579  if (pqPutInt(nParams, 2, conn) < 0)
1580  goto sendFailed;
1581  for (i = 0; i < nParams; i++)
1582  {
1583  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1584  goto sendFailed;
1585  }
1586  }
1587  else
1588  {
1589  if (pqPutInt(0, 2, conn) < 0)
1590  goto sendFailed;
1591  }
1592  if (pqPutMsgEnd(conn) < 0)
1593  goto sendFailed;
1594 
1595  /* Add a Sync, unless in pipeline mode. */
1597  {
1598  if (pqPutMsgStart('S', conn) < 0 ||
1599  pqPutMsgEnd(conn) < 0)
1600  goto sendFailed;
1601  }
1602 
1603  /* remember we are doing just a Parse */
1604  entry->queryclass = PGQUERY_PREPARE;
1605 
1606  /* and remember the query text too, if possible */
1607  /* if insufficient memory, query just winds up NULL */
1608  entry->query = strdup(query);
1609 
1610  /*
1611  * Give the data a push (in pipeline mode, only if we're past the size
1612  * threshold). In nonblock mode, don't complain if we're unable to send
1613  * it all; PQgetResult() will do any additional flushing needed.
1614  */
1615  if (pqPipelineFlush(conn) < 0)
1616  goto sendFailed;
1617 
1618  /* OK, it's launched! */
1619  pqAppendCmdQueueEntry(conn, entry);
1620 
1621  return 1;
1622 
1623 sendFailed:
1624  pqRecycleCmdQueueEntry(conn, entry);
1625  /* error message should be set up already */
1626  return 0;
1627 }
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:254
#define PQ_QUERY_PARAM_MAX_LIMIT
Definition: libpq-fe.h:443
@ PGQUERY_PREPARE
Definition: libpq-int.h:314

References conn, i, libpq_append_conn_error(), 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().

◆ PQsendQuery()

◆ PQsendQueryContinue()

int PQsendQueryContinue ( PGconn conn,
const char *  query 
)

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

1425 {
1426  return PQsendQueryInternal(conn, query, false);
1427 }

References conn, and PQsendQueryInternal().

Referenced by PQconnectPoll().

◆ 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 1757 of file fe-exec.c.

1766 {
1767  int i;
1768  PGcmdQueueEntry *entry;
1769 
1770  entry = pqAllocCmdQueueEntry(conn);
1771  if (entry == NULL)
1772  return 0; /* error msg already set */
1773 
1774  /*
1775  * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync
1776  * (if not in pipeline mode), using specified statement name and the
1777  * unnamed portal.
1778  */
1779 
1780  if (command)
1781  {
1782  /* construct the Parse message */
1783  if (pqPutMsgStart('P', conn) < 0 ||
1784  pqPuts(stmtName, conn) < 0 ||
1785  pqPuts(command, conn) < 0)
1786  goto sendFailed;
1787  if (nParams > 0 && paramTypes)
1788  {
1789  if (pqPutInt(nParams, 2, conn) < 0)
1790  goto sendFailed;
1791  for (i = 0; i < nParams; i++)
1792  {
1793  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1794  goto sendFailed;
1795  }
1796  }
1797  else
1798  {
1799  if (pqPutInt(0, 2, conn) < 0)
1800  goto sendFailed;
1801  }
1802  if (pqPutMsgEnd(conn) < 0)
1803  goto sendFailed;
1804  }
1805 
1806  /* Construct the Bind message */
1807  if (pqPutMsgStart('B', conn) < 0 ||
1808  pqPuts("", conn) < 0 ||
1809  pqPuts(stmtName, conn) < 0)
1810  goto sendFailed;
1811 
1812  /* Send parameter formats */
1813  if (nParams > 0 && paramFormats)
1814  {
1815  if (pqPutInt(nParams, 2, conn) < 0)
1816  goto sendFailed;
1817  for (i = 0; i < nParams; i++)
1818  {
1819  if (pqPutInt(paramFormats[i], 2, conn) < 0)
1820  goto sendFailed;
1821  }
1822  }
1823  else
1824  {
1825  if (pqPutInt(0, 2, conn) < 0)
1826  goto sendFailed;
1827  }
1828 
1829  if (pqPutInt(nParams, 2, conn) < 0)
1830  goto sendFailed;
1831 
1832  /* Send parameters */
1833  for (i = 0; i < nParams; i++)
1834  {
1835  if (paramValues && paramValues[i])
1836  {
1837  int nbytes;
1838 
1839  if (paramFormats && paramFormats[i] != 0)
1840  {
1841  /* binary parameter */
1842  if (paramLengths)
1843  nbytes = paramLengths[i];
1844  else
1845  {
1846  libpq_append_conn_error(conn, "length must be given for binary parameter");
1847  goto sendFailed;
1848  }
1849  }
1850  else
1851  {
1852  /* text parameter, do not use paramLengths */
1853  nbytes = strlen(paramValues[i]);
1854  }
1855  if (pqPutInt(nbytes, 4, conn) < 0 ||
1856  pqPutnchar(paramValues[i], nbytes, conn) < 0)
1857  goto sendFailed;
1858  }
1859  else
1860  {
1861  /* take the param as NULL */
1862  if (pqPutInt(-1, 4, conn) < 0)
1863  goto sendFailed;
1864  }
1865  }
1866  if (pqPutInt(1, 2, conn) < 0 ||
1867  pqPutInt(resultFormat, 2, conn))
1868  goto sendFailed;
1869  if (pqPutMsgEnd(conn) < 0)
1870  goto sendFailed;
1871 
1872  /* construct the Describe Portal message */
1873  if (pqPutMsgStart('D', conn) < 0 ||
1874  pqPutc('P', conn) < 0 ||
1875  pqPuts("", conn) < 0 ||
1876  pqPutMsgEnd(conn) < 0)
1877  goto sendFailed;
1878 
1879  /* construct the Execute message */
1880  if (pqPutMsgStart('E', conn) < 0 ||
1881  pqPuts("", conn) < 0 ||
1882  pqPutInt(0, 4, conn) < 0 ||
1883  pqPutMsgEnd(conn) < 0)
1884  goto sendFailed;
1885 
1886  /* construct the Sync message if not in pipeline mode */
1888  {
1889  if (pqPutMsgStart('S', conn) < 0 ||
1890  pqPutMsgEnd(conn) < 0)
1891  goto sendFailed;
1892  }
1893 
1894  /* remember we are using extended query protocol */
1895  entry->queryclass = PGQUERY_EXTENDED;
1896 
1897  /* and remember the query text too, if possible */
1898  /* if insufficient memory, query just winds up NULL */
1899  if (command)
1900  entry->query = strdup(command);
1901 
1902  /*
1903  * Give the data a push (in pipeline mode, only if we're past the size
1904  * threshold). In nonblock mode, don't complain if we're unable to send
1905  * it all; PQgetResult() will do any additional flushing needed.
1906  */
1907  if (pqPipelineFlush(conn) < 0)
1908  goto sendFailed;
1909 
1910  /* OK, it's launched! */
1911  pqAppendCmdQueueEntry(conn, entry);
1912 
1913  return 1;
1914 
1915 sendFailed:
1916  pqRecycleCmdQueueEntry(conn, entry);
1917  /* error message should be set up already */
1918  return 0;
1919 }
@ PGQUERY_EXTENDED
Definition: libpq-int.h:313

References conn, i, libpq_append_conn_error(), 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().

◆ PQsendQueryInternal()

static int PQsendQueryInternal ( PGconn conn,
const char *  query,
bool  newQuery 
)
static

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

1431 {
1432  PGcmdQueueEntry *entry = NULL;
1433 
1434  if (!PQsendQueryStart(conn, newQuery))
1435  return 0;
1436 
1437  /* check the argument */
1438  if (!query)
1439  {
1440  libpq_append_conn_error(conn, "command string is a null pointer");
1441  return 0;
1442  }
1443 
1445  {
1446  libpq_append_conn_error(conn, "%s not allowed in pipeline mode",
1447  "PQsendQuery");
1448  return 0;
1449  }
1450 
1451  entry = pqAllocCmdQueueEntry(conn);
1452  if (entry == NULL)
1453  return 0; /* error msg already set */
1454 
1455  /* Send the query message(s) */
1456  /* construct the outgoing Query message */
1457  if (pqPutMsgStart('Q', conn) < 0 ||
1458  pqPuts(query, conn) < 0 ||
1459  pqPutMsgEnd(conn) < 0)
1460  {
1461  /* error message should be set up already */
1462  pqRecycleCmdQueueEntry(conn, entry);
1463  return 0;
1464  }
1465 
1466  /* remember we are using simple query protocol */
1467  entry->queryclass = PGQUERY_SIMPLE;
1468  /* and remember the query text too, if possible */
1469  entry->query = strdup(query);
1470 
1471  /*
1472  * Give the data a push. In nonblock mode, don't complain if we're unable
1473  * to send it all; PQgetResult() will do any additional flushing needed.
1474  */
1475  if (pqFlush(conn) < 0)
1476  goto sendFailed;
1477 
1478  /* OK, it's launched! */
1479  pqAppendCmdQueueEntry(conn, entry);
1480 
1481  return 1;
1482 
1483 sendFailed:
1484  pqRecycleCmdQueueEntry(conn, entry);
1485  /* error message should be set up already */
1486  return 0;
1487 }

References conn, libpq_append_conn_error(), PGQUERY_SIMPLE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqAllocCmdQueueEntry(), pqAppendCmdQueueEntry(), pqFlush(), pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), pqRecycleCmdQueueEntry(), PQsendQueryStart(), PGcmdQueueEntry::query, and PGcmdQueueEntry::queryclass.

Referenced by PQsendQuery(), and PQsendQueryContinue().

◆ PQsendQueryParams()

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 at line 1494 of file fe-exec.c.

1502 {
1503  if (!PQsendQueryStart(conn, true))
1504  return 0;
1505 
1506  /* check the arguments */
1507  if (!command)
1508  {
1509  libpq_append_conn_error(conn, "command string is a null pointer");
1510  return 0;
1511  }
1512  if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1513  {
1514  libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1516  return 0;
1517  }
1518 
1519  return PQsendQueryGuts(conn,
1520  command,
1521  "", /* use unnamed statement */
1522  nParams,
1523  paramTypes,
1524  paramValues,
1525  paramLengths,
1526  paramFormats,
1527  resultFormat);
1528 }
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)
Definition: fe-exec.c:1757

References conn, libpq_append_conn_error(), PQ_QUERY_PARAM_MAX_LIMIT, PQsendQueryGuts(), and PQsendQueryStart().

Referenced by create_cursor(), ExecQueryAndProcessResults(), execute_dml_stmt(), PQexecParams(), sendCommand(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_simple_pipeline(), test_singlerowmode(), and test_transaction().

◆ PQsendQueryPrepared()

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

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

1642 {
1643  if (!PQsendQueryStart(conn, true))
1644  return 0;
1645 
1646  /* check the arguments */
1647  if (!stmtName)
1648  {
1649  libpq_append_conn_error(conn, "statement name is a null pointer");
1650  return 0;
1651  }
1652  if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1653  {
1654  libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1656  return 0;
1657  }
1658 
1659  return PQsendQueryGuts(conn,
1660  NULL, /* no command to parse */
1661  stmtName,
1662  nParams,
1663  NULL, /* no param types */
1664  paramValues,
1665  paramLengths,
1666  paramFormats,
1667  resultFormat);
1668 }

References conn, libpq_append_conn_error(), PQ_QUERY_PARAM_MAX_LIMIT, PQsendQueryGuts(), and PQsendQueryStart().

Referenced by execute_foreign_modify(), PQexecPrepared(), process_queued_fetch_requests(), sendCommand(), test_pipelined_insert(), test_transaction(), and test_uniqviol().

◆ PQsendQueryStart()

static bool PQsendQueryStart ( PGconn conn,
bool  newQuery 
)
static

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

1676 {
1677  if (!conn)
1678  return false;
1679 
1680  /*
1681  * If this is the beginning of a query cycle, reset the error state.
1682  * However, in pipeline mode with something already queued, the error
1683  * buffer belongs to that command and we shouldn't clear it.
1684  */
1685  if (newQuery && conn->cmd_queue_head == NULL)
1687 
1688  /* Don't try to send if we know there's no live connection. */
1689  if (conn->status != CONNECTION_OK)
1690  {
1691  libpq_append_conn_error(conn, "no connection to the server");
1692  return false;
1693  }
1694 
1695  /* Can't send while already busy, either, unless enqueuing for later */
1696  if (conn->asyncStatus != PGASYNC_IDLE &&
1698  {
1699  libpq_append_conn_error(conn, "another command is already in progress");
1700  return false;
1701  }
1702 
1704  {
1705  /*
1706  * When enqueuing commands we don't change much of the connection
1707  * state since it's already in use for the current command. The
1708  * connection state will get updated when pqPipelineProcessQueue()
1709  * advances to start processing the queued message.
1710  *
1711  * Just make sure we can safely enqueue given the current connection
1712  * state. We can enqueue behind another queue item, or behind a
1713  * non-queue command (one that sends its own sync), but we can't
1714  * enqueue if the connection is in a copy state.
1715  */
1716  switch (conn->asyncStatus)
1717  {
1718  case PGASYNC_IDLE:
1719  case PGASYNC_PIPELINE_IDLE:
1720  case PGASYNC_READY:
1721  case PGASYNC_READY_MORE:
1722  case PGASYNC_BUSY:
1723  /* ok to queue */
1724  break;
1725 
1726  case PGASYNC_COPY_IN:
1727  case PGASYNC_COPY_OUT:
1728  case PGASYNC_COPY_BOTH:
1729  libpq_append_conn_error(conn, "cannot queue commands during COPY");
1730  return false;
1731  }
1732  }
1733  else
1734  {
1735  /*
1736  * This command's results will come in immediately. Initialize async
1737  * result-accumulation state
1738  */
1740 
1741  /* reset single-row processing mode */
1742  conn->singleRowMode = false;
1743  }
1744 
1745  /* ready to send command message */
1746  return true;
1747 }

References pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, CONNECTION_OK, libpq_append_conn_error(), PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_PIPELINE_IDLE, PGASYNC_READY, PGASYNC_READY_MORE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqClearAsyncResult(), pqClearConnErrorState, pg_conn::singleRowMode, and pg_conn::status.

Referenced by PQsendDescribe(), PQsendPrepare(), PQsendQueryInternal(), PQsendQueryParams(), and PQsendQueryPrepared().

◆ PQsetnonblocking()

int PQsetnonblocking ( PGconn conn,
int  arg 
)

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

3774 {
3775  bool barg;
3776 
3777  if (!conn || conn->status == CONNECTION_BAD)
3778  return -1;
3779 
3780  barg = (arg ? true : false);
3781 
3782  /* early out if the socket is already in the state requested */
3783  if (barg == conn->nonblocking)
3784  return 0;
3785 
3786  /*
3787  * to guarantee constancy for flushing/query/result-polling behavior we
3788  * need to flush the send queue at this point in order to guarantee proper
3789  * behavior. this is ok because either they are making a transition _from_
3790  * or _to_ blocking mode, either way we can block them.
3791  *
3792  * Clear error state in case pqFlush adds to it, unless we're actively
3793  * pipelining, in which case it seems best not to.
3794  */
3795  if (conn->cmd_queue_head == NULL)
3797 
3798  /* if we are going from blocking to non-blocking flush here */
3799  if (pqFlush(conn))
3800  return -1;
3801 
3802  conn->nonblocking = barg;
3803 
3804  return 0;
3805 }
return true
Definition: isn.c:126
void * arg
bool nonblocking
Definition: libpq-int.h:418

References arg, pg_conn::cmd_queue_head, conn, CONNECTION_BAD, pg_conn::nonblocking, pqClearConnErrorState, pqFlush(), pg_conn::status, and true.

Referenced by test_pipelined_insert(), and test_uniqviol().

◆ PQsetResultAttrs()

int PQsetResultAttrs ( PGresult res,
int  numAttributes,
PGresAttDesc attDescs 
)

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

247 {
248  int i;
249 
250  /* Fail if argument is NULL or OOM_result */
251  if (!res || (const PGresult *) res == &OOM_result)
252  return false;
253 
254  /* If attrs already exist, they cannot be overwritten. */
255  if (res->numAttributes > 0)
256  return false;
257 
258  /* ignore no-op request */
259  if (numAttributes <= 0 || !attDescs)
260  return true;
261 
262  res->attDescs = (PGresAttDesc *)
263  PQresultAlloc(res, numAttributes * sizeof(PGresAttDesc));
264 
265  if (!res->attDescs)
266  return false;
267 
268  res->numAttributes = numAttributes;
269  memcpy(res->attDescs, attDescs, numAttributes * sizeof(PGresAttDesc));
270 
271  /* deep-copy the attribute names, and determine format */
272  res->binary = 1;
273  for (i = 0; i < res->numAttributes; i++)
274  {
275  if (res->attDescs[i].name)
277  else
279 
280  if (!res->attDescs[i].name)
281  return false;
282 
283  if (res->attDescs[i].format == 0)
284  res->binary = 0;
285  }
286 
287  return true;
288 }
char * pqResultStrdup(PGresult *res, const char *str)
Definition: fe-exec.c:672
void * PQresultAlloc(PGresult *res, size_t nBytes)
Definition: fe-exec.c:540

References pg_result::attDescs, pg_result::binary, pgresAttDesc::format, i, pgresAttDesc::name, pg_result::null_field, pg_result::numAttributes, OOM_result, PQresultAlloc(), pqResultStrdup(), and res.

Referenced by PQcopyResult().

◆ pqSetResultError()

void pqSetResultError ( PGresult res,
PQExpBuffer  errorMessage,
int  offset 
)

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

690 {
691  char *msg;
692 
693  if (!res)
694  return;
695 
696  /*
697  * We handle two OOM scenarios here. The errorMessage buffer might be
698  * marked "broken" due to having previously failed to allocate enough
699  * memory for the message, or it might be fine but pqResultStrdup fails
700  * and returns NULL. In either case, just make res->errMsg point directly
701  * at a constant "out of memory" string.
702  */
703  if (!PQExpBufferBroken(errorMessage))
704  msg = pqResultStrdup(res, errorMessage->data + offset);
705  else
706  msg = NULL;
707  if (msg)
708  res->errMsg = msg;
709  else
710  res->errMsg = libpq_gettext("out of memory\n");
711 }
#define PQExpBufferBroken(str)
Definition: pqexpbuffer.h:59

References PQExpBufferData::data, pg_result::errMsg, libpq_gettext, PQExpBufferBroken, pqResultStrdup(), and res.

Referenced by pqGetErrorNotice3(), PQmakeEmptyPGresult(), and pqPrepareAsyncResult().

◆ PQsetSingleRowMode()

int PQsetSingleRowMode ( PGconn conn)

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

1926 {
1927  /*
1928  * Only allow setting the flag when we have launched a query and not yet
1929  * received any results.
1930  */
1931  if (!conn)
1932  return 0;
1933  if (conn->asyncStatus != PGASYNC_BUSY)
1934  return 0;
1935  if (!conn->cmd_queue_head ||
1937  conn->