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

Go to the source code of this file.

Macros

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

Functions

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

Variables

char *const pgresStatus []
 
static 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 4340 of file fe-exec.c.

◆ ISOCTDIGIT

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

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

◆ OCTVAL

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

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

◆ PGRESULT_ALIGN_BOUNDARY

#define PGRESULT_ALIGN_BOUNDARY   MAXIMUM_ALIGNOF /* from configure */

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

◆ PGRESULT_BLOCK_OVERHEAD

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

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

◆ PGRESULT_DATA_BLOCKSIZE

#define PGRESULT_DATA_BLOCKSIZE   2048

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

◆ PGRESULT_SEP_ALLOC_THRESHOLD

#define PGRESULT_SEP_ALLOC_THRESHOLD   (PGRESULT_DATA_BLOCKSIZE / 2)

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

Function Documentation

◆ check_field_number()

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

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

3370 {
3371  if (!res)
3372  return false; /* no way to display error message... */
3373  if (field_num < 0 || field_num >= res->numAttributes)
3374  {
3376  "column number %d is out of range 0..%d",
3377  field_num, res->numAttributes - 1);
3378  return false;
3379  }
3380  return true;
3381 }
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:939
PGNoticeHooks noticeHooks
Definition: libpq-int.h:187
int numAttributes
Definition: libpq-int.h:171

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

3408 {
3409  if (!res)
3410  return false; /* no way to display error message... */
3411  if (param_num < 0 || param_num >= res->numParameters)
3412  {
3414  "parameter number %d is out of range 0..%d",
3415  param_num, res->numParameters - 1);
3416  return false;
3417  }
3418 
3419  return true;
3420 }
int numParameters
Definition: libpq-int.h:176

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

3386 {
3387  if (!res)
3388  return false; /* no way to display error message... */
3389  if (tup_num < 0 || tup_num >= res->ntups)
3390  {
3392  "row number %d is out of range 0..%d",
3393  tup_num, res->ntups - 1);
3394  return false;
3395  }
3396  if (field_num < 0 || field_num >= res->numAttributes)
3397  {
3399  "column number %d is out of range 0..%d",
3400  field_num, res->numAttributes - 1);
3401  return false;
3402  }
3403  return true;
3404 }
int ntups
Definition: libpq-int.h:170

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

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

◆ dupEvents()

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

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

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

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

4193 {
4194  int res = -1;
4195 
4196  if (c > 0 && c < 127)
4197  res = hexlookup[(unsigned char) c];
4198 
4199  return (char) res;
4200 }
static const int8 hexlookup[128]
Definition: fe-exec.c:4180
char * c

References hexlookup, and res.

Referenced by PQunescapeBytea().

◆ getCopyResult()

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

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

2236 {
2237  /*
2238  * If the server connection has been lost, don't pretend everything is
2239  * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
2240  * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
2241  * error in the earlier steps in PQgetResult). The text returned in the
2242  * result is whatever is in conn->errorMessage; we hope that was filled
2243  * with something relevant when the lost connection was detected.
2244  */
2245  if (conn->status != CONNECTION_OK)
2246  {
2249  return pqPrepareAsyncResult(conn);
2250  }
2251 
2252  /* If we have an async result for the COPY, return that */
2253  if (conn->result && conn->result->resultStatus == copytype)
2254  return pqPrepareAsyncResult(conn);
2255 
2256  /* Otherwise, invent a suitable PGresult */
2257  return PQmakeEmptyPGresult(conn, copytype);
2258 }
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:804
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:157
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:851
@ CONNECTION_OK
Definition: libpq-fe.h:60
@ PGASYNC_IDLE
Definition: libpq-int.h:219
PGconn * conn
Definition: streamutil.c:54
PGresult * result
Definition: libpq-int.h:508
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
ConnStatusType status
Definition: libpq-int.h:410
ExecStatusType resultStatus
Definition: libpq-int.h:178

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

2041 {
2043 }
void pqParseInput3(PGconn *conn)
Definition: fe-protocol3.c:63

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

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

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

1315 {
1316  PGcmdQueueEntry *entry;
1317 
1318  if (conn->cmd_queue_recycle == NULL)
1319  {
1320  entry = (PGcmdQueueEntry *) malloc(sizeof(PGcmdQueueEntry));
1321  if (entry == NULL)
1322  {
1324  libpq_gettext("out of memory\n"));
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 appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
struct PGcmdQueueEntry * next
Definition: libpq-int.h:324
PGcmdQueueEntry * cmd_queue_recycle
Definition: libpq-int.h:441
PQExpBufferData errorMessage
Definition: libpq-int.h:585

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

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

◆ pqAppendCmdQueueEntry()

static void pqAppendCmdQueueEntry ( PGconn conn,
PGcmdQueueEntry entry 
)
static

Definition at line 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)
1385  break;
1386  }
1387 }
static void pqPipelineProcessQueue(PGconn *conn)
Definition: fe-exec.c:3083
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:158
@ PQ_PIPELINE_ABORTED
Definition: libpq-fe.h:160
@ PQ_PIPELINE_ON
Definition: libpq-fe.h:159
@ PGASYNC_BUSY
Definition: libpq-int.h:220
Assert(fmt[strlen(fmt) - 1] !='\n')
PGcmdQueueEntry * cmd_queue_tail
Definition: libpq-int.h:435
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:417
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:434

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

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

◆ PQbinaryTuples()

int PQbinaryTuples ( const PGresult res)

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

3357 {
3358  if (!res)
3359  return 0;
3360  return res->binary;
3361 }
int binary
Definition: libpq-int.h:180

References pg_result::binary, and res.

Referenced by HandleCopyResult().

◆ PQclear()

void PQclear ( PGresult res)

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

719 {
720  PGresult_data *block;
721  int i;
722 
723  /* As a convenience, do nothing for a NULL pointer */
724  if (!res)
725  return;
726  /* Also, do nothing if the argument is OOM_result */
727  if ((const PGresult *) res == &OOM_result)
728  return;
729 
730  /* Close down any events we may have */
731  for (i = 0; i < res->nEvents; i++)
732  {
733  /* only send DESTROY to successfully-initialized event procs */
735  {
737 
738  evt.result = res;
739  (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
740  res->events[i].passThrough);
741  }
742  free(res->events[i].name);
743  }
744 
745  if (res->events)
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  if (res->tuples)
757  free(res->tuples);
758 
759  /* zero out the pointer fields to catch programming errors */
760  res->attDescs = NULL;
761  res->tuples = NULL;
762  res->paramDescs = NULL;
763  res->errFields = NULL;
764  res->events = NULL;
765  res->nEvents = 0;
766  /* res->curBlock was zeroed out earlier */
767 
768  /* Free the PGresult structure itself */
769  free(res);
770 }
static const PGresult OOM_result
Definition: fe-exec.c:48
@ PGEVT_RESULTDESTROY
Definition: libpq-events.h:34
char * name
Definition: libpq-int.h:162
bool resultInitialized
Definition: libpq-int.h:165
int nEvents
Definition: libpq-int.h:189
PGresAttDesc * attDescs
Definition: libpq-int.h:172
PGMessageField * errFields
Definition: libpq-int.h:198
PGresParamDesc * paramDescs
Definition: libpq-int.h:177
PGEvent * events
Definition: libpq-int.h:188
PGresult_data * curBlock
Definition: libpq-int.h:209
PGresult_data * next
Definition: libpq-int.h:106

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

◆ pqClearAsyncResult()

void pqClearAsyncResult ( PGconn conn)

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

779 {
780  if (conn->result)
781  PQclear(conn->result);
782  conn->result = NULL;
783  conn->error_result = false;
784  if (conn->next_result)
786  conn->next_result = NULL;
787 }
void PQclear(PGresult *res)
Definition: fe-exec.c:718
PGresult * next_result
Definition: libpq-int.h:510
bool error_result
Definition: libpq-int.h:509

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

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

◆ PQcmdStatus()

char* PQcmdStatus ( PGresult res)

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

3612 {
3613  if (!res)
3614  return NULL;
3615  return res->cmdStatus;
3616 }
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:179

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

3682 {
3683  char *p,
3684  *c;
3685 
3686  if (!res)
3687  return "";
3688 
3689  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3690  {
3691  p = res->cmdStatus + 7;
3692  /* INSERT: skip oid and space */
3693  while (*p && *p != ' ')
3694  p++;
3695  if (*p == 0)
3696  goto interpret_error; /* no space? */
3697  p++;
3698  }
3699  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3700  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3701  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3702  p = res->cmdStatus + 7;
3703  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0 ||
3704  strncmp(res->cmdStatus, "MERGE ", 6) == 0)
3705  p = res->cmdStatus + 6;
3706  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3707  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3708  p = res->cmdStatus + 5;
3709  else
3710  return "";
3711 
3712  /* check that we have an integer (at least one digit, nothing else) */
3713  for (c = p; *c; c++)
3714  {
3715  if (!isdigit((unsigned char) *c))
3716  goto interpret_error;
3717  }
3718  if (c == p)
3719  goto interpret_error;
3720 
3721  return p;
3722 
3723 interpret_error:
3725  "could not interpret result from server: %s",
3726  res->cmdStatus);
3727  return "";
3728 }

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

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

◆ pqCommandQueueAdvance()

void pqCommandQueueAdvance ( PGconn conn)

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

3063 {
3064  PGcmdQueueEntry *prevquery;
3065 
3066  if (conn->cmd_queue_head == NULL)
3067  return;
3068 
3069  /* delink from queue */
3070  prevquery = conn->cmd_queue_head;
3072 
3073  /* and make it recyclable */
3074  prevquery->next = NULL;
3075  pqRecycleCmdQueueEntry(conn, prevquery);
3076 }
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1394

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

Referenced by PQgetResult(), and pqParseInput3().

◆ PQconsumeInput()

int PQconsumeInput ( PGconn conn)

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

2005 {
2006  if (!conn)
2007  return 0;
2008 
2009  /*
2010  * for non-blocking connections try to flush the send-queue, otherwise we
2011  * may never get a response for something that may not have already been
2012  * sent because it's in our write buffer!
2013  */
2014  if (pqIsnonblocking(conn))
2015  {
2016  if (pqFlush(conn) < 0)
2017  return 0;
2018  }
2019 
2020  /*
2021  * Load more data, if available. We do this no matter what state we are
2022  * in, since we are probably getting called because the application wants
2023  * to get rid of a read-select condition. Note that we will NOT block
2024  * waiting for more input.
2025  */
2026  if (pqReadData(conn) < 0)
2027  return 0;
2028 
2029  /* Parsing of the data waits till later. */
2030  return 1;
2031 }
int pqReadData(PGconn *conn)
Definition: fe-misc.c:568
int pqFlush(PGconn *conn)
Definition: fe-misc.c:958
#define pqIsnonblocking(conn)
Definition: libpq-int.h:867

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

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

◆ PQcopyResult()

PGresult* PQcopyResult ( const PGresult src,
int  flags 
)

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

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

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

2489 {
2490  if (!PQexecStart(conn))
2491  return NULL;
2492  if (!PQsendDescribe(conn, 'P', portal))
2493  return NULL;
2494  return PQexecFinish(conn);
2495 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2423
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2355
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2533

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

◆ PQdescribePrepared()

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

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

2470 {
2471  if (!PQexecStart(conn))
2472  return NULL;
2473  if (!PQsendDescribe(conn, 'S', stmt))
2474  return NULL;
2475  return PQexecFinish(conn);
2476 }

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

Referenced by DescribeQuery(), and ECPGdescribe().

◆ PQendcopy()

int PQendcopy ( PGconn conn)

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

2886 {
2887  if (!conn)
2888  return 0;
2889 
2890  return pqEndcopy3(conn);
2891 }
int pqEndcopy3(PGconn *conn)

References conn, and pqEndcopy3().

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

◆ PQenterPipelineMode()

int PQenterPipelineMode ( PGconn conn)

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

2981 {
2982  if (!conn)
2983  return 0;
2984 
2985  /* succeed with no action if already in pipeline mode */
2987  return 1;
2988 
2989  if (conn->asyncStatus != PGASYNC_IDLE)
2990  {
2992  libpq_gettext("cannot enter pipeline mode, connection not idle\n"));
2993  return 0;
2994  }
2995 
2997 
2998  return 1;
2999 }

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

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

◆ PQescapeBytea()

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

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

4333 {
4334  return PQescapeByteaInternal(NULL, from, from_length, to_length,
4336  false /* can't use hex */ );
4337 }
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:4219
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 4316 of file fe-exec.c.

4319 {
4320  if (!conn)
4321  return NULL;
4322 
4323  if (conn->cmd_queue_head == NULL)
4325 
4326  return PQescapeByteaInternal(conn, from, from_length, to_length,
4327  conn->std_strings,
4328  (conn->sversion >= 90000));
4329 }
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:851
bool std_strings
Definition: libpq-int.h:471
int sversion
Definition: libpq-int.h:449

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

4222 {
4223  const unsigned char *vp;
4224  unsigned char *rp;
4225  unsigned char *result;
4226  size_t i;
4227  size_t len;
4228  size_t bslash_len = (std_strings ? 1 : 2);
4229 
4230  /*
4231  * empty string has 1 char ('\0')
4232  */
4233  len = 1;
4234 
4235  if (use_hex)
4236  {
4237  len += bslash_len + 1 + 2 * from_length;
4238  }
4239  else
4240  {
4241  vp = from;
4242  for (i = from_length; i > 0; i--, vp++)
4243  {
4244  if (*vp < 0x20 || *vp > 0x7e)
4245  len += bslash_len + 3;
4246  else if (*vp == '\'')
4247  len += 2;
4248  else if (*vp == '\\')
4249  len += bslash_len + bslash_len;
4250  else
4251  len++;
4252  }
4253  }
4254 
4255  *to_length = len;
4256  rp = result = (unsigned char *) malloc(len);
4257  if (rp == NULL)
4258  {
4259  if (conn)
4261  libpq_gettext("out of memory\n"));
4262  return NULL;
4263  }
4264 
4265  if (use_hex)
4266  {
4267  if (!std_strings)
4268  *rp++ = '\\';
4269  *rp++ = '\\';
4270  *rp++ = 'x';
4271  }
4272 
4273  vp = from;
4274  for (i = from_length; i > 0; i--, vp++)
4275  {
4276  unsigned char c = *vp;
4277 
4278  if (use_hex)
4279  {
4280  *rp++ = hextbl[(c >> 4) & 0xF];
4281  *rp++ = hextbl[c & 0xF];
4282  }
4283  else if (c < 0x20 || c > 0x7e)
4284  {
4285  if (!std_strings)
4286  *rp++ = '\\';
4287  *rp++ = '\\';
4288  *rp++ = (c >> 6) + '0';
4289  *rp++ = ((c >> 3) & 07) + '0';
4290  *rp++ = (c & 07) + '0';
4291  }
4292  else if (c == '\'')
4293  {
4294  *rp++ = '\'';
4295  *rp++ = '\'';
4296  }
4297  else if (c == '\\')
4298  {
4299  if (!std_strings)
4300  {
4301  *rp++ = '\\';
4302  *rp++ = '\\';
4303  }
4304  *rp++ = '\\';
4305  *rp++ = '\\';
4306  }
4307  else
4308  *rp++ = c;
4309  }
4310  *rp = '\0';
4311 
4312  return result;
4313 }
static const char hextbl[]
Definition: fe-exec.c:4178
const void size_t len

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

Referenced by PQescapeBytea(), and PQescapeByteaConn().

◆ PQescapeIdentifier()

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

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

4173 {
4174  return PQescapeInternal(conn, str, len, true);
4175 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:4042

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

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

◆ PQescapeInternal()

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

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

4043 {
4044  const char *s;
4045  char *result;
4046  char *rp;
4047  int num_quotes = 0; /* single or double, depending on as_ident */
4048  int num_backslashes = 0;
4049  int input_len;
4050  int result_size;
4051  char quote_char = as_ident ? '"' : '\'';
4052 
4053  /* We must have a connection, else fail immediately. */
4054  if (!conn)
4055  return NULL;
4056 
4057  if (conn->cmd_queue_head == NULL)
4059 
4060  /* Scan the string for characters that must be escaped. */
4061  for (s = str; (s - str) < len && *s != '\0'; ++s)
4062  {
4063  if (*s == quote_char)
4064  ++num_quotes;
4065  else if (*s == '\\')
4066  ++num_backslashes;
4067  else if (IS_HIGHBIT_SET(*s))
4068  {
4069  int charlen;
4070 
4071  /* Slow path for possible multibyte characters */
4072  charlen = pg_encoding_mblen(conn->client_encoding, s);
4073 
4074  /* Multibyte character overruns allowable length. */
4075  if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
4076  {
4078  libpq_gettext("incomplete multibyte character\n"));
4079  return NULL;
4080  }
4081 
4082  /* Adjust s, bearing in mind that for loop will increment it. */
4083  s += charlen - 1;
4084  }
4085  }
4086 
4087  /* Allocate output buffer. */
4088  input_len = s - str;
4089  result_size = input_len + num_quotes + 3; /* two quotes, plus a NUL */
4090  if (!as_ident && num_backslashes > 0)
4091  result_size += num_backslashes + 2;
4092  result = rp = (char *) malloc(result_size);
4093  if (rp == NULL)
4094  {
4096  libpq_gettext("out of memory\n"));
4097  return NULL;
4098  }
4099 
4100  /*
4101  * If we are escaping a literal that contains backslashes, we use the
4102  * escape string syntax so that the result is correct under either value
4103  * of standard_conforming_strings. We also emit a leading space in this
4104  * case, to guard against the possibility that the result might be
4105  * interpolated immediately following an identifier.
4106  */
4107  if (!as_ident && num_backslashes > 0)
4108  {
4109  *rp++ = ' ';
4110  *rp++ = 'E';
4111  }
4112 
4113  /* Opening quote. */
4114  *rp++ = quote_char;
4115 
4116  /*
4117  * Use fast path if possible.
4118  *
4119  * We've already verified that the input string is well-formed in the
4120  * current encoding. If it contains no quotes and, in the case of
4121  * literal-escaping, no backslashes, then we can just copy it directly to
4122  * the output buffer, adding the necessary quotes.
4123  *
4124  * If not, we must rescan the input and process each character
4125  * individually.
4126  */
4127  if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
4128  {
4129  memcpy(rp, str, input_len);
4130  rp += input_len;
4131  }
4132  else
4133  {
4134  for (s = str; s - str < input_len; ++s)
4135  {
4136  if (*s == quote_char || (!as_ident && *s == '\\'))
4137  {
4138  *rp++ = *s;
4139  *rp++ = *s;
4140  }
4141  else if (!IS_HIGHBIT_SET(*s))
4142  *rp++ = *s;
4143  else
4144  {
4146 
4147  while (1)
4148  {
4149  *rp++ = *s;
4150  if (--i == 0)
4151  break;
4152  ++s; /* for loop will provide the final increment */
4153  }
4154  }
4155  }
4156  }
4157 
4158  /* Closing quote and terminating NUL. */
4159  *rp++ = quote_char;
4160  *rp = '\0';
4161 
4162  return result;
4163 }
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1153
int client_encoding
Definition: libpq-int.h:470
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:2129

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

Referenced by PQescapeIdentifier(), and PQescapeLiteral().

◆ PQescapeLiteral()

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

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

4167 {
4168  return PQescapeInternal(conn, str, len, false);
4169 }

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

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

◆ PQescapeString()

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

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

4028 {
4029  return PQescapeStringInternal(NULL, to, from, length, NULL,
4032 }
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:3930
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 4005 of file fe-exec.c.

4008 {
4009  if (!conn)
4010  {
4011  /* force empty-string result */
4012  *to = '\0';
4013  if (error)
4014  *error = 1;
4015  return 0;
4016  }
4017 
4018  if (conn->cmd_queue_head == NULL)
4020 
4021  return PQescapeStringInternal(conn, to, from, length, error,
4023  conn->std_strings);
4024 }
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 3930 of file fe-exec.c.

3934 {
3935  const char *source = from;
3936  char *target = to;
3937  size_t remaining = length;
3938 
3939  if (error)
3940  *error = 0;
3941 
3942  while (remaining > 0 && *source != '\0')
3943  {
3944  char c = *source;
3945  int len;
3946  int i;
3947 
3948  /* Fast path for plain ASCII */
3949  if (!IS_HIGHBIT_SET(c))
3950  {
3951  /* Apply quoting if needed */
3952  if (SQL_STR_DOUBLE(c, !std_strings))
3953  *target++ = c;
3954  /* Copy the character */
3955  *target++ = c;
3956  source++;
3957  remaining--;
3958  continue;
3959  }
3960 
3961  /* Slow path for possible multibyte characters */
3963 
3964  /* Copy the character */
3965  for (i = 0; i < len; i++)
3966  {
3967  if (remaining == 0 || *source == '\0')
3968  break;
3969  *target++ = *source++;
3970  remaining--;
3971  }
3972 
3973  /*
3974  * If we hit premature end of string (ie, incomplete multibyte
3975  * character), try to pad out to the correct length with spaces. We
3976  * may not be able to pad completely, but we will always be able to
3977  * insert at least one pad space (since we'd not have quoted a
3978  * multibyte character). This should be enough to make a string that
3979  * the server will error out on.
3980  */
3981  if (i < len)
3982  {
3983  if (error)
3984  *error = 1;
3985  if (conn)
3987  libpq_gettext("incomplete multibyte character\n"));
3988  for (; i < len; i++)
3989  {
3990  if (((size_t) (target - to)) / 2 >= length)
3991  break;
3992  *target++ = ' ';
3993  }
3994  break;
3995  }
3996  }
3997 
3998  /* Write the terminating NUL character. */
3999  *target = '\0';
4000 
4001  return target - to;
4002 }
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:1161
int remaining
Definition: informix.c:667
int32 encoding
Definition: pg_database.h:41
static rewind_source * source
Definition: pg_rewind.c:81

References appendPQExpBufferStr(), conn, encoding, error(), pg_conn::errorMessage, i, IS_HIGHBIT_SET, len, libpq_gettext, 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 2273 of file fe-exec.c.

2274 {
2275  if (!PQexecStart(conn))
2276  return NULL;
2277  if (!PQsendQuery(conn, query))
2278  return NULL;
2279  return PQexecFinish(conn);
2280 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1424

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

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

◆ PQexecFinish()

static PGresult * PQexecFinish ( PGconn conn)
static

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

2424 {
2425  PGresult *result;
2426  PGresult *lastResult;
2427 
2428  /*
2429  * For backwards compatibility, return the last result if there are more
2430  * than one. (We used to have logic here to concatenate successive error
2431  * messages, but now that happens automatically, since conn->errorMessage
2432  * will continue to accumulate errors throughout this loop.)
2433  *
2434  * We have to stop if we see copy in/out/both, however. We will resume
2435  * parsing after application performs the data transfer.
2436  *
2437  * Also stop if the connection is lost (else we'll loop infinitely).
2438  */
2439  lastResult = NULL;
2440  while ((result = PQgetResult(conn)) != NULL)
2441  {
2442  if (lastResult)
2443  PQclear(lastResult);
2444  lastResult = result;
2445  if (result->resultStatus == PGRES_COPY_IN ||
2446  result->resultStatus == PGRES_COPY_OUT ||
2447  result->resultStatus == PGRES_COPY_BOTH ||
2449  break;
2450  }
2451 
2452  return lastResult;
2453 }
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2082
@ CONNECTION_BAD
Definition: libpq-fe.h:61
@ PGRES_COPY_IN
Definition: libpq-fe.h:104
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:109
@ PGRES_COPY_OUT
Definition: libpq-fe.h:103

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

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

◆ PQexecParams()

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

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

2295 {
2296  if (!PQexecStart(conn))
2297  return NULL;
2298  if (!PQsendQueryParams(conn, command,
2299  nParams, paramTypes, paramValues, paramLengths,
2300  paramFormats, resultFormat))
2301  return NULL;
2302  return PQexecFinish(conn);
2303 }
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:1536

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

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

◆ PQexecPrepared()

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

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

2341 {
2342  if (!PQexecStart(conn))
2343  return NULL;
2344  if (!PQsendQueryPrepared(conn, stmtName,
2345  nParams, paramValues, paramLengths,
2346  paramFormats, resultFormat))
2347  return NULL;
2348  return PQexecFinish(conn);
2349 }
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:1682

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

Referenced by ecpg_execute(), and try_complete_step().

◆ PQexecStart()

static bool PQexecStart ( PGconn conn)
static

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

2356 {
2357  PGresult *result;
2358 
2359  if (!conn)
2360  return false;
2361 
2362  /*
2363  * Since this is the beginning of a query cycle, reset the error state.
2364  * However, in pipeline mode with something already queued, the error
2365  * buffer belongs to that command and we shouldn't clear it.
2366  */
2367  if (conn->cmd_queue_head == NULL)
2369 
2371  {
2373  libpq_gettext("synchronous command execution functions are not allowed in pipeline mode\n"));
2374  return false;
2375  }
2376 
2377  /*
2378  * Silently discard any prior query result that application didn't eat.
2379  * This is probably poor design, but it's here for backward compatibility.
2380  */
2381  while ((result = PQgetResult(conn)) != NULL)
2382  {
2383  ExecStatusType resultStatus = result->resultStatus;
2384 
2385  PQclear(result); /* only need its status */
2386  if (resultStatus == PGRES_COPY_IN)
2387  {
2388  /* get out of a COPY IN state */
2389  if (PQputCopyEnd(conn,
2390  libpq_gettext("COPY terminated by new PQexec")) < 0)
2391  return false;
2392  /* keep waiting to swallow the copy's failure message */
2393  }
2394  else if (resultStatus == PGRES_COPY_OUT)
2395  {
2396  /*
2397  * Get out of a COPY OUT state: we just switch back to BUSY and
2398  * allow the remaining COPY data to be dropped on the floor.
2399  */
2401  /* keep waiting to swallow the copy's completion message */
2402  }
2403  else if (resultStatus == PGRES_COPY_BOTH)
2404  {
2405  /* We don't allow PQexec during COPY BOTH */
2407  libpq_gettext("PQexec not allowed during COPY BOTH\n"));
2408  return false;
2409  }
2410  /* check for loss of connection, too */
2411  if (conn->status == CONNECTION_BAD)
2412  return false;
2413  }
2414 
2415  /* OK to send a command */
2416  return true;
2417 }
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2683
ExecStatusType
Definition: libpq-fe.h:95

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

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

◆ PQexitPipelineMode()

int PQexitPipelineMode ( PGconn conn)

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

3013 {
3014  if (!conn)
3015  return 0;
3016 
3018  return 1;
3019 
3020  switch (conn->asyncStatus)
3021  {
3022  case PGASYNC_READY:
3023  case PGASYNC_READY_MORE:
3024  /* there are some uncollected results */
3026  libpq_gettext("cannot exit pipeline mode with uncollected results\n"));
3027  return 0;
3028 
3029  case PGASYNC_BUSY:
3031  libpq_gettext("cannot exit pipeline mode while busy\n"));
3032  return 0;
3033 
3034  default:
3035  /* OK */
3036  break;
3037  }
3038 
3039  /* still work to process */
3040  if (conn->cmd_queue_head != NULL)
3041  {
3043  libpq_gettext("cannot exit pipeline mode with uncollected results\n"));
3044  return 0;
3045  }
3046 
3049 
3050  /* Flush any pending data in out buffer */
3051  if (pqFlush(conn) < 0)
3052  return 0; /* error message is setup already */
3053  return 1;
3054 }
@ PGASYNC_READY_MORE
Definition: libpq-int.h:223
@ PGASYNC_READY
Definition: libpq-int.h:221

References appendPQExpBufferStr(), pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, pg_conn::errorMessage, libpq_gettext, PGASYNC_BUSY, PGASYNC_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_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), and test_transaction().

◆ PQfformat()

int PQfformat ( const PGresult res,
int  field_num 
)

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

3568 {
3569  if (!check_field_number(res, field_num))
3570  return 0;
3571  if (res->attDescs)
3572  return res->attDescs[field_num].format;
3573  else
3574  return 0;
3575 }
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3369

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

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

◆ PQflush()

◆ PQfmod()

int PQfmod ( const PGresult res,
int  field_num 
)

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

3601 {
3602  if (!check_field_number(res, field_num))
3603  return 0;
3604  if (res->attDescs)
3605  return res->attDescs[field_num].atttypmod;
3606  else
3607  return 0;
3608 }
int atttypmod
Definition: libpq-fe.h:269

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

Referenced by DescribeQuery(), and ECPGget_desc().

◆ PQfn()

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

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

2923 {
2924  *result_len = 0;
2925 
2926  if (!conn)
2927  return NULL;
2928 
2929  /*
2930  * Since this is the beginning of a query cycle, reset the error state.
2931  * However, in pipeline mode with something already queued, the error
2932  * buffer belongs to that command and we shouldn't clear it.
2933  */
2934  if (conn->cmd_queue_head == NULL)
2936 
2938  {
2940  libpq_gettext("PQfn not allowed in pipeline mode\n"));
2941  return NULL;
2942  }
2943 
2946  {
2948  libpq_gettext("connection in wrong state\n"));
2949  return NULL;
2950  }
2951 
2952  return pqFunctionCall3(conn, fnid,
2953  result_buf, result_len,
2954  result_is_int,
2955  args, nargs);
2956 }
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:860
#define PGINVALID_SOCKET
Definition: port.h:31
pgsocket sock
Definition: libpq-int.h:444

References appendPQExpBufferStr(), generate_unaccent_rules::args, pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, pg_conn::errorMessage, libpq_gettext, 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 3448 of file fe-exec.c.

3449 {
3450  char *field_case;
3451  bool in_quotes;
3452  bool all_lower = true;
3453  const char *iptr;
3454  char *optr;
3455  int i;
3456 
3457  if (!res)
3458  return -1;
3459 
3460  /*
3461  * Note: it is correct to reject a zero-length input string; the proper
3462  * input to match a zero-length field name would be "".
3463  */
3464  if (field_name == NULL ||
3465  field_name[0] == '\0' ||
3466  res->attDescs == NULL)
3467  return -1;
3468 
3469  /*
3470  * Check if we can avoid the strdup() and related work because the
3471  * passed-in string wouldn't be changed before we do the check anyway.
3472  */
3473  for (iptr = field_name; *iptr; iptr++)
3474  {
3475  char c = *iptr;
3476 
3477  if (c == '"' || c != pg_tolower((unsigned char) c))
3478  {
3479  all_lower = false;
3480  break;
3481  }
3482  }
3483 
3484  if (all_lower)
3485  for (i = 0; i < res->numAttributes; i++)
3486  if (strcmp(field_name, res->attDescs[i].name) == 0)
3487  return i;
3488 
3489  /* Fall through to the normal check if that didn't work out. */
3490 
3491  /*
3492  * Note: this code will not reject partially quoted strings, eg
3493  * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
3494  * condition.
3495  */
3496  field_case = strdup(field_name);
3497  if (field_case == NULL)
3498  return -1; /* grotty */
3499 
3500  in_quotes = false;
3501  optr = field_case;
3502  for (iptr = field_case; *iptr; iptr++)
3503  {
3504  char c = *iptr;
3505 
3506  if (in_quotes)
3507  {
3508  if (c == '"')
3509  {
3510  if (iptr[1] == '"')
3511  {
3512  /* doubled quotes become a single quote */
3513  *optr++ = '"';
3514  iptr++;
3515  }
3516  else
3517  in_quotes = false;
3518  }
3519  else
3520  *optr++ = c;
3521  }
3522  else if (c == '"')
3523  in_quotes = true;
3524  else
3525  {
3526  c = pg_tolower((unsigned char) c);
3527  *optr++ = c;
3528  }
3529  }
3530  *optr = '\0';
3531 
3532  for (i = 0; i < res->numAttributes; i++)
3533  {
3534  if (strcmp(field_case, res->attDescs[i].name) == 0)
3535  {
3536  free(field_case);
3537  return i;
3538  }
3539  }
3540  free(field_case);
3541  return -1;
3542 }
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_isn_and_int8_passing_mismatch(), check_for_tables_with_oids(), check_for_user_defined_encoding_conversions(), check_for_user_defined_postfix_ops(), check_proper_datallowconn(), collectComments(), collectSecLabels(), describeOneTableDetails(), dropRoles(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpDatabase(), dumpDomain(), dumpEnumType(), dumpFunc(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoles(), dumpTableSchema(), dumpTSConfig(), dumpUserMappings(), get_db_infos(), get_rel_infos(), get_tablespace_paths(), getAccessMethods(), getAggregates(), getBlobs(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getIndexes(), getInherits(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPolicies(), getProcLangs(), getPublicationNamespaces(), getPublications(), getPublicationTables(), getRules(), getSubscriptions(), getTableAttrs(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), old_9_6_invalidate_hash_indexes(), processExtensionTables(), report_extension_updates(), set_frozenxids(), and show_binary_results().

◆ PQfreemem()

◆ PQfreeNotify()

void PQfreeNotify ( PGnotify notify)

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

3909 {
3910  PQfreemem(notify);
3911 }
void PQfreemem(void *ptr)
Definition: fe-exec.c:3891

References PQfreemem().

◆ PQfsize()

int PQfsize ( const PGresult res,
int  field_num 
)

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

3590 {
3591  if (!check_field_number(res, field_num))
3592  return 0;
3593  if (res->attDescs)
3594  return res->attDescs[field_num].typlen;
3595  else
3596  return 0;
3597 }

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

3546 {
3547  if (!check_field_number(res, field_num))
3548  return InvalidOid;
3549  if (res->attDescs)
3550  return res->attDescs[field_num].tableid;
3551  else
3552  return InvalidOid;
3553 }
#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 3556 of file fe-exec.c.

3557 {
3558  if (!check_field_number(res, field_num))
3559  return 0;
3560  if (res->attDescs)
3561  return res->attDescs[field_num].columnid;
3562  else
3563  return 0;
3564 }
int columnid
Definition: libpq-fe.h:265

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

◆ PQftype()

Oid PQftype ( const PGresult res,
int  field_num 
)

◆ PQgetCopyData()

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

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

2752 {
2753  *buffer = NULL; /* for all failure cases */
2754  if (!conn)
2755  return -2;
2756  if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2758  {
2760  libpq_gettext("no COPY in progress\n"));
2761  return -2;
2762  }
2763  return pqGetCopyData3(conn, buffer, async);
2764 }
int pqGetCopyData3(PGconn *conn, char **buffer, int async)
@ PGASYNC_COPY_OUT
Definition: libpq-int.h:227
@ PGASYNC_COPY_BOTH
Definition: libpq-int.h:228

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

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

◆ PQgetisnull()

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

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

3761 {
3762  if (!check_tuple_field_number(res, tup_num, field_num))
3763  return 1; /* pretend it is null */
3764  if (res->tuples[tup_num][field_num].len == NULL_LEN)
3765  return 1;
3766  else
3767  return 0;
3768 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3384
#define NULL_LEN
Definition: libpq-int.h:134

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(), dumpRoleMembership(), dumpRoles(), dumpTableData_insert(), ecpg_get_data(), ecpg_set_compat_sqlda(), ecpg_set_native_sqlda(), ECPGget_desc(), ExecQueryTuples(), get_db_infos(), getAggregates(), getBlobs(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getNamespaces(), getPolicies(), getProcLangs(), getPublicationTables(), GetSlotInformation(), getSubscriptions(), GetTableInfo(), getTables(), getTriggers(), getTSDictionaries(), getTypes(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_create_slot(), libpqrcv_processTuples(), listTSConfigsVerbose(), listTSParsersVerbose(), make_tuple_from_result_row(), materializeResult(), postgresImportForeignSchema(), printCrosstab(), printQuery(), PrintResultInCrosstab(), process_queued_fetch_requests(), run_simple_query(), RunIdentifySystem(), sqlda_common_total_size(), StoreQueryTuple(), storeRow(), vacuum_one_database(), and verify_heap_slot_handler().

◆ PQgetlength()

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

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

3747 {
3748  if (!check_tuple_field_number(res, tup_num, field_num))
3749  return 0;
3750  if (res->tuples[tup_num][field_num].len != NULL_LEN)
3751  return res->tuples[tup_num][field_num].len;
3752  else
3753  return 0;
3754 }

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 *  s,
int  maxlen 
)

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

2791 {
2792  if (!s || maxlen <= 0)
2793  return EOF;
2794  *s = '\0';
2795  /* maxlen must be at least 3 to hold the \. terminator! */
2796  if (maxlen < 3)
2797  return EOF;
2798 
2799  if (!conn)
2800  return EOF;
2801 
2802  return pqGetline3(conn, s, maxlen);
2803 }
int pqGetline3(PGconn *conn, char *s, int maxlen)

References conn, and pqGetline3().

◆ PQgetlineAsync()

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

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

2838 {
2839  if (!conn)
2840  return -1;
2841 
2842  return pqGetlineAsync3(conn, buffer, bufsize);
2843 }
int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)

References conn, and pqGetlineAsync3().

Referenced by pqGetline3().

◆ PQgetResult()

PGresult* PQgetResult ( PGconn conn)

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

2083 {
2084  PGresult *res;
2085 
2086  if (!conn)
2087  return NULL;
2088 
2089  /* Parse any available data, if our state permits. */
2090  parseInput(conn);
2091 
2092  /* If not ready to return something, block until we are. */
2093  while (conn->asyncStatus == PGASYNC_BUSY)
2094  {
2095  int flushResult;
2096 
2097  /*
2098  * If data remains unsent, send it. Else we might be waiting for the
2099  * result of a command the backend hasn't even got yet.
2100  */
2101  while ((flushResult = pqFlush(conn)) > 0)
2102  {
2103  if (pqWait(false, true, conn))
2104  {
2105  flushResult = -1;
2106  break;
2107  }
2108  }
2109 
2110  /*
2111  * Wait for some more data, and load it. (Note: if the connection has
2112  * been lost, pqWait should return immediately because the socket
2113  * should be read-ready, either with the last server data or with an
2114  * EOF indication. We expect therefore that this won't result in any
2115  * undue delay in reporting a previous write failure.)
2116  */
2117  if (flushResult ||
2118  pqWait(true, false, conn) ||
2119  pqReadData(conn) < 0)
2120  {
2121  /* Report the error saved by pqWait or pqReadData */
2124  return pqPrepareAsyncResult(conn);
2125  }
2126 
2127  /* Parse it. */
2128  parseInput(conn);
2129 
2130  /*
2131  * If we had a write error, but nothing above obtained a query result
2132  * or detected a read error, report the write error.
2133  */
2135  {
2138  return pqPrepareAsyncResult(conn);
2139  }
2140  }
2141 
2142  /* Return the appropriate thing. */
2143  switch (conn->asyncStatus)
2144  {
2145  case PGASYNC_IDLE:
2146  res = NULL; /* query is complete */
2148  {
2149  /*
2150  * We're about to return the NULL that terminates the round of
2151  * results from the current query; prepare to send the results
2152  * of the next query when we're called next.
2153  */
2155  }
2156  break;
2157  case PGASYNC_READY:
2158 
2159  /*
2160  * For any query type other than simple query protocol, we advance
2161  * the command queue here. This is because for simple query
2162  * protocol we can get the READY state multiple times before the
2163  * command is actually complete, since the command string can
2164  * contain many queries. In simple query protocol, the queue
2165  * advance is done by fe-protocol3 when it receives ReadyForQuery.
2166  */
2167  if (conn->cmd_queue_head &&
2172  {
2173  /*
2174  * We're about to send the results of the current query. Set
2175  * us idle now, and ...
2176  */
2178 
2179  /*
2180  * ... in cases when we're sending a pipeline-sync result,
2181  * move queue processing forwards immediately, so that next
2182  * time we're called, we're prepared to return the next result
2183  * received from the server. In all other cases, leave the
2184  * queue state change for next time, so that a terminating
2185  * NULL result is sent.
2186  *
2187  * (In other words: we don't return a NULL after a pipeline
2188  * sync.)
2189  */
2192  }
2193  else
2194  {
2195  /* Set the state back to BUSY, allowing parsing to proceed. */
2197  }
2198  break;
2199  case PGASYNC_READY_MORE:
2201  /* Set the state back to BUSY, allowing parsing to proceed. */
2203  break;
2204  case PGASYNC_COPY_IN:
2206  break;
2207  case PGASYNC_COPY_OUT:
2209  break;
2210  case PGASYNC_COPY_BOTH:
2212  break;
2213  default:
2215  libpq_gettext("unexpected asyncStatus: %d\n"),
2216  (int) conn->asyncStatus);
2218  conn->asyncStatus = PGASYNC_IDLE; /* try to restore valid state */
2220  break;
2221  }
2222 
2223  /* Time to fire PGEVT_RESULTCREATE events, if there are any */
2224  if (res && res->nEvents > 0)
2226 
2227  return res;
2228 }
static void pqSaveWriteError(PGconn *conn)
Definition: fe-exec.c:821
static PGresult * getCopyResult(PGconn *conn, ExecStatusType copytype)
Definition: fe-exec.c:2235
static void parseInput(PGconn *conn)
Definition: fe-exec.c:2040
void pqCommandQueueAdvance(PGconn *conn)
Definition: fe-exec.c:3062
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:983
int PQfireResultCreateEvents(PGconn *conn, PGresult *res)
Definition: libpq-events.c:185
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:111
@ PGASYNC_COPY_IN
Definition: libpq-int.h:226
@ PGQUERY_SIMPLE
Definition: libpq-int.h:310
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
PGQueryClass queryclass
Definition: libpq-int.h:322
bool write_failed
Definition: libpq-int.h:454

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

Referenced by advanceConnectionState(), BaseBackup(), ClearOrSaveAllResults(), consumeQueryResult(), dblink_record_internal(), discardUntilSync(), dumpTableData_copy(), ecpg_process_output(), EndDBCopyMode(), ExecQueryAndProcessResults(), handleCopyIn(), handleCopyOut(), HandleEndOfCopyStream(), libpqrcv_PQgetResult(), pgfdw_finish_pre_commit_cleanup(), pgfdw_get_cleanup_result(), pgfdw_get_result(), PQconnectPoll(), pqEndcopy3(), PQexecFinish(), PQexecStart(), process_queued_fetch_requests(), process_result(), readCommandResponse(), ReceiveCopyData(), ReceiveXlogStream(), storeQueryResult(), StreamLogicalLog(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_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 3735 of file fe-exec.c.

3736 {
3737  if (!check_tuple_field_number(res, tup_num, field_num))
3738  return NULL;
3739  return res->tuples[tup_num][field_num].value;
3740 }

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

◆ pqInternalNotice()

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

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

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

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

2052 {
2053  if (!conn)
2054  return false;
2055 
2056  /* Parse any available data, if our state permits. */
2057  parseInput(conn);
2058 
2059  /*
2060  * PQgetResult will return immediately in all states except BUSY. Also,
2061  * if we've detected read EOF and dropped the connection, we can expect
2062  * that PQgetResult will fail immediately. Note that we do *not* check
2063  * conn->write_failed here --- once that's become set, we know we have
2064  * trouble, but we need to keep trying to read until we have a complete
2065  * server message or detect read EOF.
2066  */
2068 }

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

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

◆ PQisnonblocking()

int PQisnonblocking ( const PGconn conn)

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

3843 {
3844  return pqIsnonblocking(conn);
3845 }

References conn, and pqIsnonblocking.

Referenced by test_disallowed_in_pipeline(), and test_simple_pipeline().

◆ PQisthreadsafe()

int PQisthreadsafe ( void  )

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

3850 {
3851 #ifdef ENABLE_THREAD_SAFETY
3852  return true;
3853 #else
3854  return false;
3855 #endif
3856 }

◆ PQmakeEmptyPGresult()

PGresult* PQmakeEmptyPGresult ( PGconn conn,
ExecStatusType  status 
)

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

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

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

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

◆ PQnfields()

◆ PQnotifies()

PGnotify* PQnotifies ( PGconn conn)

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

2600 {
2601  PGnotify *event;
2602 
2603  if (!conn)
2604  return NULL;
2605 
2606  /* Parse any available data to see if we can extract NOTIFY messages. */
2607  parseInput(conn);
2608 
2609  event = conn->notifyHead;
2610  if (event)
2611  {
2612  conn->notifyHead = event->next;
2613  if (!conn->notifyHead)
2614  conn->notifyTail = NULL;
2615  event->next = NULL; /* don't let app see the internal state */
2616  }
2617  return event;
2618 }
struct pgNotify * next
Definition: libpq-fe.h:193
PGnotify * notifyHead
Definition: libpq-int.h:421
PGnotify * notifyTail
Definition: libpq-int.h:422

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

3775 {
3776  if (!res)
3777  return 0;
3778  return res->numParameters;
3779 }

References pg_result::numParameters, and res.

◆ PQntuples()

int PQntuples ( const PGresult res)

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

3341 {
3342  if (!res)
3343  return 0;
3344  return res->ntups;
3345 }

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

◆ PQoidStatus()

char* PQoidStatus ( const PGresult res)

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

3625 {
3626  /*
3627  * This must be enough to hold the result. Don't laugh, this is better
3628  * than what this function used to do.
3629  */
3630  static char buf[24];
3631 
3632  size_t len;
3633 
3634  if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
3635  return "";
3636 
3637  len = strspn(res->cmdStatus + 7, "0123456789");
3638  if (len > sizeof(buf) - 1)
3639  len = sizeof(buf) - 1;
3640  memcpy(buf, res->cmdStatus + 7, len);
3641  buf[len] = '\0';
3642 
3643  return buf;
3644 }
static char * buf
Definition: pg_test_fsync.c:67

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

◆ PQoidValue()

Oid PQoidValue ( const PGresult res)

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

3653 {
3654  char *endptr = NULL;
3655  unsigned long result;
3656 
3657  if (!res ||
3658  strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
3659  res->cmdStatus[7] < '0' ||
3660  res->cmdStatus[7] > '9')
3661  return InvalidOid;
3662 
3663  result = strtoul(res->cmdStatus + 7, &endptr, 10);
3664 
3665  if (!endptr || (*endptr != ' ' && *endptr != '\0'))
3666  return InvalidOid;
3667  else
3668  return (Oid) result;
3669 }
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 3785 of file fe-exec.c.

3786 {
3787  if (!check_param_number(res, param_num))
3788  return InvalidOid;
3789  if (res->paramDescs)
3790  return res->paramDescs[param_num].typid;
3791  else
3792  return InvalidOid;
3793 }
static int check_param_number(const PGresult *res, int param_num)
Definition: fe-exec.c:3407

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

◆ pqPipelineFlush()

static int pqPipelineFlush ( PGconn conn)
static

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

3876 {
3877  if ((conn->pipelineStatus != PQ_PIPELINE_ON) ||
3879  return pqFlush(conn);
3880  return 0;
3881 }
#define OUTBUFFER_THRESHOLD
Definition: libpq-int.h:872
int outCount
Definition: libpq-int.h:488

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

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

◆ pqPipelineProcessQueue()

static void pqPipelineProcessQueue ( PGconn conn)
static

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

3084 {
3085  switch (conn->asyncStatus)
3086  {
3087  case PGASYNC_COPY_IN:
3088  case PGASYNC_COPY_OUT:
3089  case PGASYNC_COPY_BOTH:
3090  case PGASYNC_READY:
3091  case PGASYNC_READY_MORE:
3092  case PGASYNC_BUSY:
3093  /* client still has to process current query or results */
3094  return;
3095  case PGASYNC_IDLE:
3096  /* next query please */
3097  break;
3098  }
3099 
3100  /* Nothing to do if not in pipeline mode, or queue is empty */
3102  conn->cmd_queue_head == NULL)
3103  return;
3104 
3105  /*
3106  * Reset the error state. This and the next couple of steps correspond to
3107  * what PQsendQueryStart didn't do for this query.
3108  */
3110 
3111  /* Initialize async result-accumulation state */
3113 
3114  /*
3115  * Reset single-row processing mode. (Client has to set it up for each
3116  * query, if desired.)
3117  */
3118  conn->singleRowMode = false;
3119 
3122  {
3123  /*
3124  * In an aborted pipeline we don't get anything from the server for
3125  * each result; we're just discarding commands from the queue until we
3126  * get to the next sync from the server.
3127  *
3128  * The PGRES_PIPELINE_ABORTED results tell the client that its queries
3129  * got aborted.
3130  */
3132  if (!conn->result)
3133  {
3135  libpq_gettext("out of memory\n"));
3137  return;
3138  }
3140  }
3141  else
3142  {
3143  /* allow parsing to continue */
3145  }
3146 }
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:778
@ PGRES_PIPELINE_ABORTED
Definition: libpq-fe.h:112
@ PGQUERY_SYNC
Definition: libpq-int.h:314
bool singleRowMode
Definition: libpq-int.h:418

References appendPQExpBufferStr(), pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, pg_conn::errorMessage, libpq_gettext, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_READY, PGASYNC_READY_MORE, PGQUERY_SYNC, PGRES_PIPELINE_ABORTED, pg_conn::pipelineStatus, PQ_PIPELINE_ABORTED, PQ_PIPELINE_OFF, pqClearAsyncResult(), 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 3169 of file fe-exec.c.

3170 {
3171  PGcmdQueueEntry *entry;
3172 
3173  if (!conn)
3174  return 0;
3175 
3177  {
3179  libpq_gettext("cannot send pipeline when not in pipeline mode\n"));
3180  return 0;
3181  }
3182 
3183  switch (conn->asyncStatus)
3184  {
3185  case PGASYNC_COPY_IN:
3186  case PGASYNC_COPY_OUT:
3187  case PGASYNC_COPY_BOTH:
3188  /* should be unreachable */
3190  "internal error: cannot send pipeline while in COPY\n");
3191  return 0;
3192  case PGASYNC_READY:
3193  case PGASYNC_READY_MORE:
3194  case PGASYNC_BUSY:
3195  case PGASYNC_IDLE:
3196  /* OK to send sync */
3197  break;
3198  }
3199 
3200  entry = pqAllocCmdQueueEntry(conn);
3201  if (entry == NULL)
3202  return 0; /* error msg already set */
3203 
3204  entry->queryclass = PGQUERY_SYNC;
3205  entry->query = NULL;
3206 
3207  /* construct the Sync message */
3208  if (pqPutMsgStart('S', conn) < 0 ||
3209  pqPutMsgEnd(conn) < 0)
3210  goto sendFailed;
3211 
3212  /*
3213  * Give the data a push. In nonblock mode, don't complain if we're unable
3214  * to send it all; PQgetResult() will do any additional flushing needed.
3215  */
3216  if (PQflush(conn) < 0)
3217  goto sendFailed;
3218 
3219  /* OK, it's launched! */
3220  pqAppendCmdQueueEntry(conn, entry);
3221 
3222  return 1;
3223 
3224 sendFailed:
3225  pqRecycleCmdQueueEntry(conn, entry);
3226  /* error message should be set up already */
3227  return 0;
3228 }
int PQflush(PGconn *conn)
Definition: fe-exec.c:3861
static void pqAppendCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1348
static PGcmdQueueEntry * pqAllocCmdQueueEntry(PGconn *conn)
Definition: fe-exec.c:1314
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520

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

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

◆ PQprepare()

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

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

2320 {
2321  if (!PQexecStart(conn))
2322  return NULL;
2323  if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
2324  return NULL;
2325  return PQexecFinish(conn);
2326 }
int PQsendPrepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:1582

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

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

◆ pqPrepareAsyncResult()

PGresult* pqPrepareAsyncResult ( PGconn conn)

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

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

References appendPQExpBufferStr(), conn, pg_conn::error_result, pg_conn::errorMessage, pg_conn::errorReported, PQExpBufferData::len, libpq_gettext, 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 2627 of file fe-exec.c.

2628 {
2629  if (!conn)
2630  return -1;
2631  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2633  {
2635  libpq_gettext("no COPY in progress\n"));
2636  return -1;
2637  }
2638 
2639  /*
2640  * Process any NOTICE or NOTIFY messages that might be pending in the
2641  * input buffer. Since the server might generate many notices during the
2642  * COPY, we want to clean those out reasonably promptly to prevent
2643  * indefinite expansion of the input buffer. (Note: the actual read of
2644  * input data into the input buffer happens down inside pqSendSome, but
2645  * it's not authorized to get rid of the data again.)
2646  */
2647  parseInput(conn);
2648 
2649  if (nbytes > 0)
2650  {
2651  /*
2652  * Try to flush any previously sent data in preference to growing the
2653  * output buffer. If we can't enlarge the buffer enough to hold the
2654  * data, return 0 in the nonblock case, else hard error. (For
2655  * simplicity, always assume 5 bytes of overhead.)
2656  */
2657  if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2658  {
2659  if (pqFlush(conn) < 0)
2660  return -1;
2661  if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2662  conn))
2663  return pqIsnonblocking(conn) ? 0 : -1;
2664  }
2665  /* Send the data (too simple to delegate to fe-protocol files) */
2666  if (pqPutMsgStart('d', conn) < 0 ||
2667  pqPutnchar(buffer, nbytes, conn) < 0 ||
2668  pqPutMsgEnd(conn) < 0)
2669  return -1;
2670  }
2671  return 1;
2672 }
int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:290
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:205
int outBufSize
Definition: libpq-int.h:487

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

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

◆ PQputCopyEnd()

int PQputCopyEnd ( PGconn conn,
const char *  errormsg 
)

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

2684 {
2685  if (!conn)
2686  return -1;
2687  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2689  {
2691  libpq_gettext("no COPY in progress\n"));
2692  return -1;
2693  }
2694 
2695  /*
2696  * Send the COPY END indicator. This is simple enough that we don't
2697  * bother delegating it to the fe-protocol files.
2698  */
2699  if (errormsg)
2700  {
2701  /* Send COPY FAIL */
2702  if (pqPutMsgStart('f', conn) < 0 ||
2703  pqPuts(errormsg, conn) < 0 ||
2704  pqPutMsgEnd(conn) < 0)
2705  return -1;
2706  }
2707  else
2708  {
2709  /* Send COPY DONE */
2710  if (pqPutMsgStart('c', conn) < 0 ||
2711  pqPutMsgEnd(conn) < 0)
2712  return -1;
2713  }
2714 
2715  /*
2716  * If we sent the COPY command in extended-query mode, we must issue a
2717  * Sync as well.
2718  */
2719  if (conn->cmd_queue_head &&
2721  {
2722  if (pqPutMsgStart('S', conn) < 0 ||
2723  pqPutMsgEnd(conn) < 0)
2724  return -1;
2725  }
2726 
2727  /* Return to active duty */
2730  else
2732 
2733  /* Try to flush data */
2734  if (pqFlush(conn) < 0)
2735  return -1;
2736 
2737  return 1;
2738 }
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:155

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

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

◆ PQputline()

int PQputline ( PGconn conn,
const char *  s 
)

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

2855 {
2856  return PQputnbytes(conn, s, strlen(s));
2857 }
int PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2864

References conn, and PQputnbytes().

Referenced by initGenerateDataClientSide().

◆ PQputnbytes()

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

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

2865 {
2866  if (PQputCopyData(conn, buffer, nbytes) > 0)
2867  return 0;
2868  else
2869  return EOF;
2870 }
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2627

References conn, and PQputCopyData().

Referenced by PQputline().

◆ pqRecycleCmdQueueEntry()

static void pqRecycleCmdQueueEntry ( PGconn conn,
PGcmdQueueEntry entry 
)
static

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

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

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

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

◆ PQresStatus()

char* PQresStatus ( ExecStatusType  status)

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

3279 {
3280  if ((unsigned int) status >= lengthof(pgresStatus))
3281  return libpq_gettext("invalid ExecStatusType code");
3282  return pgresStatus[status];
3283 }
#define lengthof(array)
Definition: c.h:734
char *const pgresStatus[]
Definition: fe-exec.c:32

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

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

◆ PQresultAlloc()

void* PQresultAlloc ( PGresult res,
size_t  nBytes 
)

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

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

References OOM_result, pqResultAlloc(), and res.

Referenced by PQsetResultAttrs().

◆ pqResultAlloc()

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

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

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

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

3326 {
3327  PGMessageField *pfield;
3328 
3329  if (!res)
3330  return NULL;
3331  for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
3332  {
3333  if (pfield->code == fieldcode)
3334  return pfield->contents;
3335  }
3336  return NULL;
3337 }
struct pgMessageField * next
Definition: libpq-int.h:145
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:147

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

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

◆ PQresultErrorMessage()

◆ PQresultMemorySize()

size_t PQresultMemorySize ( const PGresult res)

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

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

References pg_result::memorySize, and res.

◆ PQresultStatus()

ExecStatusType PQresultStatus ( const PGresult res)

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

3271 {
3272  if (!res)
3273  return PGRES_FATAL_ERROR;
3274  return res->resultStatus;
3275 }

References PGRES_FATAL_ERROR, res, and pg_result::resultStatus.

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

◆ pqResultStrdup()

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

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

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

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

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

◆ PQresultVerboseErrorMessage()

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

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

3297 {
3298  PQExpBufferData workBuf;
3299 
3300  /*
3301  * Because the caller is expected to free the result string, we must
3302  * strdup any constant result. We use plain strdup and document that
3303  * callers should expect NULL if out-of-memory.
3304  */
3305  if (!res ||
3308  return strdup(libpq_gettext("PGresult is not an error result\n"));
3309 
3310  initPQExpBuffer(&workBuf);
3311 
3312  pqBuildErrorMessage3(&workBuf, res, verbosity, show_context);
3313 
3314  /* If insufficient memory to format the message, fail cleanly */
3315  if (PQExpBufferDataBroken(workBuf))
3316  {
3317  termPQExpBuffer(&workBuf);
3318  return strdup(libpq_gettext("out of memory\n"));
3319  }
3320 
3321  return workBuf.data;
3322 }
void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
#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 1208 of file fe-exec.c.

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

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

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

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

1062 {
1063  PGMessageField *pfield;
1064 
1065  pfield = (PGMessageField *)
1067  offsetof(PGMessageField, contents) +
1068  strlen(value) + 1,
1069  true);
1070  if (!pfield)
1071  return; /* out of memory? */
1072  pfield->code = code;
1073  strcpy(pfield->contents, value);
1074  pfield->next = res->errFields;
1075  res->errFields = pfield;
1076 }
#define offsetof(type, field)
Definition: c.h:727

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

Referenced by pqGetErrorNotice3(), and pqInternalNotice().

◆ pqSaveParameterStatus()

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

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

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

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

Referenced by getParameterStatus().

◆ pqSaveWriteError()

static void pqSaveWriteError ( PGconn conn)
static

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

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

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

Referenced by PQgetResult().

◆ PQsendDescribe()

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

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

2534 {
2535  PGcmdQueueEntry *entry = NULL;
2536 
2537  /* Treat null desc_target as empty string */
2538  if (!desc_target)
2539  desc_target = "";
2540 
2541  if (!PQsendQueryStart(conn, true))
2542  return 0;
2543 
2544  entry = pqAllocCmdQueueEntry(conn);
2545  if (entry == NULL)
2546  return 0; /* error msg already set */
2547 
2548  /* construct the Describe message */
2549  if (pqPutMsgStart('D', conn) < 0 ||
2550  pqPutc(desc_type, conn) < 0 ||
2551  pqPuts(desc_target, conn) < 0 ||
2552  pqPutMsgEnd(conn) < 0)
2553  goto sendFailed;
2554 
2555  /* construct the Sync message */
2557  {
2558  if (pqPutMsgStart('S', conn) < 0 ||
2559  pqPutMsgEnd(conn) < 0)
2560  goto sendFailed;
2561  }
2562 
2563  /* remember we are doing a Describe */
2564  entry->queryclass = PGQUERY_DESCRIBE;
2565 
2566  /*
2567  * Give the data a push (in pipeline mode, only if we're past the size
2568  * threshold). In nonblock mode, don't complain if we're unable to send
2569  * it all; PQgetResult() will do any additional flushing needed.
2570  */
2571  if (pqPipelineFlush(conn) < 0)
2572  goto sendFailed;
2573 
2574  /* OK, it's launched! */
2575  pqAppendCmdQueueEntry(conn, entry);
2576 
2577  return 1;
2578 
2579 sendFailed:
2580  pqRecycleCmdQueueEntry(conn, entry);
2581  /* error message should be set up already */
2582  return 0;
2583 }
static int pqPipelineFlush(PGconn *conn)
Definition: fe-exec.c:3875
static bool PQsendQueryStart(PGconn *conn, bool newQuery)
Definition: fe-exec.c:1724
int pqPutc(char c, PGconn *conn)
Definition: fe-misc.c:95
@ PGQUERY_DESCRIBE
Definition: libpq-int.h:313

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

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

◆ PQsendDescribePortal()

int PQsendDescribePortal ( PGconn conn,
const char *  portal 
)

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

2519 {
2520  return PQsendDescribe(conn, 'P', portal);
2521 }

References conn, and PQsendDescribe().

Referenced by test_prepared().

◆ PQsendDescribePrepared()

int PQsendDescribePrepared ( PGconn conn,
const char *  stmt 
)

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

2506 {
2507  return PQsendDescribe(conn, 'S', stmt);
2508 }

References conn, and PQsendDescribe().

Referenced by test_prepared().

◆ PQsendFlushRequest()

int PQsendFlushRequest ( PGconn conn)

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

3237 {
3238  if (!conn)
3239  return 0;
3240 
3241  /* Don't try to send if we know there's no live connection. */
3242  if (conn->status != CONNECTION_OK)
3243  {
3245  libpq_gettext("no connection to the server\n"));
3246  return 0;
3247  }
3248 
3249  /* Can't send while already busy, either, unless enqueuing for later */
3250  if (conn->asyncStatus != PGASYNC_IDLE &&
3252  {
3254  libpq_gettext("another command is already in progress\n"));
3255  return 0;
3256  }
3257 
3258  if (pqPutMsgStart('H', conn) < 0 ||
3259  pqPutMsgEnd(conn) < 0)
3260  {
3261  return 0;
3262  }
3263 
3264  return 1;
3265 }

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

Referenced by test_nosync(), and test_uniqviol().

◆ PQsendPrepare()

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

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

1585 {
1586  PGcmdQueueEntry *entry = NULL;
1587 
1588  if (!PQsendQueryStart(conn, true))
1589  return 0;
1590 
1591  /* check the arguments */
1592  if (!stmtName)
1593  {
1595  libpq_gettext("statement name is a null pointer\n"));
1596  return 0;
1597  }
1598  if (!query)
1599  {
1601  libpq_gettext("command string is a null pointer\n"));
1602  return 0;
1603  }
1604  if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1605  {
1607  libpq_gettext("number of parameters must be between 0 and %d\n"),
1609  return 0;
1610  }
1611 
1612  entry = pqAllocCmdQueueEntry(conn);
1613  if (entry == NULL)
1614  return 0; /* error msg already set */
1615 
1616  /* construct the Parse message */
1617  if (pqPutMsgStart('P', conn) < 0 ||
1618  pqPuts(stmtName, conn) < 0 ||
1619  pqPuts(query, conn) < 0)
1620  goto sendFailed;
1621 
1622  if (nParams > 0 && paramTypes)
1623  {
1624  int i;
1625 
1626  if (pqPutInt(nParams, 2, conn) < 0)
1627  goto sendFailed;
1628  for (i = 0; i < nParams; i++)
1629  {
1630  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1631  goto sendFailed;
1632  }
1633  }
1634  else
1635  {
1636  if (pqPutInt(0, 2, conn) < 0)
1637  goto sendFailed;
1638  }
1639  if (pqPutMsgEnd(conn) < 0)
1640  goto sendFailed;
1641 
1642  /* Add a Sync, unless in pipeline mode. */
1644  {
1645  if (pqPutMsgStart('S', conn) < 0 ||
1646  pqPutMsgEnd(conn) < 0)
1647  goto sendFailed;
1648  }
1649 
1650  /* remember we are doing just a Parse */
1651  entry->queryclass = PGQUERY_PREPARE;
1652 
1653  /* and remember the query text too, if possible */
1654  /* if insufficient memory, query just winds up NULL */
1655  entry->query = strdup(query);
1656 
1657  /*
1658  * Give the data a push (in pipeline mode, only if we're past the size
1659  * threshold). In nonblock mode, don't complain if we're unable to send
1660  * it all; PQgetResult() will do any additional flushing needed.
1661  */
1662  if (pqPipelineFlush(conn) < 0)
1663  goto sendFailed;
1664 
1665  /* OK, it's launched! */
1666  pqAppendCmdQueueEntry(conn, entry);
1667 
1668  return 1;
1669 
1670 sendFailed:
1671  pqRecycleCmdQueueEntry(conn, entry);
1672  /* error message should be set up already */
1673  return 0;
1674 }
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:256
#define PQ_QUERY_PARAM_MAX_LIMIT
Definition: libpq-fe.h:443
@ PGQUERY_PREPARE
Definition: libpq-int.h:312

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

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

◆ PQsendQuery()

◆ PQsendQueryContinue()

int PQsendQueryContinue ( PGconn conn,
const char *  query 
)

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

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

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

1816 {
1817  int i;
1818  PGcmdQueueEntry *entry;
1819 
1820  entry = pqAllocCmdQueueEntry(conn);
1821  if (entry == NULL)
1822  return 0; /* error msg already set */
1823 
1824  /*
1825  * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync
1826  * (if not in pipeline mode), using specified statement name and the
1827  * unnamed portal.
1828  */
1829 
1830  if (command)
1831  {
1832  /* construct the Parse message */
1833  if (pqPutMsgStart('P', conn) < 0 ||
1834  pqPuts(stmtName, conn) < 0 ||
1835  pqPuts(command, conn) < 0)
1836  goto sendFailed;
1837  if (nParams > 0 && paramTypes)
1838  {
1839  if (pqPutInt(nParams, 2, conn) < 0)
1840  goto sendFailed;
1841  for (i = 0; i < nParams; i++)
1842  {
1843  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1844  goto sendFailed;
1845  }
1846  }
1847  else
1848  {
1849  if (pqPutInt(0, 2, conn) < 0)
1850  goto sendFailed;
1851  }
1852  if (pqPutMsgEnd(conn) < 0)
1853  goto sendFailed;
1854  }
1855 
1856  /* Construct the Bind message */
1857  if (pqPutMsgStart('B', conn) < 0 ||
1858  pqPuts("", conn) < 0 ||
1859  pqPuts(stmtName, conn) < 0)
1860  goto sendFailed;
1861 
1862  /* Send parameter formats */
1863  if (nParams > 0 && paramFormats)
1864  {
1865  if (pqPutInt(nParams, 2, conn) < 0)
1866  goto sendFailed;
1867  for (i = 0; i < nParams; i++)
1868  {
1869  if (pqPutInt(paramFormats[i], 2, conn) < 0)
1870  goto sendFailed;
1871  }
1872  }
1873  else
1874  {
1875  if (pqPutInt(0, 2, conn) < 0)
1876  goto sendFailed;
1877  }
1878 
1879  if (pqPutInt(nParams, 2, conn) < 0)
1880  goto sendFailed;
1881 
1882  /* Send parameters */
1883  for (i = 0; i < nParams; i++)
1884  {
1885  if (paramValues && paramValues[i])
1886  {
1887  int nbytes;
1888 
1889  if (paramFormats && paramFormats[i] != 0)
1890  {
1891  /* binary parameter */
1892  if (paramLengths)
1893  nbytes = paramLengths[i];
1894  else
1895  {
1897  libpq_gettext("length must be given for binary parameter\n"));
1898  goto sendFailed;
1899  }
1900  }
1901  else
1902  {
1903  /* text parameter, do not use paramLengths */
1904  nbytes = strlen(paramValues[i]);
1905  }
1906  if (pqPutInt(nbytes, 4, conn) < 0 ||
1907  pqPutnchar(paramValues[i], nbytes, conn) < 0)
1908  goto sendFailed;
1909  }
1910  else
1911  {
1912  /* take the param as NULL */
1913  if (pqPutInt(-1, 4, conn) < 0)
1914  goto sendFailed;
1915  }
1916  }
1917  if (pqPutInt(1, 2, conn) < 0 ||
1918  pqPutInt(resultFormat, 2, conn))
1919  goto sendFailed;
1920  if (pqPutMsgEnd(conn) < 0)
1921  goto sendFailed;
1922 
1923  /* construct the Describe Portal message */
1924  if (pqPutMsgStart('D', conn) < 0 ||
1925  pqPutc('P', conn) < 0 ||
1926  pqPuts("", conn) < 0 ||
1927  pqPutMsgEnd(conn) < 0)
1928  goto sendFailed;
1929 
1930  /* construct the Execute message */
1931  if (pqPutMsgStart('E', conn) < 0 ||
1932  pqPuts("", conn) < 0 ||
1933  pqPutInt(0, 4, conn) < 0 ||
1934  pqPutMsgEnd(conn) < 0)
1935  goto sendFailed;
1936 
1937  /* construct the Sync message if not in pipeline mode */
1939  {
1940  if (pqPutMsgStart('S', conn) < 0 ||
1941  pqPutMsgEnd(conn) < 0)
1942  goto sendFailed;
1943  }
1944 
1945  /* remember we are using extended query protocol */
1946  entry->queryclass = PGQUERY_EXTENDED;
1947 
1948  /* and remember the query text too, if possible */
1949  /* if insufficient memory, query just winds up NULL */
1950  if (command)
1951  entry->query = strdup(command);
1952 
1953  /*
1954  * Give the data a push (in pipeline mode, only if we're past the size
1955  * threshold). In nonblock mode, don't complain if we're unable to send
1956  * it all; PQgetResult() will do any additional flushing needed.
1957  */
1958  if (pqPipelineFlush(conn) < 0)
1959  goto sendFailed;
1960 
1961  /* OK, it's launched! */
1962  pqAppendCmdQueueEntry(conn, entry);
1963 
1964  return 1;
1965 
1966 sendFailed:
1967  pqRecycleCmdQueueEntry(conn, entry);
1968  /* error message should be set up already */
1969  return 0;
1970 }
@ PGQUERY_EXTENDED
Definition: libpq-int.h:311

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

Referenced by PQsendQueryParams(), and PQsendQueryPrepared().

◆ PQsendQueryInternal()

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

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

1437 {
1438  PGcmdQueueEntry *entry = NULL;
1439 
1440  if (!PQsendQueryStart(conn, newQuery))
1441  return 0;
1442 
1443  /* check the argument */
1444  if (!query)
1445  {
1447  libpq_gettext("command string is a null pointer\n"));
1448  return 0;
1449  }
1450 
1451  entry = pqAllocCmdQueueEntry(conn);
1452  if (entry == NULL)
1453  return 0; /* error msg already set */
1454 
1455  /* Send the query message(s) */
1457  {
1458  /* construct the outgoing Query message */
1459  if (pqPutMsgStart('Q', conn) < 0 ||
1460  pqPuts(query, conn) < 0 ||
1461  pqPutMsgEnd(conn) < 0)
1462  {
1463  /* error message should be set up already */
1464  pqRecycleCmdQueueEntry(conn, entry);
1465  return 0;
1466  }
1467 
1468  /* remember we are using simple query protocol */
1469  entry->queryclass = PGQUERY_SIMPLE;
1470  /* and remember the query text too, if possible */
1471  entry->query = strdup(query);
1472  }
1473  else
1474  {
1475  /*
1476  * In pipeline mode we cannot use the simple protocol, so we send
1477  * Parse, Bind, Describe Portal, Execute, Close Portal (with the
1478  * unnamed portal).
1479  */
1480  if (pqPutMsgStart('P', conn) < 0 ||
1481  pqPuts("", conn) < 0 ||
1482  pqPuts(query, conn) < 0 ||
1483  pqPutInt(0, 2, conn) < 0 ||
1484  pqPutMsgEnd(conn) < 0)
1485  goto sendFailed;
1486  if (pqPutMsgStart('B', conn) < 0 ||
1487  pqPuts("", conn) < 0 ||
1488  pqPuts("", conn) < 0 ||
1489  pqPutInt(0, 2, conn) < 0 ||
1490  pqPutInt(0, 2, conn) < 0 ||
1491  pqPutInt(0, 2, conn) < 0 ||
1492  pqPutMsgEnd(conn) < 0)
1493  goto sendFailed;
1494  if (pqPutMsgStart('D', conn) < 0 ||
1495  pqPutc('P', conn) < 0 ||
1496  pqPuts("", conn) < 0 ||
1497  pqPutMsgEnd(conn) < 0)
1498  goto sendFailed;
1499  if (pqPutMsgStart('E', conn) < 0 ||
1500  pqPuts("", conn) < 0 ||
1501  pqPutInt(0, 4, conn) < 0 ||
1502  pqPutMsgEnd(conn) < 0)
1503  goto sendFailed;
1504  if (pqPutMsgStart('C', conn) < 0 ||
1505  pqPutc('P', conn) < 0 ||
1506  pqPuts("", conn) < 0 ||
1507  pqPutMsgEnd(conn) < 0)
1508  goto sendFailed;
1509 
1510  entry->queryclass = PGQUERY_EXTENDED;
1511  entry->query = strdup(query);
1512  }
1513 
1514  /*
1515  * Give the data a push. In nonblock mode, don't complain if we're unable
1516  * to send it all; PQgetResult() will do any additional flushing needed.
1517  */
1518  if (pqPipelineFlush(conn) < 0)
1519  goto sendFailed;
1520 
1521  /* OK, it's launched! */
1522  pqAppendCmdQueueEntry(conn, entry);
1523  return 1;
1524 
1525 sendFailed:
1526  pqRecycleCmdQueueEntry(conn, entry);
1527  /* error message should be set up already */
1528  return 0;
1529 }

References appendPQExpBufferStr(), conn, pg_conn::errorMessage, libpq_gettext, PGQUERY_EXTENDED, PGQUERY_SIMPLE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqAllocCmdQueueEntry(), pqAppendCmdQueueEntry(), pqPipelineFlush(), pqPutc(), pqPutInt(), 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 1536 of file fe-exec.c.

1544 {
1545  if (!PQsendQueryStart(conn, true))
1546  return 0;
1547 
1548  /* check the arguments */
1549  if (!command)
1550  {
1552  libpq_gettext("command string is a null pointer\n"));
1553  return 0;
1554  }
1555  if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1556  {
1558  libpq_gettext("number of parameters must be between 0 and %d\n"),
1560  return 0;
1561  }
1562 
1563  return PQsendQueryGuts(conn,
1564  command,
1565  "", /* use unnamed statement */
1566  nParams,
1567  paramTypes,
1568  paramValues,
1569  paramLengths,
1570  paramFormats,
1571  resultFormat);
1572 }
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:1807

References appendPQExpBuffer(), appendPQExpBufferStr(), conn, pg_conn::errorMessage, libpq_gettext, PQ_QUERY_PARAM_MAX_LIMIT, PQsendQueryGuts(), and PQsendQueryStart().

Referenced by create_cursor(), execute_dml_stmt(), PQexecParams(), sendCommand(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), 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 1682 of file fe-exec.c.

1689 {
1690  if (!PQsendQueryStart(conn, true))
1691  return 0;
1692 
1693  /* check the arguments */
1694  if (!stmtName)
1695  {
1697  libpq_gettext("statement name is a null pointer\n"));
1698  return 0;
1699  }
1700  if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1701  {
1703  libpq_gettext("number of parameters must be between 0 and %d\n"),
1705  return 0;
1706  }
1707 
1708  return PQsendQueryGuts(conn,
1709  NULL, /* no command to parse */
1710  stmtName,
1711  nParams,
1712  NULL, /* no param types */
1713  paramValues,
1714  paramLengths,
1715  paramFormats,
1716  resultFormat);
1717 }

References appendPQExpBuffer(), appendPQExpBufferStr(), conn, pg_conn::errorMessage, libpq_gettext, 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 1724 of file fe-exec.c.

1725 {
1726  if (!conn)
1727  return false;
1728 
1729  /*
1730  * If this is the beginning of a query cycle, reset the error state.
1731  * However, in pipeline mode with something already queued, the error
1732  * buffer belongs to that command and we shouldn't clear it.
1733  */
1734  if (newQuery && conn->cmd_queue_head == NULL)
1736 
1737  /* Don't try to send if we know there's no live connection. */
1738  if (conn->status != CONNECTION_OK)
1739  {
1741  libpq_gettext("no connection to the server\n"));
1742  return false;
1743  }
1744 
1745  /* Can't send while already busy, either, unless enqueuing for later */
1746  if (conn->asyncStatus != PGASYNC_IDLE &&
1748  {
1750  libpq_gettext("another command is already in progress\n"));
1751  return false;
1752  }
1753 
1755  {
1756  /*
1757  * When enqueuing commands we don't change much of the connection
1758  * state since it's already in use for the current command. The
1759  * connection state will get updated when pqPipelineProcessQueue()
1760  * advances to start processing the queued message.
1761  *
1762  * Just make sure we can safely enqueue given the current connection
1763  * state. We can enqueue behind another queue item, or behind a
1764  * non-queue command (one that sends its own sync), but we can't
1765  * enqueue if the connection is in a copy state.
1766  */
1767  switch (conn->asyncStatus)
1768  {
1769  case PGASYNC_IDLE:
1770  case PGASYNC_READY:
1771  case PGASYNC_READY_MORE:
1772  case PGASYNC_BUSY:
1773  /* ok to queue */
1774  break;
1775  case PGASYNC_COPY_IN:
1776  case PGASYNC_COPY_OUT:
1777  case PGASYNC_COPY_BOTH: