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 pqPipelineSyncInternal (PGconn *conn, bool immediate_flush)
 
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, bool isReadyForQuery, bool gotSync)
 
int PQpipelineSync (PGconn *conn)
 
int PQsendPipelineSync (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 4437 of file fe-exec.c.

◆ ISOCTDIGIT

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

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

◆ OCTVAL

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

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

◆ PGRESULT_ALIGN_BOUNDARY

#define PGRESULT_ALIGN_BOUNDARY   MAXIMUM_ALIGNOF /* from configure */

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

◆ PGRESULT_BLOCK_OVERHEAD

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

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

◆ PGRESULT_DATA_BLOCKSIZE

#define PGRESULT_DATA_BLOCKSIZE   2048

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

◆ PGRESULT_SEP_ALLOC_THRESHOLD

#define PGRESULT_SEP_ALLOC_THRESHOLD   (PGRESULT_DATA_BLOCKSIZE / 2)

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

3471 {
3472  if (!res)
3473  return false; /* no way to display error message... */
3474  if (field_num < 0 || field_num >= res->numAttributes)
3475  {
3477  "column number %d is out of range 0..%d",
3478  field_num, res->numAttributes - 1);
3479  return false;
3480  }
3481  return true;
3482 }
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:936
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 3508 of file fe-exec.c.

3509 {
3510  if (!res)
3511  return false; /* no way to display error message... */
3512  if (param_num < 0 || param_num >= res->numParameters)
3513  {
3515  "parameter number %d is out of range 0..%d",
3516  param_num, res->numParameters - 1);
3517  return false;
3518  }
3519 
3520  return true;
3521 }
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 3485 of file fe-exec.c.

3487 {
3488  if (!res)
3489  return false; /* no way to display error message... */
3490  if (tup_num < 0 || tup_num >= res->ntups)
3491  {
3493  "row number %d is out of range 0..%d",
3494  tup_num, res->ntups - 1);
3495  return false;
3496  }
3497  if (field_num < 0 || field_num >= res->numAttributes)
3498  {
3500  "column number %d is out of range 0..%d",
3501  field_num, res->numAttributes - 1);
3502  return false;
3503  }
3504  return true;
3505 }
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 406 of file fe-exec.c.

407 {
408  PGEvent *newEvents;
409  size_t msize;
410  int i;
411 
412  if (!events || count <= 0)
413  return NULL;
414 
415  msize = count * sizeof(PGEvent);
416  newEvents = (PGEvent *) malloc(msize);
417  if (!newEvents)
418  return NULL;
419 
420  for (i = 0; i < count; i++)
421  {
422  newEvents[i].proc = events[i].proc;
423  newEvents[i].passThrough = events[i].passThrough;
424  newEvents[i].data = NULL;
425  newEvents[i].resultInitialized = false;
426  newEvents[i].name = strdup(events[i].name);
427  if (!newEvents[i].name)
428  {
429  while (--i >= 0)
430  free(newEvents[i].name);
431  free(newEvents);
432  return NULL;
433  }
434  msize += strlen(events[i].name) + 1;
435  }
436 
437  *memSize += msize;
438  return newEvents;
439 }
#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 4290 of file fe-exec.c.

4291 {
4292  int res = -1;
4293 
4294  if (c > 0 && c < 127)
4295  res = hexlookup[(unsigned char) c];
4296 
4297  return (char) res;
4298 }
static const int8 hexlookup[128]
Definition: fe-exec.c:4278
char * c

References hexlookup, and res.

Referenced by PQunescapeBytea().

◆ getCopyResult()

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

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

2187 {
2188  /*
2189  * If the server connection has been lost, don't pretend everything is
2190  * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
2191  * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
2192  * error in the earlier steps in PQgetResult). The text returned in the
2193  * result is whatever is in conn->errorMessage; we hope that was filled
2194  * with something relevant when the lost connection was detected.
2195  */
2196  if (conn->status != CONNECTION_OK)
2197  {
2200  return pqPrepareAsyncResult(conn);
2201  }
2202 
2203  /* If we have an async result for the COPY, return that */
2204  if (conn->result && conn->result->resultStatus == copytype)
2205  return pqPrepareAsyncResult(conn);
2206 
2207  /* Otherwise, invent a suitable PGresult */
2208  return PQmakeEmptyPGresult(conn, copytype);
2209 }
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:801
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:158
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:849
@ 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:541
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:430
ConnStatusType status
Definition: libpq-int.h:429
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 1996 of file fe-exec.c.

1997 {
1999 }
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 991 of file fe-exec.c.

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

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

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

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

◆ pqAppendCmdQueueEntry()

static void pqAppendCmdQueueEntry ( PGconn conn,
PGcmdQueueEntry entry 
)
static

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

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

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

◆ PQbinaryTuples()

int PQbinaryTuples ( const PGresult res)

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

3458 {
3459  if (!res)
3460  return 0;
3461  return res->binary;
3462 }
int binary
Definition: libpq-int.h:182

References pg_result::binary, and res.

Referenced by HandleCopyResult().

◆ PQclear()

void PQclear ( PGresult res)

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

720 {
721  PGresult_data *block;
722  int i;
723 
724  /* As a convenience, do nothing for a NULL pointer */
725  if (!res)
726  return;
727  /* Also, do nothing if the argument is OOM_result */
728  if ((const PGresult *) res == &OOM_result)
729  return;
730 
731  /* Close down any events we may have */
732  for (i = 0; i < res->nEvents; i++)
733  {
734  /* only send DESTROY to successfully-initialized event procs */
736  {
738 
739  evt.result = res;
740  (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
741  res->events[i].passThrough);
742  }
743  free(res->events[i].name);
744  }
745 
746  free(res->events);
747 
748  /* Free all the subsidiary blocks */
749  while ((block = res->curBlock) != NULL)
750  {
751  res->curBlock = block->next;
752  free(block);
753  }
754 
755  /* Free the top-level tuple pointer array */
756  free(res->tuples);
757 
758  /* zero out the pointer fields to catch programming errors */
759  res->attDescs = NULL;
760  res->tuples = NULL;
761  res->paramDescs = NULL;
762  res->errFields = NULL;
763  res->events = NULL;
764  res->nEvents = 0;
765  /* res->curBlock was zeroed out earlier */
766 
767  /* Free the PGresult structure itself */
768  free(res);
769 }
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 777 of file fe-exec.c.

778 {
779  PQclear(conn->result);
780  conn->result = NULL;
781  conn->error_result = false;
783  conn->next_result = NULL;
784 }
void PQclear(PGresult *res)
Definition: fe-exec.c:719
PGresult * next_result
Definition: libpq-int.h:543
bool error_result
Definition: libpq-int.h:542

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

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

◆ PQclosePortal()

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

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

2502 {
2503  if (!PQexecStart(conn))
2504  return NULL;
2505  if (!PQsendTypedCommand(conn, PqMsg_Close, 'P', portal))
2506  return NULL;
2507  return PQexecFinish(conn);
2508 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2372
static int PQsendTypedCommand(PGconn *conn, char command, char type, const char *target)
Definition: fe-exec.c:2551
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2306
#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 2483 of file fe-exec.c.

2484 {
2485  if (!PQexecStart(conn))
2486  return NULL;
2487  if (!PQsendTypedCommand(conn, PqMsg_Close, 'S', stmt))
2488  return NULL;
2489  return PQexecFinish(conn);
2490 }
#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 3712 of file fe-exec.c.

3713 {
3714  if (!res)
3715  return NULL;
3716  return res->cmdStatus;
3717 }
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 3782 of file fe-exec.c.

3783 {
3784  char *p,
3785  *c;
3786 
3787  if (!res)
3788  return "";
3789 
3790  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3791  {
3792  p = res->cmdStatus + 7;
3793  /* INSERT: skip oid and space */
3794  while (*p && *p != ' ')
3795  p++;
3796  if (*p == 0)
3797  goto interpret_error; /* no space? */
3798  p++;
3799  }
3800  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3801  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3802  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3803  p = res->cmdStatus + 7;
3804  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0 ||
3805  strncmp(res->cmdStatus, "MERGE ", 6) == 0)
3806  p = res->cmdStatus + 6;
3807  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3808  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3809  p = res->cmdStatus + 5;
3810  else
3811  return "";
3812 
3813  /* check that we have an integer (at least one digit, nothing else) */
3814  for (c = p; *c; c++)
3815  {
3816  if (!isdigit((unsigned char) *c))
3817  goto interpret_error;
3818  }
3819  if (c == p)
3820  goto interpret_error;
3821 
3822  return p;
3823 
3824 interpret_error:
3826  "could not interpret result from server: %s",
3827  res->cmdStatus);
3828  return "";
3829 }

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,
bool  isReadyForQuery,
bool  gotSync 
)

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

3105 {
3106  PGcmdQueueEntry *prevquery;
3107 
3108  if (conn->cmd_queue_head == NULL)
3109  return;
3110 
3111  /*
3112  * If processing a query of simple query protocol, we only advance the
3113  * queue when we receive the ReadyForQuery message for it.
3114  */
3115  if (conn->cmd_queue_head->queryclass == PGQUERY_SIMPLE && !isReadyForQuery)
3116  return;
3117 
3118  /*
3119  * If we're waiting for a SYNC, don't advance the queue until we get one.
3120  */
3121  if (conn->cmd_queue_head->queryclass == PGQUERY_SYNC && !gotSync)
3122  return;
3123 
3124  /* delink element from queue */
3125  prevquery = conn->cmd_queue_head;
3127 
3128  /* If the queue is now empty, reset the tail too */
3129  if (conn->cmd_queue_head == NULL)
3130  conn->cmd_queue_tail = NULL;
3131 
3132  /* and make the queue element recyclable */
3133  prevquery->next = NULL;
3134  pqRecycleCmdQueueEntry(conn, prevquery);
3135 }
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1395
@ PGQUERY_SIMPLE
Definition: libpq-int.h:320
@ PGQUERY_SYNC
Definition: libpq-int.h:324
PGQueryClass queryclass
Definition: libpq-int.h:333

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

Referenced by PQgetResult(), and pqParseInput3().

◆ PQconsumeInput()

int PQconsumeInput ( PGconn conn)

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

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

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

Referenced by advanceConnectionState(), confirm_query_canceled_impl(), CopyStreamReceive(), dblink_get_notify(), dblink_is_busy(), do_sql_command_end(), ecpg_process_output(), libpqrcv_PQgetResult(), libpqrcv_receive(), libpqsrv_get_result(), main(), pgfdw_cancel_query_end(), pgfdw_exec_cleanup_query_end(), pgfdw_get_cleanup_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 316 of file fe-exec.c.

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

2437 {
2438  if (!PQexecStart(conn))
2439  return NULL;
2440  if (!PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal))
2441  return NULL;
2442  return PQexecFinish(conn);
2443 }
#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 2417 of file fe-exec.c.

2418 {
2419  if (!PQexecStart(conn))
2420  return NULL;
2422  return NULL;
2423  return PQexecFinish(conn);
2424 }

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

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

◆ PQendcopy()

int PQendcopy ( PGconn conn)

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

2912 {
2913  if (!conn)
2914  return 0;
2915 
2916  return pqEndcopy3(conn);
2917 }
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 3004 of file fe-exec.c.

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

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

4430 {
4431  return PQescapeByteaInternal(NULL, from, from_length, to_length,
4433  false /* can't use hex */ );
4434 }
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:4317
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 4413 of file fe-exec.c.

4416 {
4417  if (!conn)
4418  return NULL;
4419 
4420  if (conn->cmd_queue_head == NULL)
4422 
4423  return PQescapeByteaInternal(conn, from, from_length, to_length,
4424  conn->std_strings,
4425  (conn->sversion >= 90000));
4426 }
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:872
bool std_strings
Definition: libpq-int.h:502
int sversion
Definition: libpq-int.h:468

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

4320 {
4321  const unsigned char *vp;
4322  unsigned char *rp;
4323  unsigned char *result;
4324  size_t i;
4325  size_t len;
4326  size_t bslash_len = (std_strings ? 1 : 2);
4327 
4328  /*
4329  * empty string has 1 char ('\0')
4330  */
4331  len = 1;
4332 
4333  if (use_hex)
4334  {
4335  len += bslash_len + 1 + 2 * from_length;
4336  }
4337  else
4338  {
4339  vp = from;
4340  for (i = from_length; i > 0; i--, vp++)
4341  {
4342  if (*vp < 0x20 || *vp > 0x7e)
4343  len += bslash_len + 3;
4344  else if (*vp == '\'')
4345  len += 2;
4346  else if (*vp == '\\')
4347  len += bslash_len + bslash_len;
4348  else
4349  len++;
4350  }
4351  }
4352 
4353  *to_length = len;
4354  rp = result = (unsigned char *) malloc(len);
4355  if (rp == NULL)
4356  {
4357  if (conn)
4358  libpq_append_conn_error(conn, "out of memory");
4359  return NULL;
4360  }
4361 
4362  if (use_hex)
4363  {
4364  if (!std_strings)
4365  *rp++ = '\\';
4366  *rp++ = '\\';
4367  *rp++ = 'x';
4368  }
4369 
4370  vp = from;
4371  for (i = from_length; i > 0; i--, vp++)
4372  {
4373  unsigned char c = *vp;
4374 
4375  if (use_hex)
4376  {
4377  *rp++ = hextbl[(c >> 4) & 0xF];
4378  *rp++ = hextbl[c & 0xF];
4379  }
4380  else if (c < 0x20 || c > 0x7e)
4381  {
4382  if (!std_strings)
4383  *rp++ = '\\';
4384  *rp++ = '\\';
4385  *rp++ = (c >> 6) + '0';
4386  *rp++ = ((c >> 3) & 07) + '0';
4387  *rp++ = (c & 07) + '0';
4388  }
4389  else if (c == '\'')
4390  {
4391  *rp++ = '\'';
4392  *rp++ = '\'';
4393  }
4394  else if (c == '\\')
4395  {
4396  if (!std_strings)
4397  {
4398  *rp++ = '\\';
4399  *rp++ = '\\';
4400  }
4401  *rp++ = '\\';
4402  *rp++ = '\\';
4403  }
4404  else
4405  *rp++ = c;
4406  }
4407  *rp = '\0';
4408 
4409  return result;
4410 }
static const char hextbl[]
Definition: fe-exec.c:4276
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 4270 of file fe-exec.c.

4271 {
4272  return PQescapeInternal(conn, str, len, true);
4273 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:4142

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

Referenced by initCreatePKeys(), initCreateTables(), main(), PQchangePassword(), 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 4142 of file fe-exec.c.

4143 {
4144  const char *s;
4145  char *result;
4146  char *rp;
4147  int num_quotes = 0; /* single or double, depending on as_ident */
4148  int num_backslashes = 0;
4149  int input_len;
4150  int result_size;
4151  char quote_char = as_ident ? '"' : '\'';
4152 
4153  /* We must have a connection, else fail immediately. */
4154  if (!conn)
4155  return NULL;
4156 
4157  if (conn->cmd_queue_head == NULL)
4159 
4160  /* Scan the string for characters that must be escaped. */
4161  for (s = str; (s - str) < len && *s != '\0'; ++s)
4162  {
4163  if (*s == quote_char)
4164  ++num_quotes;
4165  else if (*s == '\\')
4166  ++num_backslashes;
4167  else if (IS_HIGHBIT_SET(*s))
4168  {
4169  int charlen;
4170 
4171  /* Slow path for possible multibyte characters */
4172  charlen = pg_encoding_mblen(conn->client_encoding, s);
4173 
4174  /* Multibyte character overruns allowable length. */
4175  if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
4176  {
4177  libpq_append_conn_error(conn, "incomplete multibyte character");
4178  return NULL;
4179  }
4180 
4181  /* Adjust s, bearing in mind that for loop will increment it. */
4182  s += charlen - 1;
4183  }
4184  }
4185 
4186  /* Allocate output buffer. */
4187  input_len = s - str;
4188  result_size = input_len + num_quotes + 3; /* two quotes, plus a NUL */
4189  if (!as_ident && num_backslashes > 0)
4190  result_size += num_backslashes + 2;
4191  result = rp = (char *) malloc(result_size);
4192  if (rp == NULL)
4193  {
4194  libpq_append_conn_error(conn, "out of memory");
4195  return NULL;
4196  }
4197 
4198  /*
4199  * If we are escaping a literal that contains backslashes, we use the
4200  * escape string syntax so that the result is correct under either value
4201  * of standard_conforming_strings. We also emit a leading space in this
4202  * case, to guard against the possibility that the result might be
4203  * interpolated immediately following an identifier.
4204  */
4205  if (!as_ident && num_backslashes > 0)
4206  {
4207  *rp++ = ' ';
4208  *rp++ = 'E';
4209  }
4210 
4211  /* Opening quote. */
4212  *rp++ = quote_char;
4213 
4214  /*
4215  * Use fast path if possible.
4216  *
4217  * We've already verified that the input string is well-formed in the
4218  * current encoding. If it contains no quotes and, in the case of
4219  * literal-escaping, no backslashes, then we can just copy it directly to
4220  * the output buffer, adding the necessary quotes.
4221  *
4222  * If not, we must rescan the input and process each character
4223  * individually.
4224  */
4225  if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
4226  {
4227  memcpy(rp, str, input_len);
4228  rp += input_len;
4229  }
4230  else
4231  {
4232  for (s = str; s - str < input_len; ++s)
4233  {
4234  if (*s == quote_char || (!as_ident && *s == '\\'))
4235  {
4236  *rp++ = *s;
4237  *rp++ = *s;
4238  }
4239  else if (!IS_HIGHBIT_SET(*s))
4240  *rp++ = *s;
4241  else
4242  {
4244 
4245  while (1)
4246  {
4247  *rp++ = *s;
4248  if (--i == 0)
4249  break;
4250  ++s; /* for loop will provide the final increment */
4251  }
4252  }
4253  }
4254  }
4255 
4256  /* Closing quote and terminating NUL. */
4257  *rp++ = quote_char;
4258  *rp = '\0';
4259 
4260  return result;
4261 }
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1142
int client_encoding
Definition: libpq-int.h:501
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 
)

◆ PQescapeString()

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

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

4128 {
4129  return PQescapeStringInternal(NULL, to, from, length, NULL,
4132 }
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:4031
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 4105 of file fe-exec.c.

4108 {
4109  if (!conn)
4110  {
4111  /* force empty-string result */
4112  *to = '\0';
4113  if (error)
4114  *error = 1;
4115  return 0;
4116  }
4117 
4118  if (conn->cmd_queue_head == NULL)
4120 
4121  return PQescapeStringInternal(conn, to, from, length, error,
4123  conn->std_strings);
4124 }
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 4031 of file fe-exec.c.

4035 {
4036  const char *source = from;
4037  char *target = to;
4038  size_t remaining = length;
4039 
4040  if (error)
4041  *error = 0;
4042 
4043  while (remaining > 0 && *source != '\0')
4044  {
4045  char c = *source;
4046  int len;
4047  int i;
4048 
4049  /* Fast path for plain ASCII */
4050  if (!IS_HIGHBIT_SET(c))
4051  {
4052  /* Apply quoting if needed */
4053  if (SQL_STR_DOUBLE(c, !std_strings))
4054  *target++ = c;
4055  /* Copy the character */
4056  *target++ = c;
4057  source++;
4058  remaining--;
4059  continue;
4060  }
4061 
4062  /* Slow path for possible multibyte characters */
4064 
4065  /* Copy the character */
4066  for (i = 0; i < len; i++)
4067  {
4068  if (remaining == 0 || *source == '\0')
4069  break;
4070  *target++ = *source++;
4071  remaining--;
4072  }
4073 
4074  /*
4075  * If we hit premature end of string (ie, incomplete multibyte
4076  * character), try to pad out to the correct length with spaces. We
4077  * may not be able to pad completely, but we will always be able to
4078  * insert at least one pad space (since we'd not have quoted a
4079  * multibyte character). This should be enough to make a string that
4080  * the server will error out on.
4081  */
4082  if (i < len)
4083  {
4084  if (error)
4085  *error = 1;
4086  if (conn)
4087  libpq_append_conn_error(conn, "incomplete multibyte character");
4088  for (; i < len; i++)
4089  {
4090  if (((size_t) (target - to)) / 2 >= length)
4091  break;
4092  *target++ = ' ';
4093  }
4094  break;
4095  }
4096  }
4097 
4098  /* Write the terminating NUL character. */
4099  *target = '\0';
4100 
4101  return target - to;
4102 }
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:1150
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 2224 of file fe-exec.c.

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

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

Referenced by _doSetSessionAuth(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), check_loadable_libraries(), check_prepare_conn(), CreateReplicationSlot(), 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(), PQchangePassword(), 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 2372 of file fe-exec.c.

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

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

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

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

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

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

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

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

Referenced by ecpg_execute(), and try_complete_step().

◆ PQexecStart()

static bool PQexecStart ( PGconn conn)
static

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

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

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

3036 {
3037  if (!conn)
3038  return 0;
3039 
3041  (conn->asyncStatus == PGASYNC_IDLE ||
3043  conn->cmd_queue_head == NULL)
3044  return 1;
3045 
3046  switch (conn->asyncStatus)
3047  {
3048  case PGASYNC_READY:
3049  case PGASYNC_READY_MORE:
3050  /* there are some uncollected results */
3051  libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
3052  return 0;
3053 
3054  case PGASYNC_BUSY:
3055  libpq_append_conn_error(conn, "cannot exit pipeline mode while busy");
3056  return 0;
3057 
3058  case PGASYNC_IDLE:
3059  case PGASYNC_PIPELINE_IDLE:
3060  /* OK */
3061  break;
3062 
3063  case PGASYNC_COPY_IN:
3064  case PGASYNC_COPY_OUT:
3065  case PGASYNC_COPY_BOTH:
3066  libpq_append_conn_error(conn, "cannot exit pipeline mode while in COPY");
3067  }
3068 
3069  /* still work to process */
3070  if (conn->cmd_queue_head != NULL)
3071  {
3072  libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
3073  return 0;
3074  }
3075 
3078 
3079  /* Flush any pending data in out buffer */
3080  if (pqFlush(conn) < 0)
3081  return 0; /* error message is setup already */
3082  return 1;
3083 }
@ 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 3668 of file fe-exec.c.

3669 {
3670  if (!check_field_number(res, field_num))
3671  return 0;
3672  if (res->attDescs)
3673  return res->attDescs[field_num].format;
3674  else
3675  return 0;
3676 }
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3470

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

int PQflush ( PGconn conn)

◆ PQfmod()

int PQfmod ( const PGresult res,
int  field_num 
)

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

3702 {
3703  if (!check_field_number(res, field_num))
3704  return 0;
3705  if (res->attDescs)
3706  return res->attDescs[field_num].atttypmod;
3707  else
3708  return 0;
3709 }
int atttypmod
Definition: libpq-fe.h:277

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

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

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

3550 {
3551  char *field_case;
3552  bool in_quotes;
3553  bool all_lower = true;
3554  const char *iptr;
3555  char *optr;
3556  int i;
3557 
3558  if (!res)
3559  return -1;
3560 
3561  /*
3562  * Note: it is correct to reject a zero-length input string; the proper
3563  * input to match a zero-length field name would be "".
3564  */
3565  if (field_name == NULL ||
3566  field_name[0] == '\0' ||
3567  res->attDescs == NULL)
3568  return -1;
3569 
3570  /*
3571  * Check if we can avoid the strdup() and related work because the
3572  * passed-in string wouldn't be changed before we do the check anyway.
3573  */
3574  for (iptr = field_name; *iptr; iptr++)
3575  {
3576  char c = *iptr;
3577 
3578  if (c == '"' || c != pg_tolower((unsigned char) c))
3579  {
3580  all_lower = false;
3581  break;
3582  }
3583  }
3584 
3585  if (all_lower)
3586  for (i = 0; i < res->numAttributes; i++)
3587  if (strcmp(field_name, res->attDescs[i].name) == 0)
3588  return i;
3589 
3590  /* Fall through to the normal check if that didn't work out. */
3591 
3592  /*
3593  * Note: this code will not reject partially quoted strings, eg
3594  * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
3595  * condition.
3596  */
3597  field_case = strdup(field_name);
3598  if (field_case == NULL)
3599  return -1; /* grotty */
3600 
3601  in_quotes = false;
3602  optr = field_case;
3603  for (iptr = field_case; *iptr; iptr++)
3604  {
3605  char c = *iptr;
3606 
3607  if (in_quotes)
3608  {
3609  if (c == '"')
3610  {
3611  if (iptr[1] == '"')
3612  {
3613  /* doubled quotes become a single quote */
3614  *optr++ = '"';
3615  iptr++;
3616  }
3617  else
3618  in_quotes = false;
3619  }
3620  else
3621  *optr++ = c;
3622  }
3623  else if (c == '"')
3624  in_quotes = true;
3625  else
3626  {
3627  c = pg_tolower((unsigned char) c);
3628  *optr++ = c;
3629  }
3630  }
3631  *optr = '\0';
3632 
3633  for (i = 0; i < res->numAttributes; i++)
3634  {
3635  if (strcmp(field_case, res->attDescs[i].name) == 0)
3636  {
3637  free(field_case);
3638  return i;
3639  }
3640  }
3641  free(field_case);
3642  return -1;
3643 }
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_old_cluster_logical_slot_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(), getSubscriptionTables(), 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 4009 of file fe-exec.c.

4010 {
4011  PQfreemem(notify);
4012 }
void PQfreemem(void *ptr)
Definition: fe-exec.c:3992

References PQfreemem().

◆ PQfsize()

int PQfsize ( const PGresult res,
int  field_num 
)

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

3691 {
3692  if (!check_field_number(res, field_num))
3693  return 0;
3694  if (res->attDescs)
3695  return res->attDescs[field_num].typlen;
3696  else
3697  return 0;
3698 }

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

3647 {
3648  if (!check_field_number(res, field_num))
3649  return InvalidOid;
3650  if (res->attDescs)
3651  return res->attDescs[field_num].tableid;
3652  else
3653  return InvalidOid;
3654 }
#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 3657 of file fe-exec.c.

3658 {
3659  if (!check_field_number(res, field_num))
3660  return 0;
3661  if (res->attDescs)
3662  return res->attDescs[field_num].columnid;
3663  else
3664  return 0;
3665 }
int columnid
Definition: libpq-fe.h:273

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

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

3862 {
3863  if (!check_tuple_field_number(res, tup_num, field_num))
3864  return 1; /* pretend it is null */
3865  if (res->tuples[tup_num][field_num].len == NULL_LEN)
3866  return 1;
3867  else
3868  return 0;
3869 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3485
#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(), getExtendedStatistics(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getLOs(), getNamespaces(), getPolicies(), getProcLangs(), getPublicationTables(), GetSlotInformation(), getSubscriptions(), getSubscriptionTables(), getTableAttrs(), GetTableInfo(), getTables(), 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 3847 of file fe-exec.c.

3848 {
3849  if (!check_tuple_field_number(res, tup_num, field_num))
3850  return 0;
3851  if (res->tuples[tup_num][field_num].len != NULL_LEN)
3852  return res->tuples[tup_num][field_num].len;
3853  else
3854  return 0;
3855 }

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

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

References conn, and pqGetline3().

◆ PQgetlineAsync()

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

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

2864 {
2865  if (!conn)
2866  return -1;
2867 
2868  return pqGetlineAsync3(conn, buffer, bufsize);
2869 }
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 2038 of file fe-exec.c.

2039 {
2040  PGresult *res;
2041 
2042  if (!conn)
2043  return NULL;
2044 
2045  /* Parse any available data, if our state permits. */
2046  parseInput(conn);
2047 
2048  /* If not ready to return something, block until we are. */
2049  while (conn->asyncStatus == PGASYNC_BUSY)
2050  {
2051  int flushResult;
2052 
2053  /*
2054  * If data remains unsent, send it. Else we might be waiting for the
2055  * result of a command the backend hasn't even got yet.
2056  */
2057  while ((flushResult = pqFlush(conn)) > 0)
2058  {
2059  if (pqWait(false, true, conn))
2060  {
2061  flushResult = -1;
2062  break;
2063  }
2064  }
2065 
2066  /*
2067  * Wait for some more data, and load it. (Note: if the connection has
2068  * been lost, pqWait should return immediately because the socket
2069  * should be read-ready, either with the last server data or with an
2070  * EOF indication. We expect therefore that this won't result in any
2071  * undue delay in reporting a previous write failure.)
2072  */
2073  if (flushResult ||
2074  pqWait(true, false, conn) ||
2075  pqReadData(conn) < 0)
2076  {
2077  /* Report the error saved by pqWait or pqReadData */
2080  return pqPrepareAsyncResult(conn);
2081  }
2082 
2083  /* Parse it. */
2084  parseInput(conn);
2085 
2086  /*
2087  * If we had a write error, but nothing above obtained a query result
2088  * or detected a read error, report the write error.
2089  */
2091  {
2094  return pqPrepareAsyncResult(conn);
2095  }
2096  }
2097 
2098  /* Return the appropriate thing. */
2099  switch (conn->asyncStatus)
2100  {
2101  case PGASYNC_IDLE:
2102  res = NULL; /* query is complete */
2103  break;
2104  case PGASYNC_PIPELINE_IDLE:
2106 
2107  /*
2108  * We're about to return the NULL that terminates the round of
2109  * results from the current query; prepare to send the results of
2110  * the next query, if any, when we're called next. If there's no
2111  * next element in the command queue, this gets us in IDLE state.
2112  */
2114  res = NULL; /* query is complete */
2115  break;
2116 
2117  case PGASYNC_READY:
2119 
2120  /* Advance the queue as appropriate */
2121  pqCommandQueueAdvance(conn, false,
2123 
2125  {
2126  /*
2127  * We're about to send the results of the current query. Set
2128  * us idle now, and ...
2129  */
2131 
2132  /*
2133  * ... in cases when we're sending a pipeline-sync result,
2134  * move queue processing forwards immediately, so that next
2135  * time we're called, we're prepared to return the next result
2136  * received from the server. In all other cases, leave the
2137  * queue state change for next time, so that a terminating
2138  * NULL result is sent.
2139  *
2140  * (In other words: we don't return a NULL after a pipeline
2141  * sync.)
2142  */
2145  }
2146  else
2147  {
2148  /* Set the state back to BUSY, allowing parsing to proceed. */
2150  }
2151  break;
2152  case PGASYNC_READY_MORE:
2154  /* Set the state back to BUSY, allowing parsing to proceed. */
2156  break;
2157  case PGASYNC_COPY_IN:
2159  break;
2160  case PGASYNC_COPY_OUT:
2162  break;
2163  case PGASYNC_COPY_BOTH:
2165  break;
2166  default:
2167  libpq_append_conn_error(conn, "unexpected asyncStatus: %d", (int) conn->asyncStatus);
2169  conn->asyncStatus = PGASYNC_IDLE; /* try to restore valid state */
2171  break;
2172  }
2173 
2174  /* Time to fire PGEVT_RESULTCREATE events, if there are any */
2175  if (res && res->nEvents > 0)
2177 
2178  return res;
2179 }
static void pqSaveWriteError(PGconn *conn)
Definition: fe-exec.c:818
void pqCommandQueueAdvance(PGconn *conn, bool isReadyForQuery, bool gotSync)
Definition: fe-exec.c:3104
static PGresult * getCopyResult(PGconn *conn, ExecStatusType copytype)
Definition: fe-exec.c:2186
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1996
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:114
bool write_failed
Definition: libpq-int.h:474

References Assert(), pg_conn::asyncStatus, 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, 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(), res, pg_result::resultStatus, and pg_conn::write_failed.

Referenced by advanceConnectionState(), BaseBackup(), ClearOrSaveAllResults(), confirm_query_canceled_impl(), consumeQueryResult(), discardUntilSync(), dumpTableData_copy(), ecpg_process_output(), EndDBCopyMode(), ExecQueryAndProcessResults(), handleCopyIn(), handleCopyOut(), HandleEndOfCopyStream(), libpqrcv_PQgetResult(), libpqsrv_get_result(), pgfdw_finish_pre_commit_cleanup(), pgfdw_get_cleanup_result(), PQconnectPoll(), pqEndcopy3(), PQexecFinish(), PQexecStart(), process_queued_fetch_requests(), process_result(), readCommandResponse(), ReceiveCopyData(), ReceiveXlogStream(), 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 3836 of file fe-exec.c.

3837 {
3838  if (!check_tuple_field_number(res, tup_num, field_num))
3839  return NULL;
3840  return res->tuples[tup_num][field_num].value;
3841 }

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_new_cluster_logical_replication_slots(), check_new_cluster_subscription_configuration(), check_old_cluster_subscription_state(), 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_db_subscription_count(), get_language_name(), get_loadable_libraries(), get_next_possible_free_pg_type_oid(), get_old_cluster_logical_slot_infos(), 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(), getSubscriptionTables(), 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(), verify_heap_slot_handler(), and wait_for_connection_state().

◆ pqInternalNotice()

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

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

937 {
938  char msgBuf[1024];
939  va_list args;
940  PGresult *res;
941 
942  if (hooks->noticeRec == NULL)
943  return; /* nobody home to receive notice? */
944 
945  /* Format the message */
946  va_start(args, fmt);
947  vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
948  va_end(args);
949  msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
950 
951  /* Make a PGresult to pass to the notice receiver */
953  if (!res)
954  return;
955  res->noticeHooks = *hooks;
956 
957  /*
958  * Set up fields of notice.
959  */
963  /* XXX should provide a SQLSTATE too? */
964 
965  /*
966  * Result text is always just the primary message + newline. If we can't
967  * allocate it, substitute "out of memory", as in pqSetResultError.
968  */
969  res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, false);
970  if (res->errMsg)
971  sprintf(res->errMsg, "%s\n", msgBuf);
972  else
973  res->errMsg = libpq_gettext("out of memory\n");
974 
975  /*
976  * Pass to receiver, then free it.
977  */
979  PQclear(res);
980 }
void pqSaveMessageField(PGresult *res, char code, const char *value)
Definition: fe-exec.c:1058
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:561
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:110
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 2007 of file fe-exec.c.

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

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

Referenced by advanceConnectionState(), confirm_query_canceled_impl(), dblink_is_busy(), libpqrcv_PQgetResult(), libpqsrv_get_result(), pgfdw_get_cleanup_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 3943 of file fe-exec.c.

3944 {
3945  if (!conn || conn->status == CONNECTION_BAD)
3946  return false;
3947  return pqIsnonblocking(conn);
3948 }

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

3953 {
3954  return true;
3955 }

◆ PQmakeEmptyPGresult()

PGresult* PQmakeEmptyPGresult ( PGconn conn,
ExecStatusType  status 
)

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

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

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

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

3876 {
3877  if (!res)
3878  return 0;
3879  return res->numParameters;
3880 }

References pg_result::numParameters, and res.

◆ PQntuples()

int PQntuples ( const PGresult res)

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

3442 {
3443  if (!res)
3444  return 0;
3445  return res->ntups;
3446 }

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_new_cluster_logical_replication_slots(), check_new_cluster_subscription_configuration(), check_old_cluster_subscription_state(), 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_old_cluster_logical_slot_infos(), 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(), getSubscriptionTables(), 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(), verify_heap_slot_handler(), and wait_for_connection_state().

◆ PQoidStatus()

char* PQoidStatus ( const PGresult res)

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

3726 {
3727  /*
3728  * This must be enough to hold the result. Don't laugh, this is better
3729  * than what this function used to do.
3730  */
3731  static char buf[24];
3732 
3733  size_t len;
3734 
3735  if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
3736  return "";
3737 
3738  len = strspn(res->cmdStatus + 7, "0123456789");
3739  if (len > sizeof(buf) - 1)
3740  len = sizeof(buf) - 1;
3741  memcpy(buf, res->cmdStatus + 7, len);
3742  buf[len] = '\0';
3743 
3744  return buf;
3745 }
static char * buf
Definition: pg_test_fsync.c:73

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

◆ PQoidValue()

Oid PQoidValue ( const PGresult res)

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

3754 {
3755  char *endptr = NULL;
3756  unsigned long result;
3757 
3758  if (!res ||
3759  strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
3760  res->cmdStatus[7] < '0' ||
3761  res->cmdStatus[7] > '9')
3762  return InvalidOid;
3763 
3764  result = strtoul(res->cmdStatus + 7, &endptr, 10);
3765 
3766  if (!endptr || (*endptr != ' ' && *endptr != '\0'))
3767  return InvalidOid;
3768  else
3769  return (Oid) result;
3770 }
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 3886 of file fe-exec.c.

3887 {
3888  if (!check_param_number(res, param_num))
3889  return InvalidOid;
3890  if (res->paramDescs)
3891  return res->paramDescs[param_num].typid;
3892  else
3893  return InvalidOid;
3894 }
static int check_param_number(const PGresult *res, int param_num)
Definition: fe-exec.c:3508

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

◆ pqPipelineFlush()

static int pqPipelineFlush ( PGconn conn)
static

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

3977 {
3978  if ((conn->pipelineStatus != PQ_PIPELINE_ON) ||
3980  return pqFlush(conn);
3981  return 0;
3982 }
#define OUTBUFFER_THRESHOLD
Definition: libpq-int.h:893
int outCount
Definition: libpq-int.h:521

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

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

◆ pqPipelineProcessQueue()

static void pqPipelineProcessQueue ( PGconn conn)
static

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

3143 {
3144  switch (conn->asyncStatus)
3145  {
3146  case PGASYNC_COPY_IN:
3147  case PGASYNC_COPY_OUT:
3148  case PGASYNC_COPY_BOTH:
3149  case PGASYNC_READY:
3150  case PGASYNC_READY_MORE:
3151  case PGASYNC_BUSY:
3152  /* client still has to process current query or results */
3153  return;
3154 
3155  case PGASYNC_IDLE:
3156 
3157  /*
3158  * If we're in IDLE mode and there's some command in the queue,
3159  * get us into PIPELINE_IDLE mode and process normally. Otherwise
3160  * there's nothing for us to do.
3161  */
3162  if (conn->cmd_queue_head != NULL)
3163  {
3165  break;
3166  }
3167  return;
3168 
3169  case PGASYNC_PIPELINE_IDLE:
3171  /* next query please */
3172  break;
3173  }
3174 
3175  /*
3176  * Reset single-row processing mode. (Client has to set it up for each
3177  * query, if desired.)
3178  */
3179  conn->singleRowMode = false;
3180 
3181  /*
3182  * If there are no further commands to process in the queue, get us in
3183  * "real idle" mode now.
3184  */
3185  if (conn->cmd_queue_head == NULL)
3186  {
3188  return;
3189  }
3190 
3191  /*
3192  * Reset the error state. This and the next couple of steps correspond to
3193  * what PQsendQueryStart didn't do for this query.
3194  */
3196 
3197  /* Initialize async result-accumulation state */
3199 
3202  {
3203  /*
3204  * In an aborted pipeline we don't get anything from the server for
3205  * each result; we're just discarding commands from the queue until we
3206  * get to the next sync from the server.
3207  *
3208  * The PGRES_PIPELINE_ABORTED results tell the client that its queries
3209  * got aborted.
3210  */
3212  if (!conn->result)
3213  {
3214  libpq_append_conn_error(conn, "out of memory");
3216  return;
3217  }
3219  }
3220  else
3221  {
3222  /* allow parsing to continue */
3224  }
3225 }
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:777
@ PGRES_PIPELINE_ABORTED
Definition: libpq-fe.h:115
bool singleRowMode
Definition: libpq-int.h:437

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

3233 {
3234  return pqPipelineSyncInternal(conn, true);
3235 }
static int pqPipelineSyncInternal(PGconn *conn, bool immediate_flush)
Definition: fe-exec.c:3254

References conn, and pqPipelineSyncInternal().

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

◆ pqPipelineSyncInternal()

static int pqPipelineSyncInternal ( PGconn conn,
bool  immediate_flush 
)
static

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

3255 {
3256  PGcmdQueueEntry *entry;
3257 
3258  if (!conn)
3259  return 0;
3260 
3262  {
3263  libpq_append_conn_error(conn, "cannot send pipeline when not in pipeline mode");
3264  return 0;
3265  }
3266 
3267  switch (conn->asyncStatus)
3268  {
3269  case PGASYNC_COPY_IN:
3270  case PGASYNC_COPY_OUT:
3271  case PGASYNC_COPY_BOTH:
3272  /* should be unreachable */
3274  "internal error: cannot send pipeline while in COPY\n");
3275  return 0;
3276  case PGASYNC_READY:
3277  case PGASYNC_READY_MORE:
3278  case PGASYNC_BUSY:
3279  case PGASYNC_IDLE:
3280  case PGASYNC_PIPELINE_IDLE:
3281  /* OK to send sync */
3282  break;
3283  }
3284 
3285  entry = pqAllocCmdQueueEntry(conn);
3286  if (entry == NULL)
3287  return 0; /* error msg already set */
3288 
3289  entry->queryclass = PGQUERY_SYNC;
3290  entry->query = NULL;
3291 
3292  /* construct the Sync message */
3293  if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
3294  pqPutMsgEnd(conn) < 0)
3295  goto sendFailed;
3296 
3297  /*
3298  * Give the data a push. In nonblock mode, don't complain if we're unable
3299  * to send it all; PQgetResult() will do any additional flushing needed.
3300  * If immediate_flush is disabled, the data is pushed if we are past the
3301  * size threshold.
3302  */
3303  if (immediate_flush)
3304  {
3305  if (pqFlush(conn) < 0)
3306  goto sendFailed;
3307  }
3308  else
3309  {
3310  if (pqPipelineFlush(conn) < 0)
3311  goto sendFailed;
3312  }
3313 
3314  /* OK, it's launched! */
3315  pqAppendCmdQueueEntry(conn, entry);
3316 
3317  return 1;
3318 
3319 sendFailed:
3320  pqRecycleCmdQueueEntry(conn, entry);
3321  /* error message should be set up already */
3322  return 0;
3323 }
static void pqAppendCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1348
static int pqPipelineFlush(PGconn *conn)
Definition: fe-exec.c:3976
static PGcmdQueueEntry * pqAllocCmdQueueEntry(PGconn *conn)
Definition: fe-exec.c:1315
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, pqPipelineFlush(), pqPutMsgEnd(), pqPutMsgStart(), pqRecycleCmdQueueEntry(), PGcmdQueueEntry::query, and PGcmdQueueEntry::queryclass.

Referenced by PQpipelineSync(), and PQsendPipelineSync().

◆ PQprepare()

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

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

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

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

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

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

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

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 BaseBackup(), ExecuteSqlCommandBuf(), handleCopyIn(), libpqrcv_send(), PQputnbytes(), and sendFeedback().

◆ PQputCopyEnd()

int PQputCopyEnd ( PGconn conn,
const char *  errormsg 
)

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

2712 {
2713  if (!conn)
2714  return -1;
2715  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2717  {
2718  libpq_append_conn_error(conn, "no COPY in progress");
2719  return -1;
2720  }
2721 
2722  /*
2723  * Send the COPY END indicator. This is simple enough that we don't
2724  * bother delegating it to the fe-protocol files.
2725  */
2726  if (errormsg)
2727  {
2728  /* Send COPY FAIL */
2729  if (pqPutMsgStart(PqMsg_CopyFail, conn) < 0 ||
2730  pqPuts(errormsg, conn) < 0 ||
2731  pqPutMsgEnd(conn) < 0)
2732  return -1;
2733  }
2734  else
2735  {
2736  /* Send COPY DONE */
2737  if (pqPutMsgStart(PqMsg_CopyDone, conn) < 0 ||
2738  pqPutMsgEnd(conn) < 0)
2739  return -1;
2740  }
2741 
2742  /*
2743  * If we sent the COPY command in extended-query mode, we must issue a
2744  * Sync as well.
2745  */
2746  if (conn->cmd_queue_head &&
2748  {
2749  if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
2750  pqPutMsgEnd(conn) < 0)
2751  return -1;
2752  }
2753 
2754  /* Return to active duty */
2757  else
2759 
2760  /* Try to flush data */
2761  if (pqFlush(conn) < 0)
2762  return -1;
2763 
2764  return 1;
2765 }
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 BaseBackup(), CheckCopyStreamStop(), EndDBCopyMode(), handleCopyIn(), HandleEndOfCopyStream(), libpqrcv_endstreaming(), PQexecStart(), prepareToTerminate(), and ProcessXLogDataMsg().

◆ PQputline()

int PQputline ( PGconn conn,
const char *  string 
)

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

2881 {
2882  return PQputnbytes(conn, string, strlen(string));
2883 }
int PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2890

References conn, and PQputnbytes().

Referenced by initPopulateTable().

◆ PQputnbytes()

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

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

2891 {
2892  if (PQputCopyData(conn, buffer, nbytes) > 0)
2893  return 0;
2894  else
2895  return EOF;
2896 }
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2657

References conn, and PQputCopyData().

Referenced by PQputline().

◆ pqRecycleCmdQueueEntry()

static void pqRecycleCmdQueueEntry ( PGconn conn,
PGcmdQueueEntry entry 
)
static

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

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

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

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

◆ PQresStatus()

char* PQresStatus ( ExecStatusType  status)

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

3380 {
3381  if ((unsigned int) status >= lengthof(pgresStatus))
3382  return libpq_gettext("invalid ExecStatusType code");
3383  return pgresStatus[status];
3384 }
#define lengthof(array)
Definition: c.h:775
char *const pgresStatus[]
Definition: fe-exec.c:32

References lengthof, libpq_gettext, and pgresStatus.

Referenced by BaseBackup(), 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 541 of file fe-exec.c.

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

References OOM_result, pqResultAlloc(), and res.

Referenced by PQsetResultAttrs().

◆ pqResultAlloc()

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

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

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

3427 {
3428  PGMessageField *pfield;
3429 
3430  if (!res)
3431  return NULL;
3432  for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
3433  {
3434  if (pfield->code == fieldcode)
3435  return pfield->contents;
3436  }
3437  return NULL;
3438 }
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(), confirm_query_canceled_impl(), 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 661 of file fe-exec.c.

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

References pg_result::memorySize, and res.

◆ PQresultStatus()

ExecStatusType PQresultStatus ( const PGresult res)

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

3372 {
3373  if (!res)
3374  return PGRES_FATAL_ERROR;
3375  return res->resultStatus;
3376 }

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(), confirm_query_canceled_impl(), 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(), exec_command_password(), 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_alter_slot(), libpqrcv_connect(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_exec(), libpqrcv_identify_system(), libpqrcv_PQexec(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_startstreaming(), libpqsrv_get_result_last(), 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(), verify_heap_slot_handler(), and wait_for_connection_state().

◆ pqResultStrdup()

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

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

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

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

3398 {
3399  PQExpBufferData workBuf;
3400 
3401  /*
3402  * Because the caller is expected to free the result string, we must
3403  * strdup any constant result. We use plain strdup and document that
3404  * callers should expect NULL if out-of-memory.
3405  */
3406  if (!res ||
3409  return strdup(libpq_gettext("PGresult is not an error result\n"));
3410 
3411  initPQExpBuffer(&workBuf);
3412 
3413  pqBuildErrorMessage3(&workBuf, res, verbosity, show_context);
3414 
3415  /* If insufficient memory to format the message, fail cleanly */
3416  if (PQExpBufferDataBroken(workBuf))
3417  {
3418  termPQExpBuffer(&workBuf);
3419  return strdup(libpq_gettext("out of memory\n"));
3420  }
3421 
3422  return workBuf.data;
3423 }
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 1209 of file fe-exec.c.

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

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

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

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

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

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

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

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

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

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

2532 {
2533  return PQsendTypedCommand(conn, PqMsg_Close, 'P', portal);
2534 }

References conn, PqMsg_Close, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQsendClosePrepared()

int PQsendClosePrepared ( PGconn conn,
const char *  stmt 
)

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

2519 {
2520  return PQsendTypedCommand(conn, PqMsg_Close, 'S', stmt);
2521 }

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

Referenced by test_prepared().

◆ PQsendDescribePortal()

int PQsendDescribePortal ( PGconn conn,
const char *  portal 
)

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

2467 {
2468  return PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal);
2469 }

References conn, PqMsg_Describe, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQsendDescribePrepared()

int PQsendDescribePrepared ( PGconn conn,
const char *  stmt 
)

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

2454 {
2455  return PQsendTypedCommand(conn, PqMsg_Describe, 'S', stmt);
2456 }

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

Referenced by test_prepared().

◆ PQsendFlushRequest()

int PQsendFlushRequest ( PGconn conn)

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

3332 {
3333  if (!conn)
3334  return 0;
3335 
3336  /* Don't try to send if we know there's no live connection. */
3337  if (conn->status != CONNECTION_OK)
3338  {
3339  libpq_append_conn_error(conn, "no connection to the server");
3340  return 0;
3341  }
3342 
3343  /* Can't send while already busy, either, unless enqueuing for later */
3344  if (conn->asyncStatus != PGASYNC_IDLE &&
3346  {
3347  libpq_append_conn_error(conn, "another command is already in progress");
3348  return 0;
3349  }
3350 
3351  if (pqPutMsgStart(PqMsg_Flush, conn) < 0 ||
3352  pqPutMsgEnd(conn) < 0)
3353  {
3354  return 0;
3355  }
3356 
3357  /*
3358  * Give the data a push (in pipeline mode, only if we're past the size
3359  * threshold). In nonblock mode, don't complain if we're unable to send
3360  * it all; PQgetResult() will do any additional flushing needed.
3361  */
3362  if (pqPipelineFlush(conn) < 0)
3363  return 0;
3364 
3365  return 1;
3366 }
#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, pqPipelineFlush(), pqPutMsgEnd(), pqPutMsgStart(), and pg_conn::status.

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

◆ PQsendPipelineSync()

int PQsendPipelineSync ( PGconn conn)

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

3243 {
3244  return pqPipelineSyncInternal(conn, false);
3245 }

References conn, and pqPipelineSyncInternal().

Referenced by executeMetaCommand(), and test_multi_pipelines().

◆ PQsendPrepare()

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

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

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

1432 {
1433  return PQsendQueryInternal(conn, query, false);
1434 }

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

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

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

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

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

Referenced by create_cursor(), ExecQueryAndProcessResults(), execute_dml_stmt(), libpqsrv_exec_params(), PQexecParams(), send_cancellable_query_impl(), 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 1642 of file fe-exec.c.

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

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

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

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

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

3905 {
3906  bool barg;
3907 
3908  if (!conn || conn->status == CONNECTION_BAD)
3909  return -1;
3910 
3911  barg = (arg ? true : false);
3912 
3913  /* early out if the socket is already in the state requested */
3914  if (barg == conn->nonblocking)
3915  return 0;
3916 
3917  /*
3918  * to guarantee constancy for flushing/query/result-polling behavior we
3919  * need to flush the send queue at this point in order to guarantee proper
3920  * behavior. this is ok because either they are making a transition _from_
3921  * or _to_ blocking mode, either way we can block them.
3922  *
3923  * Clear error state in case pqFlush adds to it, unless we're actively
3924  * pipelining, in which case it seems best not to.
3925  */
3926  if (conn->cmd_queue_head == NULL)
3928 
3929  /* if we are going from blocking to non-blocking flush here */
3930  if (pqFlush(conn))
3931  return -1;
3932 
3933  conn->nonblocking = barg;
3934 
3935  return 0;
3936 }
return true
Definition: isn.c:126
void * arg
bool nonblocking
Definition: libpq-int.h:434

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

Referenced by test_cancel(), test_pipelined_insert(), and test_uniqviol().

◆ PQsetResultAttrs()

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

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

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

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

Referenced by PQcopyResult().

◆ pqSetResultError()

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

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

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

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

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

◆ PQsetSingleRowMode()

int PQsetSingleRowMode ( PGconn conn)

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

1933 {
1934  /*
1935  * Only allow setting the flag when we have launched a query and not yet
1936  * received any results.
1937  */
1938  if (!conn)
1939  return 0;
1940  if (conn->asyncStatus != PGASYNC_BUSY)
1941  return 0;
1942  if (!conn->cmd_queue_head ||
1945  return 0;
1947  return 0;
1948 
1949  /* OK, set flag */
1950  conn->singleRowMode = true;
1951  return 1;
1952 }

References pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, PGASYNC_BUSY, pgHavePendingResult, PGQUERY_EXTENDED, PGQUERY_SIMPLE, PGcmdQueueEntry::queryclass, and pg_conn::singleRowMode.

Referenced by process_queued_fetch_requests(), storeQueryResult(), test_pipeline_abort(), and test_singlerowmode().

◆ PQsetvalue()

int PQsetvalue ( PGresult res,
int  tup_num,
int  field_num,
char *  value,
int  len 
)

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

451 {
452  PGresAttValue *attval;
453  const char *errmsg = NULL;
454 
455  /* Fail if argument is NULL or OOM_result */
456  if (!res || (const PGresult *) res == &OOM_result)
457  return false;
458 
459  /* Invalid field_num? */
460  if (!check_field_number(res, field_num))
461  return false;
462 
463  /* Invalid tup_num, must be <= ntups */
464  if (tup_num < 0 || tup_num > res->ntups)
465  {
467  "row number %d is out of range 0..%d",
468  tup_num, res->ntups);
469  return false;
470  }
471 
472  /* need to allocate a new tuple? */
473  if (tup_num == res->ntups)
474  {
475  PGresAttValue *tup;
476  int i;
477 
478  tup = (PGresAttValue *)
480  true);
481 
482  if (!tup)
483  goto fail;
484 
485  /* initialize each column to NULL */
486  for (i = 0; i < res->numAttributes; i++)
487  {
488  tup[i].len = NULL_LEN;
489  tup[i].value = res->null_field;
490  }
491 
492  /* add it to the array */
493  if (!pqAddTuple(res, tup, &errmsg))
494  goto fail;
495  }
496 
497  attval = &res->tuples[tup_num][field_num];
498 
499  /* treat either NULL_LEN or NULL value pointer as a NULL field */
500  if (len == NULL_LEN || value == NULL)
501  {
502  attval->len = NULL_LEN;
503  attval->value = res->null_field;
504  }
505  else if (len <= 0)
506  {
507  attval->len = 0;
508  attval->value = res->null_field;
509  }
510  else
511  {
512  attval->value = (char *) pqResultAlloc(res, len + 1, true);
513  if (!attval->value)
514  goto fail;
515  attval->len = len;
516  memcpy(attval->value, value, len);
517  attval->value[len] = '\0';
518  }
519 
520  return true;
521 
522  /*
523  * Report failure via pqInternalNotice. If preceding code didn't provide
524  * an error message, assume "out of memory" was meant.
525  */
526 fail:
527  if (!errmsg)
528  errmsg = libpq_gettext("out of memory");
530 
531  return false;
532 }
int errmsg(const char *fmt,...)
Definition: elog.c:1072

References check_field_number(), errmsg(), i, pgresAttValue::len, len, libpq_gettext, pg_result::noticeHooks, pg_result::ntups, pg_result::null_field, NULL_LEN, pg_result::numAttributes, OOM_result, pqAddTuple(), pqInternalNotice(), pqResultAlloc(), res, pg_result::tuples, value, and pgresAttValue::value.

Referenced by PQcopyResult().

◆ PQunescapeBytea()

unsigned char* PQunescapeBytea ( const unsigned char *  strtext,
size_t *  retbuflen 
)

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

4455 {
4456  size_t strtextlen,
4457  buflen;
4458  unsigned char *buffer,
4459  *tmpbuf;
4460  size_t i,
4461  j;
4462 
4463  if (strtext == NULL)
4464  return NULL;
4465 
4466  strtextlen = strlen((const char *) strtext);
4467 
4468  if (strtext[0] == '\\' && strtext[1] == 'x')
4469  {
4470  const unsigned char *s;
4471  unsigned char *p;
4472 
4473  buflen = (strtextlen - 2) / 2;
4474  /* Avoid unportable malloc(0) */
4475  buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
4476  if (buffer == NULL)
4477  return NULL;
4478 
4479  s = strtext + 2;
4480  p = buffer;
4481  while (*s)
4482  {
4483  char v1,
4484  v2;
4485 
4486  /*
4487  * Bad input is silently ignored. Note that this includes
4488  * whitespace between hex pairs, which is allowed by byteain.
4489  */
4490  v1 = get_hex(*s++);
4491  if (!*s || v1 == (char) -1)
4492  continue;
4493  v2 = get_hex(*s++);
4494  if (v2 != (char) -1)
4495  *p++ = (v1 << 4) | v2;
4496  }
4497 
4498  buflen = p - buffer;
4499  }
4500  else
4501  {
4502  /*
4503  * Length of input is max length of output, but add one to avoid
4504  * unportable malloc(0) if input is zero-length.
4505  */
4506  buffer = (unsigned char *) malloc(strtextlen + 1);
4507  if (buffer == NULL)
4508  return NULL;
4509 
4510  for (i = j = 0; i < strtextlen;)
4511  {
4512  switch (strtext[i])
4513  {
4514  case '\\':
4515  i++;
4516  if (strtext[i] == '\\')
4517  buffer[j++] = strtext[i++];
4518  else
4519  {
4520  if ((ISFIRSTOCTDIGIT(strtext[i])) &&
4521  (ISOCTDIGIT(strtext[i + 1])) &&
4522  (ISOCTDIGIT(strtext[i + 2])))
4523  {
4524  int byte;
4525 
4526  byte = OCTVAL(strtext[i++]);
4527  byte = (byte << 3) + OCTVAL(strtext[i++]);
4528  byte = (byte << 3) + OCTVAL(strtext[i++]);
4529  buffer[j++] = byte;
4530  }
4531  }
4532 
4533  /*
4534  * Note: if we see '\' followed by something that isn't a
4535  * recognized escape sequence, we loop around having done
4536  * nothing except advance i. Therefore the something will
4537  * be emitted as ordinary data on the next cycle. Corner
4538  * case: '\' at end of string will just be discarded.
4539  */
4540  break;
4541 
4542  default:
4543  buffer[j++] = strtext[i++];
4544  break;
4545  }
4546  }
4547  buflen = j; /* buflen is the length of the dequoted data */
4548  }
4549 
4550  /* Shrink the buffer to be no larger than necessary */
4551  /* +1 avoids unportable behavior when buflen==0 */
4552  tmpbuf = realloc(buffer, buflen + 1);
4553 
4554  /* It would only be a very brain-dead realloc that could fail, but... */
4555  if (!tmpbuf)
4556  {
4557  free(buffer);
4558  return NULL;
4559  }
4560 
4561  *retbuflen = buflen;
4562  return tmpbuf;
4563 }
static char get_hex(char c)
Definition: fe-exec.c:4290
#define ISOCTDIGIT(CH)
Definition: fe-exec.c:4438
#define OCTVAL(CH)
Definition: fe-exec.c:4439
#define ISFIRSTOCTDIGIT(CH)
Definition: fe-exec.c:4437
int j
Definition: isn.c:74
static StringInfoData tmpbuf
Definition: walsender.c:170

References free, get_hex(), i, ISFIRSTOCTDIGIT, ISOCTDIGIT, j, malloc, OCTVAL, realloc, and tmpbuf.

Variable Documentation

◆ hexlookup

const int8 hexlookup[128]
static
Initial value:
= {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
}

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

Referenced by get_hex().

◆ hextbl

const char hextbl[] = "0123456789abcdef"
static

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

Referenced by PQescapeByteaInternal().

◆ OOM_result

const PGresult OOM_result
static
Initial value:
= {
.resultStatus = PGRES_FATAL_ERROR,
.client_encoding = PG_SQL_ASCII,
.errMsg = "out of memory\n",
}

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

Referenced by PQclear(), pqPrepareAsyncResult(), PQresultAlloc(), PQsetResultAttrs(), and PQsetvalue().

◆ pgresStatus

char* const pgresStatus[]
Initial value:
= {
"PGRES_EMPTY_QUERY",
"PGRES_COMMAND_OK",
"PGRES_TUPLES_OK",
"PGRES_COPY_OUT",
"PGRES_COPY_IN",
"PGRES_BAD_RESPONSE",
"PGRES_NONFATAL_ERROR",
"PGRES_FATAL_ERROR",
"PGRES_COPY_BOTH",
"PGRES_SINGLE_TUPLE",
"PGRES_PIPELINE_SYNC",
"PGRES_PIPELINE_ABORTED"
}

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

Referenced by PQresStatus().

◆ static_client_encoding

int static_client_encoding = PG_SQL_ASCII
static

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

Referenced by PQescapeString(), and pqSaveParameterStatus().

◆ static_std_strings

bool static_std_strings = false
static

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

Referenced by PQescapeBytea(), PQescapeString(), and pqSaveParameterStatus().