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 PQsendTypedCommand (PGconn *conn, char command, char type, const char *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)
 
PGresultPQclosePrepared (PGconn *conn, const char *stmt)
 
PGresultPQclosePortal (PGconn *conn, const char *portal)
 
int PQsendClosePrepared (PGconn *conn, const char *stmt)
 
int PQsendClosePortal (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 4391 of file fe-exec.c.

◆ ISOCTDIGIT

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

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

◆ OCTVAL

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

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

3425 {
3426  if (!res)
3427  return false; /* no way to display error message... */
3428  if (field_num < 0 || field_num >= res->numAttributes)
3429  {
3431  "column number %d is out of range 0..%d",
3432  field_num, res->numAttributes - 1);
3433  return false;
3434  }
3435  return true;
3436 }
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:933
PGNoticeHooks noticeHooks
Definition: libpq-int.h:189
int numAttributes
Definition: libpq-int.h:173

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

3463 {
3464  if (!res)
3465  return false; /* no way to display error message... */
3466  if (param_num < 0 || param_num >= res->numParameters)
3467  {
3469  "parameter number %d is out of range 0..%d",
3470  param_num, res->numParameters - 1);
3471  return false;
3472  }
3473 
3474  return true;
3475 }
int numParameters
Definition: libpq-int.h:178

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

3441 {
3442  if (!res)
3443  return false; /* no way to display error message... */
3444  if (tup_num < 0 || tup_num >= res->ntups)
3445  {
3447  "row number %d is out of range 0..%d",
3448  tup_num, res->ntups - 1);
3449  return false;
3450  }
3451  if (field_num < 0 || field_num >= res->numAttributes)
3452  {
3454  "column number %d is out of range 0..%d",
3455  field_num, res->numAttributes - 1);
3456  return false;
3457  }
3458  return true;
3459 }
int ntups
Definition: libpq-int.h:172

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 }
#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:165
PGEventProc proc
Definition: libpq-int.h:163
const char * name

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

4245 {
4246  int res = -1;
4247 
4248  if (c > 0 && c < 127)
4249  res = hexlookup[(unsigned char) c];
4250 
4251  return (char) res;
4252 }
static const int8 hexlookup[128]
Definition: fe-exec.c:4232
char * c

References hexlookup, and res.

Referenced by PQunescapeBytea().

◆ getCopyResult()

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

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

2191 {
2192  /*
2193  * If the server connection has been lost, don't pretend everything is
2194  * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
2195  * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
2196  * error in the earlier steps in PQgetResult). The text returned in the
2197  * result is whatever is in conn->errorMessage; we hope that was filled
2198  * with something relevant when the lost connection was detected.
2199  */
2200  if (conn->status != CONNECTION_OK)
2201  {
2204  return pqPrepareAsyncResult(conn);
2205  }
2206 
2207  /* If we have an async result for the COPY, return that */
2208  if (conn->result && conn->result->resultStatus == copytype)
2209  return pqPrepareAsyncResult(conn);
2210 
2211  /* Otherwise, invent a suitable PGresult */
2212  return PQmakeEmptyPGresult(conn, copytype);
2213 }
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:221
PGconn * conn
Definition: streamutil.c:54
PGresult * result
Definition: libpq-int.h:537
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:426
ConnStatusType status
Definition: libpq-int.h:425
ExecStatusType resultStatus
Definition: libpq-int.h:180

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

1994 {
1996 }
void pqParseInput3(PGconn *conn)
Definition: fe-protocol3.c:66

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:900
size_t memorySize
Definition: libpq-int.h:215
PGresAttValue ** tuples
Definition: libpq-int.h:175
int tupArrSize
Definition: libpq-int.h:177

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

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

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

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

◆ pqAppendCmdQueueEntry()

static void pqAppendCmdQueueEntry ( PGconn conn,
PGcmdQueueEntry entry 
)
static

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

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

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(), PQsendPrepare(), PQsendQueryGuts(), PQsendQueryInternal(), and PQsendTypedCommand().

◆ PQbinaryTuples()

int PQbinaryTuples ( const PGresult res)

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

3412 {
3413  if (!res)
3414  return 0;
3415  return res->binary;
3416 }
int binary
Definition: libpq-int.h:182

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:164
bool resultInitialized
Definition: libpq-int.h:167
int nEvents
Definition: libpq-int.h:191
PGresAttDesc * attDescs
Definition: libpq-int.h:174
PGMessageField * errFields
Definition: libpq-int.h:200
PGresParamDesc * paramDescs
Definition: libpq-int.h:179
PGEvent * events
Definition: libpq-int.h:190
PGresult_data * curBlock
Definition: libpq-int.h:211
PGresult_data * next
Definition: libpq-int.h:108

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:539
bool error_result
Definition: libpq-int.h:538

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

◆ PQclosePortal()

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

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

2506 {
2507  if (!PQexecStart(conn))
2508  return NULL;
2509  if (!PQsendTypedCommand(conn, PqMsg_Close, 'P', portal))
2510  return NULL;
2511  return PQexecFinish(conn);
2512 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2376
static int PQsendTypedCommand(PGconn *conn, char command, char type, const char *target)
Definition: fe-exec.c:2555
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2310
#define PqMsg_Close
Definition: protocol.h:20

References conn, PQexecFinish(), PQexecStart(), PqMsg_Close, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQclosePrepared()

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

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

2488 {
2489  if (!PQexecStart(conn))
2490  return NULL;
2491  if (!PQsendTypedCommand(conn, PqMsg_Close, 'S', stmt))
2492  return NULL;
2493  return PQexecFinish(conn);
2494 }
#define stmt
Definition: indent_codes.h:59

References conn, PQexecFinish(), PQexecStart(), PqMsg_Close, PQsendTypedCommand(), and stmt.

Referenced by test_prepared().

◆ PQcmdStatus()

char* PQcmdStatus ( PGresult res)

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

3667 {
3668  if (!res)
3669  return NULL;
3670  return res->cmdStatus;
3671 }
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:181

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

3737 {
3738  char *p,
3739  *c;
3740 
3741  if (!res)
3742  return "";
3743 
3744  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3745  {
3746  p = res->cmdStatus + 7;
3747  /* INSERT: skip oid and space */
3748  while (*p && *p != ' ')
3749  p++;
3750  if (*p == 0)
3751  goto interpret_error; /* no space? */
3752  p++;
3753  }
3754  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3755  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3756  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3757  p = res->cmdStatus + 7;
3758  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0 ||
3759  strncmp(res->cmdStatus, "MERGE ", 6) == 0)
3760  p = res->cmdStatus + 6;
3761  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3762  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3763  p = res->cmdStatus + 5;
3764  else
3765  return "";
3766 
3767  /* check that we have an integer (at least one digit, nothing else) */
3768  for (c = p; *c; c++)
3769  {
3770  if (!isdigit((unsigned char) *c))
3771  goto interpret_error;
3772  }
3773  if (c == p)
3774  goto interpret_error;
3775 
3776  return p;
3777 
3778 interpret_error:
3780  "could not interpret result from server: %s",
3781  res->cmdStatus);
3782  return "";
3783 }

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

3096 {
3097  PGcmdQueueEntry *prevquery;
3098 
3099  if (conn->cmd_queue_head == NULL)
3100  return;
3101 
3102  /* delink from queue */
3103  prevquery = conn->cmd_queue_head;
3105 
3106  /* If the queue is now empty, reset the tail too */
3107  if (conn->cmd_queue_head == NULL)
3108  conn->cmd_queue_tail = NULL;
3109 
3110  /* and make it recyclable */
3111  prevquery->next = NULL;
3112  pqRecycleCmdQueueEntry(conn, prevquery);
3113 }
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1392

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

1958 {
1959  if (!conn)
1960  return 0;
1961 
1962  /*
1963  * for non-blocking connections try to flush the send-queue, otherwise we
1964  * may never get a response for something that may not have already been
1965  * sent because it's in our write buffer!
1966  */
1967  if (pqIsnonblocking(conn))
1968  {
1969  if (pqFlush(conn) < 0)
1970  return 0;
1971  }
1972 
1973  /*
1974  * Load more data, if available. We do this no matter what state we are
1975  * in, since we are probably getting called because the application wants
1976  * to get rid of a read-select condition. Note that we will NOT block
1977  * waiting for more input.
1978  */
1979  if (pqReadData(conn) < 0)
1980  return 0;
1981 
1982  /* Parsing of the data waits till later. */
1983  return 1;
1984 }
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:889

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_cancel_query_end(), pgfdw_exec_cleanup_query_end(), 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:192
char * value
Definition: libpq-int.h:141

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

2441 {
2442  if (!PQexecStart(conn))
2443  return NULL;
2444  if (!PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal))
2445  return NULL;
2446  return PQexecFinish(conn);
2447 }
#define PqMsg_Describe
Definition: protocol.h:21

References conn, PQexecFinish(), PQexecStart(), PqMsg_Describe, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQdescribePrepared()

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

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

2422 {
2423  if (!PQexecStart(conn))
2424  return NULL;
2426  return NULL;
2427  return PQexecFinish(conn);
2428 }

References conn, PQexecFinish(), PQexecStart(), PqMsg_Describe, PQsendTypedCommand(), and stmt.

Referenced by DescribeQuery(), ECPGdescribe(), and test_prepared().

◆ PQendcopy()

int PQendcopy ( PGconn conn)

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

2916 {
2917  if (!conn)
2918  return 0;
2919 
2920  return pqEndcopy3(conn);
2921 }
int pqEndcopy3(PGconn *conn)

References conn, and pqEndcopy3().

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

◆ PQenterPipelineMode()

int PQenterPipelineMode ( PGconn conn)

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

3009 {
3010  if (!conn)
3011  return 0;
3012 
3013  /* succeed with no action if already in pipeline mode */
3015  return 1;
3016 
3017  if (conn->asyncStatus != PGASYNC_IDLE)
3018  {
3019  libpq_append_conn_error(conn, "cannot enter pipeline mode, connection not idle");
3020  return 0;
3021  }
3022 
3024 
3025  return 1;
3026 }

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

4384 {
4385  return PQescapeByteaInternal(NULL, from, from_length, to_length,
4387  false /* can't use hex */ );
4388 }
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:4271
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 4367 of file fe-exec.c.

4370 {
4371  if (!conn)
4372  return NULL;
4373 
4374  if (conn->cmd_queue_head == NULL)
4376 
4377  return PQescapeByteaInternal(conn, from, from_length, to_length,
4378  conn->std_strings,
4379  (conn->sversion >= 90000));
4380 }
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:873
bool std_strings
Definition: libpq-int.h:498
int sversion
Definition: libpq-int.h:464

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

4274 {
4275  const unsigned char *vp;
4276  unsigned char *rp;
4277  unsigned char *result;
4278  size_t i;
4279  size_t len;
4280  size_t bslash_len = (std_strings ? 1 : 2);
4281 
4282  /*
4283  * empty string has 1 char ('\0')
4284  */
4285  len = 1;
4286 
4287  if (use_hex)
4288  {
4289  len += bslash_len + 1 + 2 * from_length;
4290  }
4291  else
4292  {
4293  vp = from;
4294  for (i = from_length; i > 0; i--, vp++)
4295  {
4296  if (*vp < 0x20 || *vp > 0x7e)
4297  len += bslash_len + 3;
4298  else if (*vp == '\'')
4299  len += 2;
4300  else if (*vp == '\\')
4301  len += bslash_len + bslash_len;
4302  else
4303  len++;
4304  }
4305  }
4306 
4307  *to_length = len;
4308  rp = result = (unsigned char *) malloc(len);
4309  if (rp == NULL)
4310  {
4311  if (conn)
4312  libpq_append_conn_error(conn, "out of memory");
4313  return NULL;
4314  }
4315 
4316  if (use_hex)
4317  {
4318  if (!std_strings)
4319  *rp++ = '\\';
4320  *rp++ = '\\';
4321  *rp++ = 'x';
4322  }
4323 
4324  vp = from;
4325  for (i = from_length; i > 0; i--, vp++)
4326  {
4327  unsigned char c = *vp;
4328 
4329  if (use_hex)
4330  {
4331  *rp++ = hextbl[(c >> 4) & 0xF];
4332  *rp++ = hextbl[c & 0xF];
4333  }
4334  else if (c < 0x20 || c > 0x7e)
4335  {
4336  if (!std_strings)
4337  *rp++ = '\\';
4338  *rp++ = '\\';
4339  *rp++ = (c >> 6) + '0';
4340  *rp++ = ((c >> 3) & 07) + '0';
4341  *rp++ = (c & 07) + '0';
4342  }
4343  else if (c == '\'')
4344  {
4345  *rp++ = '\'';
4346  *rp++ = '\'';
4347  }
4348  else if (c == '\\')
4349  {
4350  if (!std_strings)
4351  {
4352  *rp++ = '\\';
4353  *rp++ = '\\';
4354  }
4355  *rp++ = '\\';
4356  *rp++ = '\\';
4357  }
4358  else
4359  *rp++ = c;
4360  }
4361  *rp = '\0';
4362 
4363  return result;
4364 }
static const char hextbl[]
Definition: fe-exec.c:4230
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 4224 of file fe-exec.c.

4225 {
4226  return PQescapeInternal(conn, str, len, true);
4227 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:4096

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

4097 {
4098  const char *s;
4099  char *result;
4100  char *rp;
4101  int num_quotes = 0; /* single or double, depending on as_ident */
4102  int num_backslashes = 0;
4103  int input_len;
4104  int result_size;
4105  char quote_char = as_ident ? '"' : '\'';
4106 
4107  /* We must have a connection, else fail immediately. */
4108  if (!conn)
4109  return NULL;
4110 
4111  if (conn->cmd_queue_head == NULL)
4113 
4114  /* Scan the string for characters that must be escaped. */
4115  for (s = str; (s - str) < len && *s != '\0'; ++s)
4116  {
4117  if (*s == quote_char)
4118  ++num_quotes;
4119  else if (*s == '\\')
4120  ++num_backslashes;
4121  else if (IS_HIGHBIT_SET(*s))
4122  {
4123  int charlen;
4124 
4125  /* Slow path for possible multibyte characters */
4126  charlen = pg_encoding_mblen(conn->client_encoding, s);
4127 
4128  /* Multibyte character overruns allowable length. */
4129  if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
4130  {
4131  libpq_append_conn_error(conn, "incomplete multibyte character");
4132  return NULL;
4133  }
4134 
4135  /* Adjust s, bearing in mind that for loop will increment it. */
4136  s += charlen - 1;
4137  }
4138  }
4139 
4140  /* Allocate output buffer. */
4141  input_len = s - str;
4142  result_size = input_len + num_quotes + 3; /* two quotes, plus a NUL */
4143  if (!as_ident && num_backslashes > 0)
4144  result_size += num_backslashes + 2;
4145  result = rp = (char *) malloc(result_size);
4146  if (rp == NULL)
4147  {
4148  libpq_append_conn_error(conn, "out of memory");
4149  return NULL;
4150  }
4151 
4152  /*
4153  * If we are escaping a literal that contains backslashes, we use the
4154  * escape string syntax so that the result is correct under either value
4155  * of standard_conforming_strings. We also emit a leading space in this
4156  * case, to guard against the possibility that the result might be
4157  * interpolated immediately following an identifier.
4158  */
4159  if (!as_ident && num_backslashes > 0)
4160  {
4161  *rp++ = ' ';
4162  *rp++ = 'E';
4163  }
4164 
4165  /* Opening quote. */
4166  *rp++ = quote_char;
4167 
4168  /*
4169  * Use fast path if possible.
4170  *
4171  * We've already verified that the input string is well-formed in the
4172  * current encoding. If it contains no quotes and, in the case of
4173  * literal-escaping, no backslashes, then we can just copy it directly to
4174  * the output buffer, adding the necessary quotes.
4175  *
4176  * If not, we must rescan the input and process each character
4177  * individually.
4178  */
4179  if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
4180  {
4181  memcpy(rp, str, input_len);
4182  rp += input_len;
4183  }
4184  else
4185  {
4186  for (s = str; s - str < input_len; ++s)
4187  {
4188  if (*s == quote_char || (!as_ident && *s == '\\'))
4189  {
4190  *rp++ = *s;
4191  *rp++ = *s;
4192  }
4193  else if (!IS_HIGHBIT_SET(*s))
4194  *rp++ = *s;
4195  else
4196  {
4198 
4199  while (1)
4200  {
4201  *rp++ = *s;
4202  if (--i == 0)
4203  break;
4204  ++s; /* for loop will provide the final increment */
4205  }
4206  }
4207  }
4208  }
4209 
4210  /* Closing quote and terminating NUL. */
4211  *rp++ = quote_char;
4212  *rp = '\0';
4213 
4214  return result;
4215 }
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1168
int client_encoding
Definition: libpq-int.h:497
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 4218 of file fe-exec.c.

4219 {
4220  return PQescapeInternal(conn, str, len, false);
4221 }

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

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

◆ PQescapeString()

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

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

4082 {
4083  return PQescapeStringInternal(NULL, to, from, length, NULL,
4086 }
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:3985
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 4059 of file fe-exec.c.

4062 {
4063  if (!conn)
4064  {
4065  /* force empty-string result */
4066  *to = '\0';
4067  if (error)
4068  *error = 1;
4069  return 0;
4070  }
4071 
4072  if (conn->cmd_queue_head == NULL)
4074 
4075  return PQescapeStringInternal(conn, to, from, length, error,
4077  conn->std_strings);
4078 }
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 3985 of file fe-exec.c.

3989 {
3990  const char *source = from;
3991  char *target = to;
3992  size_t remaining = length;
3993 
3994  if (error)
3995  *error = 0;
3996 
3997  while (remaining > 0 && *source != '\0')
3998  {
3999  char c = *source;
4000  int len;
4001  int i;
4002 
4003  /* Fast path for plain ASCII */
4004  if (!IS_HIGHBIT_SET(c))
4005  {
4006  /* Apply quoting if needed */
4007  if (SQL_STR_DOUBLE(c, !std_strings))
4008  *target++ = c;
4009  /* Copy the character */
4010  *target++ = c;
4011  source++;
4012  remaining--;
4013  continue;
4014  }
4015 
4016  /* Slow path for possible multibyte characters */
4018 
4019  /* Copy the character */
4020  for (i = 0; i < len; i++)
4021  {
4022  if (remaining == 0 || *source == '\0')
4023  break;
4024  *target++ = *source++;
4025  remaining--;
4026  }
4027 
4028  /*
4029  * If we hit premature end of string (ie, incomplete multibyte
4030  * character), try to pad out to the correct length with spaces. We
4031  * may not be able to pad completely, but we will always be able to
4032  * insert at least one pad space (since we'd not have quoted a
4033  * multibyte character). This should be enough to make a string that
4034  * the server will error out on.
4035  */
4036  if (i < len)
4037  {
4038  if (error)
4039  *error = 1;
4040  if (conn)
4041  libpq_append_conn_error(conn, "incomplete multibyte character");
4042  for (; i < len; i++)
4043  {
4044  if (((size_t) (target - to)) / 2 >= length)
4045  break;
4046  *target++ = ' ';
4047  }
4048  break;
4049  }
4050  }
4051 
4052  /* Write the terminating NUL character. */
4053  *target = '\0';
4054 
4055  return target - to;
4056 }
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:1176
int remaining
Definition: informix.c:667
int32 encoding
Definition: pg_database.h:41
static rewind_source * source
Definition: pg_rewind.c:89

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

2229 {
2230  if (!PQexecStart(conn))
2231  return NULL;
2232  if (!PQsendQuery(conn, query))
2233  return NULL;
2234  return PQexecFinish(conn);
2235 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1422

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(), initPopulateTable(), 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 2376 of file fe-exec.c.

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

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

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

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

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

Referenced by ecpg_execute(), and try_complete_step().

◆ PQexecStart()

static bool PQexecStart ( PGconn conn)
static

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

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

◆ PQexitPipelineMode()

int PQexitPipelineMode ( PGconn conn)

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

3040 {
3041  if (!conn)
3042  return 0;
3043 
3045  (conn->asyncStatus == PGASYNC_IDLE ||
3047  conn->cmd_queue_head == NULL)
3048  return 1;
3049 
3050  switch (conn->asyncStatus)
3051  {
3052  case PGASYNC_READY:
3053  case PGASYNC_READY_MORE:
3054  /* there are some uncollected results */
3055  libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
3056  return 0;
3057 
3058  case PGASYNC_BUSY:
3059  libpq_append_conn_error(conn, "cannot exit pipeline mode while busy");
3060  return 0;
3061 
3062  case PGASYNC_IDLE:
3063  case PGASYNC_PIPELINE_IDLE:
3064  /* OK */
3065  break;
3066 
3067  case PGASYNC_COPY_IN:
3068  case PGASYNC_COPY_OUT:
3069  case PGASYNC_COPY_BOTH:
3070  libpq_append_conn_error(conn, "cannot exit pipeline mode while in COPY");
3071  }
3072 
3073  /* still work to process */
3074  if (conn->cmd_queue_head != NULL)
3075  {
3076  libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
3077  return 0;
3078  }
3079 
3082 
3083  /* Flush any pending data in out buffer */
3084  if (pqFlush(conn) < 0)
3085  return 0; /* error message is setup already */
3086  return 1;
3087 }
@ PGASYNC_COPY_OUT
Definition: libpq-int.h:229
@ PGASYNC_READY_MORE
Definition: libpq-int.h:225
@ PGASYNC_READY
Definition: libpq-int.h:223
@ PGASYNC_COPY_BOTH
Definition: libpq-int.h:230
@ PGASYNC_COPY_IN
Definition: libpq-int.h:228

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

3623 {
3624  if (!check_field_number(res, field_num))
3625  return 0;
3626  if (res->attDescs)
3627  return res->attDescs[field_num].format;
3628  else
3629  return 0;
3630 }
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3424

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

3656 {
3657  if (!check_field_number(res, field_num))
3658  return 0;
3659  if (res->attDescs)
3660  return res->attDescs[field_num].atttypmod;
3661  else
3662  return 0;
3663 }
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 2946 of file fe-exec.c.

2953 {
2954  *result_len = 0;
2955 
2956  if (!conn)
2957  return NULL;
2958 
2959  /*
2960  * Since this is the beginning of a query cycle, reset the error state.
2961  * However, in pipeline mode with something already queued, the error
2962  * buffer belongs to that command and we shouldn't clear it.
2963  */
2964  if (conn->cmd_queue_head == NULL)
2966 
2968  {
2969  libpq_append_conn_error(conn, "%s not allowed in pipeline mode", "PQfn");
2970  return NULL;
2971  }
2972 
2975  {
2976  libpq_append_conn_error(conn, "connection in wrong state");
2977  return NULL;
2978  }
2979 
2980  return pqFunctionCall3(conn, fnid,
2981  result_buf, result_len,
2982  result_is_int,
2983  args, nargs);
2984 }
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:882
#define PGINVALID_SOCKET
Definition: port.h:31
pgsocket sock
Definition: libpq-int.h:459

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

3504 {
3505  char *field_case;
3506  bool in_quotes;
3507  bool all_lower = true;
3508  const char *iptr;
3509  char *optr;
3510  int i;
3511 
3512  if (!res)
3513  return -1;
3514 
3515  /*
3516  * Note: it is correct to reject a zero-length input string; the proper
3517  * input to match a zero-length field name would be "".
3518  */
3519  if (field_name == NULL ||
3520  field_name[0] == '\0' ||
3521  res->attDescs == NULL)
3522  return -1;
3523 
3524  /*
3525  * Check if we can avoid the strdup() and related work because the
3526  * passed-in string wouldn't be changed before we do the check anyway.
3527  */
3528  for (iptr = field_name; *iptr; iptr++)
3529  {
3530  char c = *iptr;
3531 
3532  if (c == '"' || c != pg_tolower((unsigned char) c))
3533  {
3534  all_lower = false;
3535  break;
3536  }
3537  }
3538 
3539  if (all_lower)
3540  for (i = 0; i < res->numAttributes; i++)
3541  if (strcmp(field_name, res->attDescs[i].name) == 0)
3542  return i;
3543 
3544  /* Fall through to the normal check if that didn't work out. */
3545 
3546  /*
3547  * Note: this code will not reject partially quoted strings, eg
3548  * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
3549  * condition.
3550  */
3551  field_case = strdup(field_name);
3552  if (field_case == NULL)
3553  return -1; /* grotty */
3554 
3555  in_quotes = false;
3556  optr = field_case;
3557  for (iptr = field_case; *iptr; iptr++)
3558  {
3559  char c = *iptr;
3560 
3561  if (in_quotes)
3562  {
3563  if (c == '"')
3564  {
3565  if (iptr[1] == '"')
3566  {
3567  /* doubled quotes become a single quote */
3568  *optr++ = '"';
3569  iptr++;
3570  }
3571  else
3572  in_quotes = false;
3573  }
3574  else
3575  *optr++ = c;
3576  }
3577  else if (c == '"')
3578  in_quotes = true;
3579  else
3580  {
3581  c = pg_tolower((unsigned char) c);
3582  *optr++ = c;
3583  }
3584  }
3585  *optr = '\0';
3586 
3587  for (i = 0; i < res->numAttributes; i++)
3588  {
3589  if (strcmp(field_case, res->attDescs[i].name) == 0)
3590  {
3591  free(field_case);
3592  return i;
3593  }
3594  }
3595  free(field_case);
3596  return -1;
3597 }
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(), get_template0_info(), 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 3963 of file fe-exec.c.

3964 {
3965  PQfreemem(notify);
3966 }
void PQfreemem(void *ptr)
Definition: fe-exec.c:3946

References PQfreemem().

◆ PQfsize()

int PQfsize ( const PGresult res,
int  field_num 
)

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

3645 {
3646  if (!check_field_number(res, field_num))
3647  return 0;
3648  if (res->attDescs)
3649  return res->attDescs[field_num].typlen;
3650  else
3651  return 0;
3652 }

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

3601 {
3602  if (!check_field_number(res, field_num))
3603  return InvalidOid;
3604  if (res->attDescs)
3605  return res->attDescs[field_num].tableid;
3606  else
3607  return InvalidOid;
3608 }
#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 3611 of file fe-exec.c.

3612 {
3613  if (!check_field_number(res, field_num))
3614  return 0;
3615  if (res->attDescs)
3616  return res->attDescs[field_num].columnid;
3617  else
3618  return 0;
3619 }
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 2782 of file fe-exec.c.

2783 {
2784  *buffer = NULL; /* for all failure cases */
2785  if (!conn)
2786  return -2;
2787  if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2789  {
2790  libpq_append_conn_error(conn, "no COPY in progress");
2791  return -2;
2792  }
2793  return pqGetCopyData3(conn, buffer, async);
2794 }
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 3815 of file fe-exec.c.

3816 {
3817  if (!check_tuple_field_number(res, tup_num, field_num))
3818  return 1; /* pretend it is null */
3819  if (res->tuples[tup_num][field_num].len == NULL_LEN)
3820  return 1;
3821  else
3822  return 0;
3823 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3439
#define NULL_LEN
Definition: libpq-int.h:136

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_template0_info(), getAggregates(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getLOs(), getNamespaces(), getPolicies(), getProcLangs(), getPublicationTables(), GetSlotInformation(), getSubscriptions(), getTableAttrs(), 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 3801 of file fe-exec.c.

3802 {
3803  if (!check_tuple_field_number(res, tup_num, field_num))
3804  return 0;
3805  if (res->tuples[tup_num][field_num].len != NULL_LEN)
3806  return res->tuples[tup_num][field_num].len;
3807  else
3808  return 0;
3809 }

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

2821 {
2822  if (!buffer || length <= 0)
2823  return EOF;
2824  *buffer = '\0';
2825  /* length must be at least 3 to hold the \. terminator! */
2826  if (length < 3)
2827  return EOF;
2828 
2829  if (!conn)
2830  return EOF;
2831 
2832  return pqGetline3(conn, buffer, length);
2833 }
int pqGetline3(PGconn *conn, char *s, int maxlen)

References conn, and pqGetline3().

◆ PQgetlineAsync()

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

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

2868 {
2869  if (!conn)
2870  return -1;
2871 
2872  return pqGetlineAsync3(conn, buffer, bufsize);
2873 }
int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)
#define bufsize
Definition: indent_globs.h:36

References bufsize, conn, and pqGetlineAsync3().

Referenced by pqGetline3().

◆ PQgetResult()

PGresult* PQgetResult ( PGconn conn)

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

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

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

3791 {
3792  if (!check_tuple_field_number(res, tup_num, field_num))
3793  return NULL;
3794  return res->tuples[tup_num][field_num].value;
3795 }

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(), get_template0_info(), 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(), getPartitioningInfo(), 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(), postgresGetAnalyzeInfoForForeignTable(), 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:155
void * noticeRecArg
Definition: libpq-int.h:156
char * errMsg
Definition: libpq-int.h:199

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

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

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

3898 {
3899  if (!conn || conn->status == CONNECTION_BAD)
3900  return false;
3901  return pqIsnonblocking(conn);
3902 }

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

3907 {
3908  return true;
3909 }

◆ 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
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
void * noticeProcArg
Definition: libpq-int.h:158
PQnoticeProcessor noticeProc
Definition: libpq-int.h:157
PQExpBufferData errorMessage
Definition: libpq-int.h:617
int nEvents
Definition: libpq-int.h:421
PGNoticeHooks noticeHooks
Definition: libpq-int.h:417
PGEvent * events
Definition: libpq-int.h:420
int curOffset
Definition: libpq-int.h:212
char null_field[1]
Definition: libpq-int.h:204
int spaceLeft
Definition: libpq-int.h:213
char * errQuery
Definition: libpq-int.h:201

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, 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 2633 of file fe-exec.c.

2634 {
2635  PGnotify *event;
2636 
2637  if (!conn)
2638  return NULL;
2639 
2640  /* Parse any available data to see if we can extract NOTIFY messages. */
2641  parseInput(conn);
2642 
2643  event = conn->notifyHead;
2644  if (event)
2645  {
2646  conn->notifyHead = event->next;
2647  if (!conn->notifyHead)
2648  conn->notifyTail = NULL;
2649  event->next = NULL; /* don't let app see the internal state */
2650  }
2651  return event;
2652 }
struct pgNotify * next
Definition: libpq-fe.h:193
PGnotify * notifyHead
Definition: libpq-int.h:436
PGnotify * notifyTail
Definition: libpq-int.h:437

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

3830 {
3831  if (!res)
3832  return 0;
3833  return res->numParameters;
3834 }

References pg_result::numParameters, and res.

◆ PQntuples()

int PQntuples ( const PGresult res)

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

3396 {
3397  if (!res)
3398  return 0;
3399  return res->ntups;
3400 }

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(), ExecQueryAndProcessResults(), 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(), get_template0_info(), getAccessMethods(), getAdditionalACLs(), getAggregates(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getIndexes(), getInherits(), getLOs(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPartitioningInfo(), 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(), postgresGetAnalyzeInfoForForeignTable(), 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 3679 of file fe-exec.c.

3680 {
3681  /*
3682  * This must be enough to hold the result. Don't laugh, this is better
3683  * than what this function used to do.
3684  */
3685  static char buf[24];
3686 
3687  size_t len;
3688 
3689  if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
3690  return "";
3691 
3692  len = strspn(res->cmdStatus + 7, "0123456789");
3693  if (len > sizeof(buf) - 1)
3694  len = sizeof(buf) - 1;
3695  memcpy(buf, res->cmdStatus + 7, len);
3696  buf[len] = '\0';
3697 
3698  return buf;
3699 }
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 3707 of file fe-exec.c.

3708 {
3709  char *endptr = NULL;
3710  unsigned long result;
3711 
3712  if (!res ||
3713  strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
3714  res->cmdStatus[7] < '0' ||
3715  res->cmdStatus[7] > '9')
3716  return InvalidOid;
3717 
3718  result = strtoul(res->cmdStatus + 7, &endptr, 10);
3719 
3720  if (!endptr || (*endptr != ' ' && *endptr != '\0'))
3721  return InvalidOid;
3722  else
3723  return (Oid) result;
3724 }
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 3840 of file fe-exec.c.

3841 {
3842  if (!check_param_number(res, param_num))
3843  return InvalidOid;
3844  if (res->paramDescs)
3845  return res->paramDescs[param_num].typid;
3846  else
3847  return InvalidOid;
3848 }
static int check_param_number(const PGresult *res, int param_num)
Definition: fe-exec.c:3462

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

◆ pqPipelineFlush()

static int pqPipelineFlush ( PGconn conn)
static

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

3931 {
3932  if ((conn->pipelineStatus != PQ_PIPELINE_ON) ||
3934  return pqFlush(conn);
3935  return 0;
3936 }
#define OUTBUFFER_THRESHOLD
Definition: libpq-int.h:894
int outCount
Definition: libpq-int.h:517

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

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

◆ pqPipelineProcessQueue()

static void pqPipelineProcessQueue ( PGconn conn)
static

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

3121 {
3122  switch (conn->asyncStatus)
3123  {
3124  case PGASYNC_COPY_IN:
3125  case PGASYNC_COPY_OUT:
3126  case PGASYNC_COPY_BOTH:
3127  case PGASYNC_READY:
3128  case PGASYNC_READY_MORE:
3129  case PGASYNC_BUSY:
3130  /* client still has to process current query or results */
3131  return;
3132 
3133  case PGASYNC_IDLE:
3134 
3135  /*
3136  * If we're in IDLE mode and there's some command in the queue,
3137  * get us into PIPELINE_IDLE mode and process normally. Otherwise
3138  * there's nothing for us to do.
3139  */
3140  if (conn->cmd_queue_head != NULL)
3141  {
3143  break;
3144  }
3145  return;
3146 
3147  case PGASYNC_PIPELINE_IDLE:
3149  /* next query please */
3150  break;
3151  }
3152 
3153  /*
3154  * Reset single-row processing mode. (Client has to set it up for each
3155  * query, if desired.)
3156  */
3157  conn->singleRowMode = false;
3158 
3159  /*
3160  * If there are no further commands to process in the queue, get us in
3161  * "real idle" mode now.
3162  */
3163  if (conn->cmd_queue_head == NULL)
3164  {
3166  return;
3167  }
3168 
3169  /*
3170  * Reset the error state. This and the next couple of steps correspond to
3171  * what PQsendQueryStart didn't do for this query.
3172  */
3174 
3175  /* Initialize async result-accumulation state */
3177 
3180  {
3181  /*
3182  * In an aborted pipeline we don't get anything from the server for
3183  * each result; we're just discarding commands from the queue until we
3184  * get to the next sync from the server.
3185  *
3186  * The PGRES_PIPELINE_ABORTED results tell the client that its queries
3187  * got aborted.
3188  */
3190  if (!conn->result)
3191  {
3192  libpq_append_conn_error(conn, "out of memory");
3194  return;
3195  }
3197  }
3198  else
3199  {
3200  /* allow parsing to continue */
3202  }
3203 }
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:776
@ PGRES_PIPELINE_ABORTED
Definition: libpq-fe.h:112
@ PGQUERY_SYNC
Definition: libpq-int.h:324
bool singleRowMode
Definition: libpq-int.h:433

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

3227 {
3228  PGcmdQueueEntry *entry;
3229 
3230  if (!conn)
3231  return 0;
3232 
3234  {
3235  libpq_append_conn_error(conn, "cannot send pipeline when not in pipeline mode");
3236  return 0;
3237  }
3238 
3239  switch (conn->asyncStatus)
3240  {
3241  case PGASYNC_COPY_IN:
3242  case PGASYNC_COPY_OUT:
3243  case PGASYNC_COPY_BOTH:
3244  /* should be unreachable */
3246  "internal error: cannot send pipeline while in COPY\n");
3247  return 0;
3248  case PGASYNC_READY:
3249  case PGASYNC_READY_MORE:
3250  case PGASYNC_BUSY:
3251  case PGASYNC_IDLE:
3252  case PGASYNC_PIPELINE_IDLE:
3253  /* OK to send sync */
3254  break;
3255  }
3256 
3257  entry = pqAllocCmdQueueEntry(conn);
3258  if (entry == NULL)
3259  return 0; /* error msg already set */
3260 
3261  entry->queryclass = PGQUERY_SYNC;
3262  entry->query = NULL;
3263 
3264  /* construct the Sync message */
3265  if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
3266  pqPutMsgEnd(conn) < 0)
3267  goto sendFailed;
3268 
3269  /*
3270  * Give the data a push. In nonblock mode, don't complain if we're unable
3271  * to send it all; PQgetResult() will do any additional flushing needed.
3272  */
3273  if (PQflush(conn) < 0)
3274  goto sendFailed;
3275 
3276  /* OK, it's launched! */
3277  pqAppendCmdQueueEntry(conn, entry);
3278 
3279  return 1;
3280 
3281 sendFailed:
3282  pqRecycleCmdQueueEntry(conn, entry);
3283  /* error message should be set up already */
3284  return 0;
3285 }
int PQflush(PGconn *conn)
Definition: fe-exec.c:3914
static void pqAppendCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1345
static PGcmdQueueEntry * pqAllocCmdQueueEntry(PGconn *conn)
Definition: fe-exec.c:1312
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
#define PqMsg_Sync
Definition: protocol.h:27

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(), PqMsg_Sync, 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 2272 of file fe-exec.c.

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

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

Referenced by DescribeQuery(), init_libpq_conn(), main(), prepare_common(), prepareCommand(), 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:1255
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:108
int errorReported
Definition: libpq-int.h:618

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

2662 {
2663  if (!conn)
2664  return -1;
2665  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2667  {
2668  libpq_append_conn_error(conn, "no COPY in progress");
2669  return -1;
2670  }
2671 
2672  /*
2673  * Process any NOTICE or NOTIFY messages that might be pending in the
2674  * input buffer. Since the server might generate many notices during the
2675  * COPY, we want to clean those out reasonably promptly to prevent
2676  * indefinite expansion of the input buffer. (Note: the actual read of
2677  * input data into the input buffer happens down inside pqSendSome, but
2678  * it's not authorized to get rid of the data again.)
2679  */
2680  parseInput(conn);
2681 
2682  if (nbytes > 0)
2683  {
2684  /*
2685  * Try to flush any previously sent data in preference to growing the
2686  * output buffer. If we can't enlarge the buffer enough to hold the
2687  * data, return 0 in the nonblock case, else hard error. (For
2688  * simplicity, always assume 5 bytes of overhead.)
2689  */
2690  if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2691  {
2692  if (pqFlush(conn) < 0)
2693  return -1;
2694  if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2695  conn))
2696  return pqIsnonblocking(conn) ? 0 : -1;
2697  }
2698  /* Send the data (too simple to delegate to fe-protocol files) */
2699  if (pqPutMsgStart(PqMsg_CopyData, conn) < 0 ||
2700  pqPutnchar(buffer, nbytes, conn) < 0 ||
2701  pqPutMsgEnd(conn) < 0)
2702  return -1;
2703  }
2704  return 1;
2705 }
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
#define PqMsg_CopyData
Definition: protocol.h:65
int outBufSize
Definition: libpq-int.h:516

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, PqMsg_CopyData, pqPutMsgEnd(), pqPutMsgStart(), and pqPutnchar().

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

◆ PQputCopyEnd()

int PQputCopyEnd ( PGconn conn,
const char *  errormsg 
)

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

2716 {
2717  if (!conn)
2718  return -1;
2719  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2721  {
2722  libpq_append_conn_error(conn, "no COPY in progress");
2723  return -1;
2724  }
2725 
2726  /*
2727  * Send the COPY END indicator. This is simple enough that we don't
2728  * bother delegating it to the fe-protocol files.
2729  */
2730  if (errormsg)
2731  {
2732  /* Send COPY FAIL */
2733  if (pqPutMsgStart(PqMsg_CopyFail, conn) < 0 ||
2734  pqPuts(errormsg, conn) < 0 ||
2735  pqPutMsgEnd(conn) < 0)
2736  return -1;
2737  }
2738  else
2739  {
2740  /* Send COPY DONE */
2741  if (pqPutMsgStart(PqMsg_CopyDone, conn) < 0 ||
2742  pqPutMsgEnd(conn) < 0)
2743  return -1;
2744  }
2745 
2746  /*
2747  * If we sent the COPY command in extended-query mode, we must issue a
2748  * Sync as well.
2749  */
2750  if (conn->cmd_queue_head &&
2752  {
2753  if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
2754  pqPutMsgEnd(conn) < 0)
2755  return -1;
2756  }
2757 
2758  /* Return to active duty */
2761  else
2763 
2764  /* Try to flush data */
2765  if (pqFlush(conn) < 0)
2766  return -1;
2767 
2768  return 1;
2769 }
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:153
#define PqMsg_CopyDone
Definition: protocol.h:64
#define PqMsg_CopyFail
Definition: protocol.h:29

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(), PqMsg_CopyDone, PqMsg_CopyFail, PqMsg_Sync, 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 2884 of file fe-exec.c.

2885 {
2886  return PQputnbytes(conn, string, strlen(string));
2887 }
int PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2894

References conn, and PQputnbytes().

Referenced by initPopulateTable().

◆ PQputnbytes()

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

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

2895 {
2896  if (PQputCopyData(conn, buffer, nbytes) > 0)
2897  return 0;
2898  else
2899  return EOF;
2900 }
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2661

References conn, and PQputCopyData().

Referenced by PQputline().

◆ pqRecycleCmdQueueEntry()

static void pqRecycleCmdQueueEntry ( PGconn conn,
PGcmdQueueEntry entry 
)
static

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

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

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

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

◆ PQresStatus()

char* PQresStatus ( ExecStatusType  status)

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

3334 {
3335  if ((unsigned int) status >= lengthof(pgresStatus))
3336  return libpq_gettext("invalid ExecStatusType code");
3337  return pgresStatus[status];
3338 }
#define lengthof(array)
Definition: c.h:777
char *const pgresStatus[]
Definition: fe-exec.c:32

References lengthof, libpq_gettext, and pgresStatus.

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:104
char space[1]
Definition: libpq-int.h:109

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

3381 {
3382  PGMessageField *pfield;
3383 
3384  if (!res)
3385  return NULL;
3386  for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
3387  {
3388  if (pfield->code == fieldcode)
3389  return pfield->contents;
3390  }
3391  return NULL;
3392 }
struct pgMessageField * next
Definition: libpq-int.h:147
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:149

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

3326 {
3327  if (!res)
3328  return PGRES_FATAL_ERROR;
3329  return res->resultStatus;
3330 }

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(), initPopulateTable(), 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_end(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresGetAnalyzeInfoForForeignTable(), postgresImportForeignSchema(), postgresReScanForeignScan(), PQconnectPoll(), PQencryptPasswordConn(), prepare_foreign_modify(), prepareCommand(), PrintQueryResult(), PrintResultInCrosstab(), process_queued_fetch_requests(), process_result(), readCommandResponse(), ReceiveCopyData(), ReceiveXlogStream(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_permutation(), run_simple_command(), run_simple_query(), RunIdentifySystem(), 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 3349 of file fe-exec.c.

3352 {
3353  PQExpBufferData workBuf;
3354 
3355  /*
3356  * Because the caller is expected to free the result string, we must
3357  * strdup any constant result. We use plain strdup and document that
3358  * callers should expect NULL if out-of-memory.
3359  */
3360  if (!res ||
3363  return strdup(libpq_gettext("PGresult is not an error result\n"));
3364 
3365  initPQExpBuffer(&workBuf);
3366 
3367  pqBuildErrorMessage3(&workBuf, res, verbosity, show_context);
3368 
3369  /* If insufficient memory to format the message, fail cleanly */
3370  if (PQExpBufferDataBroken(workBuf))
3371  {
3372  termPQExpBuffer(&workBuf);
3373  return strdup(libpq_gettext("out of memory\n"));
3374  }
3375 
3376  return workBuf.data;
3377 }
void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
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 1206 of file fe-exec.c.

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

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  else if (strcmp(name, "scram_iterations") == 0)
1185  {
1187  }
1188 }
int pg_char_to_encoding(const char *name)
Definition: encnames.c:550
struct pgParameterStatus pgParameterStatus
@ PG_BOOL_YES
Definition: libpq-int.h:257
@ PG_BOOL_NO
Definition: libpq-int.h:258
struct pgParameterStatus * next
Definition: libpq-int.h:271
PGTernaryBool in_hot_standby
Definition: libpq-int.h:500
PGTernaryBool default_transaction_read_only
Definition: libpq-int.h:499
pgParameterStatus * pstatus
Definition: libpq-int.h:496
int scram_sha_256_iterations
Definition: libpq-int.h:544

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, pg_conn::scram_sha_256_iterations, 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:471

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

Referenced by PQgetResult().

◆ PQsendClosePortal()

int PQsendClosePortal ( PGconn conn,
const char *  portal 
)

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

2536 {
2537  return PQsendTypedCommand(conn, PqMsg_Close, 'P', portal);
2538 }

References conn, PqMsg_Close, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQsendClosePrepared()

int PQsendClosePrepared ( PGconn conn,
const char *  stmt 
)

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

2523 {
2524  return PQsendTypedCommand(conn, PqMsg_Close, 'S', stmt);
2525 }

References conn, PqMsg_Close, PQsendTypedCommand(), and stmt.

Referenced by test_prepared().

◆ PQsendDescribePortal()

int PQsendDescribePortal ( PGconn conn,
const char *  portal 
)

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

2471 {
2472  return PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal);
2473 }

References conn, PqMsg_Describe, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQsendDescribePrepared()

int PQsendDescribePrepared ( PGconn conn,
const char *  stmt 
)

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

2458 {
2459  return PQsendTypedCommand(conn, PqMsg_Describe, 'S', stmt);
2460 }

References conn, PqMsg_Describe, PQsendTypedCommand(), and stmt.

Referenced by test_prepared().

◆ PQsendFlushRequest()

int PQsendFlushRequest ( PGconn conn)

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

3294 {
3295  if (!conn)
3296  return 0;
3297 
3298  /* Don't try to send if we know there's no live connection. */
3299  if (conn->status != CONNECTION_OK)
3300  {
3301  libpq_append_conn_error(conn, "no connection to the server");
3302  return 0;
3303  }
3304 
3305  /* Can't send while already busy, either, unless enqueuing for later */
3306  if (conn->asyncStatus != PGASYNC_IDLE &&
3308  {
3309  libpq_append_conn_error(conn, "another command is already in progress");
3310  return 0;
3311  }
3312 
3313  if (pqPutMsgStart(PqMsg_Flush, conn) < 0 ||
3314  pqPutMsgEnd(conn) < 0)
3315  {
3316  return 0;
3317  }
3318 
3319  return 1;
3320 }
#define PqMsg_Flush
Definition: protocol.h:24

References pg_conn::asyncStatus, conn, CONNECTION_OK, libpq_append_conn_error(), PGASYNC_IDLE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, PqMsg_Flush, 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 1542 of file fe-exec.c.

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

References conn, i, libpq_append_conn_error(), PGQUERY_PREPARE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, PQ_QUERY_PARAM_MAX_LIMIT, pqAllocCmdQueueEntry(), pqAppendCmdQueueEntry(), PqMsg_Parse, PqMsg_Sync, pqPipelineFlush(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), pqRecycleCmdQueueEntry(), PQsendQueryStart(), PGcmdQueueEntry::query, and PGcmdQueueEntry::queryclass.

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

◆ PQsendQuery()

◆ PQsendQueryContinue()

int PQsendQueryContinue ( PGconn conn,
const char *  query 
)

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

1429 {
1430  return PQsendQueryInternal(conn, query, false);
1431 }

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

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

References conn, i, libpq_append_conn_error(), PGQUERY_EXTENDED, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqAllocCmdQueueEntry(), pqAppendCmdQueueEntry(), PqMsg_Bind, PqMsg_Describe, PqMsg_Execute, PqMsg_Parse, PqMsg_Sync, 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 1434 of file fe-exec.c.

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

References conn, libpq_append_conn_error(), PGQUERY_SIMPLE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqAllocCmdQueueEntry(), pqAppendCmdQueueEntry(), pqFlush(), PqMsg_Query, 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 1498 of file fe-exec.c.

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

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

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

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

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

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 PQsendPrepare(), PQsendQueryInternal(), PQsendQueryParams(), PQsendQueryPrepared(), and PQsendTypedCommand().

◆ PQsendTypedCommand()

static int PQsendTypedCommand ( PGconn conn,
char  command,
char  type,
const char *  target 
)
static

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

2556 {
2557  PGcmdQueueEntry *entry = NULL;
2558 
2559  /* Treat null target as empty string */
2560  if (!target)
2561  target = "";
2562 
2563  if (!PQsendQueryStart(conn, true))
2564  return 0;
2565 
2566  entry = pqAllocCmdQueueEntry(conn);
2567  if (entry == NULL)
2568  return 0; /* error msg already set */
2569 
2570  /* construct the Close message */
2571  if (pqPutMsgStart(command, conn) < 0 ||
2572  pqPutc(type, conn) < 0 ||
2573  pqPuts(target, conn) < 0 ||
2574  pqPutMsgEnd(conn) < 0)
2575  goto sendFailed;
2576 
2577  /* construct the Sync message */
2579  {
2580  if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
2581  pqPutMsgEnd(conn) < 0)
2582  goto sendFailed;
2583  }
2584 
2585  /* remember if we are doing a Close or a Describe */
2586  if (command == PqMsg_Close)
2587  {
2588  entry->queryclass = PGQUERY_CLOSE;
2589  }
2590  else if (command == PqMsg_Describe)
2591  {
2592  entry->queryclass = PGQUERY_DESCRIBE;
2593  }
2594  else
2595  {
2596  libpq_append_conn_error(conn, "unknown command type provided");
2597  goto sendFailed;
2598  }
2599 
2600  /*
2601  * Give the data a push (in pipeline mode, only if we're past the size
2602  * threshold). In nonblock mode, don't complain if we're unable to send
2603  * it all; PQgetResult() will do any additional flushing needed.
2604  */
2605  if (pqPipelineFlush(conn) < 0)
2606  goto sendFailed;
2607 
2608  /* OK, it's launched! */
2609  pqAppendCmdQueueEntry(conn, entry);
2610 
2611  return 1;
2612 
2613 sendFailed:
2614  pqRecycleCmdQueueEntry(conn, entry);
2615  /* error message should be set up already */
2616  return 0;
2617 }
@ PGQUERY_DESCRIBE
Definition: libpq-int.h:323
@ PGQUERY_CLOSE
Definition: libpq-int.h:325
const char * type

References conn, libpq_append_conn_error(), PGQUERY_CLOSE, PGQUERY_DESCRIBE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqAllocCmdQueueEntry(), pqAppendCmdQueueEntry(), PqMsg_Close, PqMsg_Describe, PqMsg_Sync, pqPipelineFlush(), pqPutc(), pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), pqRecycleCmdQueueEntry(), PQsendQueryStart(), PGcmdQueueEntry::queryclass, and type.

Referenced by PQclosePortal(), PQclosePrepared(), PQdescribePortal(), PQdescribePrepared(), PQsendClosePortal(), PQsendClosePrepared(), PQsendDescribePortal(), and PQsendDescribePrepared().

◆ PQsetnonblocking()

int PQsetnonblocking ( PGconn conn,
int  arg 
)

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

3859 {
3860  bool barg;
3861 
3862  if (!conn || conn->status == CONNECTION_BAD)
3863  return -1;
3864 
3865  barg = (arg ? true : false);
3866 
3867  /* early out if the socket is already in the state requested */
3868  if (barg == conn->nonblocking)
3869  return 0;
3870 
3871  /*
3872  * to guarantee constancy for flushing/query/result-polling behavior we
3873  * need to flush the send queue at this point in order to guarantee proper
3874  * behavior. this is ok because either they are making a transition _from_
3875  * or _to_ blocking mode, either way we can block them.
3876  *
3877  * Clear error state in case pqFlush adds to it, unless we're actively
3878  * pipelining, in which case it seems best not to.
3879  */
3880  if (