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, const char *msg)
 
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)
 
ExecStatusType PQresultStatus (const PGresult *res)
 
char * PQresStatus (ExecStatusType status)
 
char * PQresultErrorMessage (const PGresult *res)
 
char * PQresultVerboseErrorMessage (const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
 
char * PQresultErrorField (const PGresult *res, int fieldcode)
 
int PQntuples (const PGresult *res)
 
int PQnfields (const PGresult *res)
 
int PQbinaryTuples (const PGresult *res)
 
static int check_tuple_field_number (const PGresult *res, int tup_num, int field_num)
 
static int check_param_number (const PGresult *res, int param_num)
 
char * PQfname (const PGresult *res, int field_num)
 
int PQfnumber (const PGresult *res, const char *field_name)
 
Oid PQftable (const PGresult *res, int field_num)
 
int PQftablecol (const PGresult *res, int field_num)
 
int PQfformat (const PGresult *res, int field_num)
 
Oid PQftype (const PGresult *res, int field_num)
 
int PQfsize (const PGresult *res, int field_num)
 
int PQfmod (const PGresult *res, int field_num)
 
char * PQcmdStatus (PGresult *res)
 
char * PQoidStatus (const PGresult *res)
 
Oid PQoidValue (const PGresult *res)
 
char * PQcmdTuples (PGresult *res)
 
char * PQgetvalue (const PGresult *res, int tup_num, int field_num)
 
int PQgetlength (const PGresult *res, int tup_num, int field_num)
 
int PQgetisnull (const PGresult *res, int tup_num, int field_num)
 
int PQnparams (const PGresult *res)
 
Oid PQparamtype (const PGresult *res, int param_num)
 
int PQsetnonblocking (PGconn *conn, int arg)
 
int PQisnonblocking (const PGconn *conn)
 
int PQisthreadsafe (void)
 
int PQflush (PGconn *conn)
 
void PQfreemem (void *ptr)
 
void PQfreeNotify (PGnotify *notify)
 
static size_t PQescapeStringInternal (PGconn *conn, char *to, const char *from, size_t length, int *error, int encoding, bool std_strings)
 
size_t PQescapeStringConn (PGconn *conn, char *to, const char *from, size_t length, int *error)
 
size_t PQescapeString (char *to, const char *from, size_t length)
 
static char * PQescapeInternal (PGconn *conn, const char *str, size_t len, bool as_ident)
 
char * PQescapeLiteral (PGconn *conn, const char *str, size_t len)
 
char * PQescapeIdentifier (PGconn *conn, const char *str, size_t len)
 
static char get_hex (char c)
 
static unsigned char * PQescapeByteaInternal (PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length, bool std_strings, bool use_hex)
 
unsigned char * PQescapeByteaConn (PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length)
 
unsigned char * PQescapeBytea (const unsigned char *from, size_t from_length, size_t *to_length)
 
unsigned char * PQunescapeBytea (const unsigned char *strtext, size_t *retbuflen)
 

Variables

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

Macro Definition Documentation

◆ ISFIRSTOCTDIGIT

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

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

Referenced by PQunescapeBytea().

◆ ISOCTDIGIT

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

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

Referenced by PQunescapeBytea().

◆ OCTVAL

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

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

Referenced by PQunescapeBytea().

◆ PGRESULT_ALIGN_BOUNDARY

#define PGRESULT_ALIGN_BOUNDARY   MAXIMUM_ALIGNOF /* from configure */

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

Referenced by pqResultAlloc().

◆ PGRESULT_BLOCK_OVERHEAD

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

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

Referenced by pqResultAlloc().

◆ PGRESULT_DATA_BLOCKSIZE

#define PGRESULT_DATA_BLOCKSIZE   2048

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

Referenced by pqResultAlloc().

◆ PGRESULT_SEP_ALLOC_THRESHOLD

#define PGRESULT_SEP_ALLOC_THRESHOLD   (PGRESULT_DATA_BLOCKSIZE / 2)

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

Referenced by pqResultAlloc().

Function Documentation

◆ check_field_number()

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

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

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

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

3197 {
3198  if (!res)
3199  return false; /* no way to display error message... */
3200  if (field_num < 0 || field_num >= res->numAttributes)
3201  {
3203  "column number %d is out of range 0..%d",
3204  field_num, res->numAttributes - 1);
3205  return false;
3206  }
3207  return true;
3208 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:825
int numAttributes
Definition: libpq-int.h:170

◆ check_param_number()

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

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

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

Referenced by PQparamtype().

3235 {
3236  if (!res)
3237  return false; /* no way to display error message... */
3238  if (param_num < 0 || param_num >= res->numParameters)
3239  {
3241  "parameter number %d is out of range 0..%d",
3242  param_num, res->numParameters - 1);
3243  return false;
3244  }
3245 
3246  return true;
3247 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:825
int numParameters
Definition: libpq-int.h:175

◆ check_tuple_field_number()

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

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

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

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

3213 {
3214  if (!res)
3215  return false; /* no way to display error message... */
3216  if (tup_num < 0 || tup_num >= res->ntups)
3217  {
3219  "row number %d is out of range 0..%d",
3220  tup_num, res->ntups - 1);
3221  return false;
3222  }
3223  if (field_num < 0 || field_num >= res->numAttributes)
3224  {
3226  "column number %d is out of range 0..%d",
3227  field_num, res->numAttributes - 1);
3228  return false;
3229  }
3230  return true;
3231 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:825
int numAttributes
Definition: libpq-int.h:170
int ntups
Definition: libpq-int.h:169

◆ dupEvents()

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

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

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

Referenced by PQcopyResult(), and PQmakeEmptyPGresult().

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

◆ get_hex()

static char get_hex ( char  c)
inlinestatic

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

References hexlookup.

Referenced by PQunescapeBytea().

4015 {
4016  int res = -1;
4017 
4018  if (c > 0 && c < 127)
4019  res = hexlookup[(unsigned char) c];
4020 
4021  return (char) res;
4022 }
static const int8 hexlookup[128]
Definition: fe-exec.c:4002
char * c

◆ getCopyResult()

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

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

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

Referenced by PQgetResult().

2105 {
2106  /*
2107  * If the server connection has been lost, don't pretend everything is
2108  * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
2109  * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
2110  * error in the earlier steps in PQgetResult). The text returned in the
2111  * result is whatever is in conn->errorMessage; we hope that was filled
2112  * with something relevant when the lost connection was detected.
2113  */
2114  if (conn->status != CONNECTION_OK)
2115  {
2116  pqSaveErrorResult(conn);
2117  conn->asyncStatus = PGASYNC_IDLE;
2118  return pqPrepareAsyncResult(conn);
2119  }
2120 
2121  /* If we have an async result for the COPY, return that */
2122  if (conn->result && conn->result->resultStatus == copytype)
2123  return pqPrepareAsyncResult(conn);
2124 
2125  /* Otherwise, invent a suitable PGresult */
2126  return PQmakeEmptyPGresult(conn, copytype);
2127 }
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:790
PGresult * result
Definition: libpq-int.h:499
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:146
ConnStatusType status
Definition: libpq-int.h:409
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:751
ExecStatusType resultStatus
Definition: libpq-int.h:177

◆ parseInput()

static void parseInput ( PGconn conn)
static

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

References pqParseInput3().

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

1890 {
1891  pqParseInput3(conn);
1892 }
void pqParseInput3(PGconn *conn)
Definition: fe-protocol3.c:63

◆ pqAddTuple()

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

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

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

Referenced by pqRowProcessor(), and PQsetvalue().

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

◆ pqAllocCmdQueueEntry()

static PGcmdQueueEntry* pqAllocCmdQueueEntry ( PGconn conn)
static

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

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

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

1200 {
1201  PGcmdQueueEntry *entry;
1202 
1203  if (conn->cmd_queue_recycle == NULL)
1204  {
1205  entry = (PGcmdQueueEntry *) malloc(sizeof(PGcmdQueueEntry));
1206  if (entry == NULL)
1207  {
1209  libpq_gettext("out of memory\n"));
1210  return NULL;
1211  }
1212  }
1213  else
1214  {
1215  entry = conn->cmd_queue_recycle;
1216  conn->cmd_queue_recycle = entry->next;
1217  }
1218  entry->next = NULL;
1219  entry->query = NULL;
1220 
1221  return entry;
1222 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
struct PGcmdQueueEntry * next
Definition: libpq-int.h:323
#define malloc(a)
Definition: header.h:50
PQExpBufferData errorMessage
Definition: libpq-int.h:569
PGcmdQueueEntry * cmd_queue_recycle
Definition: libpq-int.h:440
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ pqAppendCmdQueueEntry()

static void pqAppendCmdQueueEntry ( PGconn conn,
PGcmdQueueEntry entry 
)
static

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

References Assert, pg_conn::cmd_queue_head, pg_conn::cmd_queue_tail, and PGcmdQueueEntry::next.

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

1233 {
1234  Assert(entry->next == NULL);
1235 
1236  if (conn->cmd_queue_head == NULL)
1237  conn->cmd_queue_head = entry;
1238  else
1239  conn->cmd_queue_tail->next = entry;
1240 
1241  conn->cmd_queue_tail = entry;
1242 }
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:433
struct PGcmdQueueEntry * next
Definition: libpq-int.h:323
PGcmdQueueEntry * cmd_queue_tail
Definition: libpq-int.h:434
#define Assert(condition)
Definition: c.h:804

◆ PQbinaryTuples()

int PQbinaryTuples ( const PGresult res)

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

References pg_result::binary.

Referenced by ProcessResult().

3184 {
3185  if (!res)
3186  return 0;
3187  return res->binary;
3188 }
int binary
Definition: libpq-int.h:179

◆ PQclear()

void PQclear ( PGresult res)

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

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

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

681 {
682  PGresult_data *block;
683  int i;
684 
685  if (!res)
686  return;
687 
688  for (i = 0; i < res->nEvents; i++)
689  {
690  /* only send DESTROY to successfully-initialized event procs */
691  if (res->events[i].resultInitialized)
692  {
694 
695  evt.result = res;
696  (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
697  res->events[i].passThrough);
698  }
699  free(res->events[i].name);
700  }
701 
702  if (res->events)
703  free(res->events);
704 
705  /* Free all the subsidiary blocks */
706  while ((block = res->curBlock) != NULL)
707  {
708  res->curBlock = block->next;
709  free(block);
710  }
711 
712  /* Free the top-level tuple pointer array */
713  if (res->tuples)
714  free(res->tuples);
715 
716  /* zero out the pointer fields to catch programming errors */
717  res->attDescs = NULL;
718  res->tuples = NULL;
719  res->paramDescs = NULL;
720  res->errFields = NULL;
721  res->events = NULL;
722  res->nEvents = 0;
723  /* res->curBlock was zeroed out earlier */
724 
725  /* Free the PGresult structure itself */
726  free(res);
727 }
PGMessageField * errFields
Definition: libpq-int.h:197
bool resultInitialized
Definition: libpq-int.h:164
PGresult_data * next
Definition: libpq-int.h:105
int nEvents
Definition: libpq-int.h:188
PGresAttDesc * attDescs
Definition: libpq-int.h:171
PGresAttValue ** tuples
Definition: libpq-int.h:172
PGresult_data * curBlock
Definition: libpq-int.h:208
#define free(a)
Definition: header.h:65
PGresParamDesc * paramDescs
Definition: libpq-int.h:176
PGEventProc proc
Definition: libpq-int.h:160
int i
void * passThrough
Definition: libpq-int.h:162
PGEvent * events
Definition: libpq-int.h:187
char * name
Definition: libpq-int.h:161

◆ pqClearAsyncResult()

void pqClearAsyncResult ( PGconn conn)

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

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

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

736 {
737  if (conn->result)
738  PQclear(conn->result);
739  conn->result = NULL;
740  if (conn->next_result)
741  PQclear(conn->next_result);
742  conn->next_result = NULL;
743 }
PGresult * result
Definition: libpq-int.h:499
PGresult * next_result
Definition: libpq-int.h:500
void PQclear(PGresult *res)
Definition: fe-exec.c:680

◆ PQcmdStatus()

char* PQcmdStatus ( PGresult res)

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

References pg_result::cmdStatus.

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

3439 {
3440  if (!res)
3441  return NULL;
3442  return res->cmdStatus;
3443 }
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178

◆ PQcmdTuples()

char* PQcmdTuples ( PGresult res)

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

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

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

3509 {
3510  char *p,
3511  *c;
3512 
3513  if (!res)
3514  return "";
3515 
3516  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3517  {
3518  p = res->cmdStatus + 7;
3519  /* INSERT: skip oid and space */
3520  while (*p && *p != ' ')
3521  p++;
3522  if (*p == 0)
3523  goto interpret_error; /* no space? */
3524  p++;
3525  }
3526  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3527  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3528  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3529  p = res->cmdStatus + 7;
3530  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
3531  p = res->cmdStatus + 6;
3532  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3533  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3534  p = res->cmdStatus + 5;
3535  else
3536  return "";
3537 
3538  /* check that we have an integer (at least one digit, nothing else) */
3539  for (c = p; *c; c++)
3540  {
3541  if (!isdigit((unsigned char) *c))
3542  goto interpret_error;
3543  }
3544  if (c == p)
3545  goto interpret_error;
3546 
3547  return p;
3548 
3549 interpret_error:
3551  "could not interpret result from server: %s",
3552  res->cmdStatus);
3553  return "";
3554 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
char * c
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:825
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178

◆ pqCommandQueueAdvance()

void pqCommandQueueAdvance ( PGconn conn)

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

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

Referenced by PQgetResult(), and pqParseInput3().

2927 {
2928  PGcmdQueueEntry *prevquery;
2929 
2930  if (conn->cmd_queue_head == NULL)
2931  return;
2932 
2933  /* delink from queue */
2934  prevquery = conn->cmd_queue_head;
2935  conn->cmd_queue_head = conn->cmd_queue_head->next;
2936 
2937  /* and make it recyclable */
2938  prevquery->next = NULL;
2939  pqRecycleCmdQueueEntry(conn, prevquery);
2940 }
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:433
struct PGcmdQueueEntry * next
Definition: libpq-int.h:323
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1249

◆ PQconsumeInput()

int PQconsumeInput ( PGconn conn)

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

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

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

1854 {
1855  if (!conn)
1856  return 0;
1857 
1858  /*
1859  * for non-blocking connections try to flush the send-queue, otherwise we
1860  * may never get a response for something that may not have already been
1861  * sent because it's in our write buffer!
1862  */
1863  if (pqIsnonblocking(conn))
1864  {
1865  if (pqFlush(conn) < 0)
1866  return 0;
1867  }
1868 
1869  /*
1870  * Load more data, if available. We do this no matter what state we are
1871  * in, since we are probably getting called because the application wants
1872  * to get rid of a read-select condition. Note that we will NOT block
1873  * waiting for more input.
1874  */
1875  if (pqReadData(conn) < 0)
1876  return 0;
1877 
1878  /* Parsing of the data waits till later. */
1879  return 1;
1880 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:965
#define pqIsnonblocking(conn)
Definition: libpq-int.h:835
int pqReadData(PGconn *conn)
Definition: fe-misc.c:568

◆ PQcopyResult()

PGresult* PQcopyResult ( const PGresult src,
int  flags 
)

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

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

Referenced by pqRowProcessor().

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

◆ PQdescribePortal()

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

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

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

2355 {
2356  if (!PQexecStart(conn))
2357  return NULL;
2358  if (!PQsendDescribe(conn, 'P', portal))
2359  return NULL;
2360  return PQexecFinish(conn);
2361 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2399
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2289
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2224

◆ PQdescribePrepared()

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

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

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

Referenced by DescribeQuery(), and ECPGdescribe().

2336 {
2337  if (!PQexecStart(conn))
2338  return NULL;
2339  if (!PQsendDescribe(conn, 'S', stmt))
2340  return NULL;
2341  return PQexecFinish(conn);
2342 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2399
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2289
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2224

◆ PQendcopy()

int PQendcopy ( PGconn conn)

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

References pqEndcopy3().

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

2753 {
2754  if (!conn)
2755  return 0;
2756 
2757  return pqEndcopy3(conn);
2758 }
int pqEndcopy3(PGconn *conn)

◆ PQenterPipelineMode()

int PQenterPipelineMode ( PGconn conn)

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

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

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

2845 {
2846  if (!conn)
2847  return 0;
2848 
2849  /* succeed with no action if already in pipeline mode */
2850  if (conn->pipelineStatus != PQ_PIPELINE_OFF)
2851  return 1;
2852 
2853  if (conn->asyncStatus != PGASYNC_IDLE)
2854  {
2856  libpq_gettext("cannot enter pipeline mode, connection not idle\n"));
2857  return 0;
2858  }
2859 
2861 
2862  return 1;
2863 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:416
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
PQExpBufferData errorMessage
Definition: libpq-int.h:569
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQescapeBytea()

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

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

References PQescapeByteaInternal(), and static_std_strings.

4154 {
4155  return PQescapeByteaInternal(NULL, from, from_length, to_length,
4157  false /* can't use hex */ );
4158 }
static bool static_std_strings
Definition: fe-exec.c:52
static unsigned char * PQescapeByteaInternal(PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length, bool std_strings, bool use_hex)
Definition: fe-exec.c:4041

◆ PQescapeByteaConn()

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

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

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

4141 {
4142  if (!conn)
4143  return NULL;
4144 
4146 
4147  return PQescapeByteaInternal(conn, from, from_length, to_length,
4148  conn->std_strings,
4149  (conn->sversion >= 90000));
4150 }
int sversion
Definition: libpq-int.h:448
PQExpBufferData errorMessage
Definition: libpq-int.h:569
bool std_strings
Definition: libpq-int.h:470
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
static unsigned char * PQescapeByteaInternal(PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length, bool std_strings, bool use_hex)
Definition: fe-exec.c:4041

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

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

Referenced by PQescapeBytea(), and PQescapeByteaConn().

4044 {
4045  const unsigned char *vp;
4046  unsigned char *rp;
4047  unsigned char *result;
4048  size_t i;
4049  size_t len;
4050  size_t bslash_len = (std_strings ? 1 : 2);
4051 
4052  /*
4053  * empty string has 1 char ('\0')
4054  */
4055  len = 1;
4056 
4057  if (use_hex)
4058  {
4059  len += bslash_len + 1 + 2 * from_length;
4060  }
4061  else
4062  {
4063  vp = from;
4064  for (i = from_length; i > 0; i--, vp++)
4065  {
4066  if (*vp < 0x20 || *vp > 0x7e)
4067  len += bslash_len + 3;
4068  else if (*vp == '\'')
4069  len += 2;
4070  else if (*vp == '\\')
4071  len += bslash_len + bslash_len;
4072  else
4073  len++;
4074  }
4075  }
4076 
4077  *to_length = len;
4078  rp = result = (unsigned char *) malloc(len);
4079  if (rp == NULL)
4080  {
4081  if (conn)
4083  libpq_gettext("out of memory\n"));
4084  return NULL;
4085  }
4086 
4087  if (use_hex)
4088  {
4089  if (!std_strings)
4090  *rp++ = '\\';
4091  *rp++ = '\\';
4092  *rp++ = 'x';
4093  }
4094 
4095  vp = from;
4096  for (i = from_length; i > 0; i--, vp++)
4097  {
4098  unsigned char c = *vp;
4099 
4100  if (use_hex)
4101  {
4102  *rp++ = hextbl[(c >> 4) & 0xF];
4103  *rp++ = hextbl[c & 0xF];
4104  }
4105  else if (c < 0x20 || c > 0x7e)
4106  {
4107  if (!std_strings)
4108  *rp++ = '\\';
4109  *rp++ = '\\';
4110  *rp++ = (c >> 6) + '0';
4111  *rp++ = ((c >> 3) & 07) + '0';
4112  *rp++ = (c & 07) + '0';
4113  }
4114  else if (c == '\'')
4115  {
4116  *rp++ = '\'';
4117  *rp++ = '\'';
4118  }
4119  else if (c == '\\')
4120  {
4121  if (!std_strings)
4122  {
4123  *rp++ = '\\';
4124  *rp++ = '\\';
4125  }
4126  *rp++ = '\\';
4127  *rp++ = '\\';
4128  }
4129  else
4130  *rp++ = c;
4131  }
4132  *rp = '\0';
4133 
4134  return result;
4135 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define malloc(a)
Definition: header.h:50
char * c
PQExpBufferData errorMessage
Definition: libpq-int.h:569
static const char hextbl[]
Definition: fe-exec.c:4000
int i
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQescapeIdentifier()

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

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

References PQescapeInternal().

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

3995 {
3996  return PQescapeInternal(conn, str, len, true);
3997 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:3865

◆ PQescapeInternal()

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

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

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

Referenced by PQescapeIdentifier(), and PQescapeLiteral().

3866 {
3867  const char *s;
3868  char *result;
3869  char *rp;
3870  int num_quotes = 0; /* single or double, depending on as_ident */
3871  int num_backslashes = 0;
3872  int input_len;
3873  int result_size;
3874  char quote_char = as_ident ? '"' : '\'';
3875 
3876  /* We must have a connection, else fail immediately. */
3877  if (!conn)
3878  return NULL;
3879 
3881 
3882  /* Scan the string for characters that must be escaped. */
3883  for (s = str; (s - str) < len && *s != '\0'; ++s)
3884  {
3885  if (*s == quote_char)
3886  ++num_quotes;
3887  else if (*s == '\\')
3888  ++num_backslashes;
3889  else if (IS_HIGHBIT_SET(*s))
3890  {
3891  int charlen;
3892 
3893  /* Slow path for possible multibyte characters */
3894  charlen = pg_encoding_mblen(conn->client_encoding, s);
3895 
3896  /* Multibyte character overruns allowable length. */
3897  if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
3898  {
3900  libpq_gettext("incomplete multibyte character\n"));
3901  return NULL;
3902  }
3903 
3904  /* Adjust s, bearing in mind that for loop will increment it. */
3905  s += charlen - 1;
3906  }
3907  }
3908 
3909  /* Allocate output buffer. */
3910  input_len = s - str;
3911  result_size = input_len + num_quotes + 3; /* two quotes, plus a NUL */
3912  if (!as_ident && num_backslashes > 0)
3913  result_size += num_backslashes + 2;
3914  result = rp = (char *) malloc(result_size);
3915  if (rp == NULL)
3916  {
3918  libpq_gettext("out of memory\n"));
3919  return NULL;
3920  }
3921 
3922  /*
3923  * If we are escaping a literal that contains backslashes, we use the
3924  * escape string syntax so that the result is correct under either value
3925  * of standard_conforming_strings. We also emit a leading space in this
3926  * case, to guard against the possibility that the result might be
3927  * interpolated immediately following an identifier.
3928  */
3929  if (!as_ident && num_backslashes > 0)
3930  {
3931  *rp++ = ' ';
3932  *rp++ = 'E';
3933  }
3934 
3935  /* Opening quote. */
3936  *rp++ = quote_char;
3937 
3938  /*
3939  * Use fast path if possible.
3940  *
3941  * We've already verified that the input string is well-formed in the
3942  * current encoding. If it contains no quotes and, in the case of
3943  * literal-escaping, no backslashes, then we can just copy it directly to
3944  * the output buffer, adding the necessary quotes.
3945  *
3946  * If not, we must rescan the input and process each character
3947  * individually.
3948  */
3949  if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
3950  {
3951  memcpy(rp, str, input_len);
3952  rp += input_len;
3953  }
3954  else
3955  {
3956  for (s = str; s - str < input_len; ++s)
3957  {
3958  if (*s == quote_char || (!as_ident && *s == '\\'))
3959  {
3960  *rp++ = *s;
3961  *rp++ = *s;
3962  }
3963  else if (!IS_HIGHBIT_SET(*s))
3964  *rp++ = *s;
3965  else
3966  {
3967  int i = pg_encoding_mblen(conn->client_encoding, s);
3968 
3969  while (1)
3970  {
3971  *rp++ = *s;
3972  if (--i == 0)
3973  break;
3974  ++s; /* for loop will provide the final increment */
3975  }
3976  }
3977  }
3978  }
3979 
3980  /* Closing quote and terminating NUL. */
3981  *rp++ = quote_char;
3982  *rp = '\0';
3983 
3984  return result;
3985 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define malloc(a)
Definition: header.h:50
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1156
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1916
PQExpBufferData errorMessage
Definition: libpq-int.h:569
int i
int client_encoding
Definition: libpq-int.h:469
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQescapeLiteral()

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

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

References PQescapeInternal().

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

3989 {
3990  return PQescapeInternal(conn, str, len, false);
3991 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:3865

◆ PQescapeString()

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

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

References PQescapeStringInternal(), static_client_encoding, and static_std_strings.

Referenced by get_comma_elts(), and quote_postgres().

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

◆ PQescapeStringConn()

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

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

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

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

3832 {
3833  if (!conn)
3834  {
3835  /* force empty-string result */
3836  *to = '\0';
3837  if (error)
3838  *error = 1;
3839  return 0;
3840  }
3841 
3843 
3844  return PQescapeStringInternal(conn, to, from, length, error,
3845  conn->client_encoding,
3846  conn->std_strings);
3847 }
static void error(void)
Definition: sql-dyntest.c:147
PQExpBufferData errorMessage
Definition: libpq-int.h:569
bool std_strings
Definition: libpq-int.h:470
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:3754
int client_encoding
Definition: libpq-int.h:469
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148

◆ PQescapeStringInternal()

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

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

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

Referenced by PQescapeString(), and PQescapeStringConn().

3758 {
3759  const char *source = from;
3760  char *target = to;
3761  size_t remaining = length;
3762 
3763  if (error)
3764  *error = 0;
3765 
3766  while (remaining > 0 && *source != '\0')
3767  {
3768  char c = *source;
3769  int len;
3770  int i;
3771 
3772  /* Fast path for plain ASCII */
3773  if (!IS_HIGHBIT_SET(c))
3774  {
3775  /* Apply quoting if needed */
3776  if (SQL_STR_DOUBLE(c, !std_strings))
3777  *target++ = c;
3778  /* Copy the character */
3779  *target++ = c;
3780  source++;
3781  remaining--;
3782  continue;
3783  }
3784 
3785  /* Slow path for possible multibyte characters */
3786  len = pg_encoding_mblen(encoding, source);
3787 
3788  /* Copy the character */
3789  for (i = 0; i < len; i++)
3790  {
3791  if (remaining == 0 || *source == '\0')
3792  break;
3793  *target++ = *source++;
3794  remaining--;
3795  }
3796 
3797  /*
3798  * If we hit premature end of string (ie, incomplete multibyte
3799  * character), try to pad out to the correct length with spaces. We
3800  * may not be able to pad completely, but we will always be able to
3801  * insert at least one pad space (since we'd not have quoted a
3802  * multibyte character). This should be enough to make a string that
3803  * the server will error out on.
3804  */
3805  if (i < len)
3806  {
3807  if (error)
3808  *error = 1;
3809  if (conn)
3811  libpq_gettext("incomplete multibyte character\n"));
3812  for (; i < len; i++)
3813  {
3814  if (((size_t) (target - to)) / 2 >= length)
3815  break;
3816  *target++ = ' ';
3817  }
3818  break;
3819  }
3820  }
3821 
3822  /* Write the terminating NUL character. */
3823  *target = '\0';
3824 
3825  return target - to;
3826 }
int remaining
Definition: informix.c:667
static void error(void)
Definition: sql-dyntest.c:147
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1156
char * c
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1916
PQExpBufferData errorMessage
Definition: libpq-int.h:569
static rewind_source * source
Definition: pg_rewind.c:79
int32 encoding
Definition: pg_database.h:41
int i
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:1164
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQexec()

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

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

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

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

2143 {
2144  if (!PQexecStart(conn))
2145  return NULL;
2146  if (!PQsendQuery(conn, query))
2147  return NULL;
2148  return PQexecFinish(conn);
2149 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1279
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2289
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2224

◆ PQexecFinish()

static PGresult * PQexecFinish ( PGconn conn)
static

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

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

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

2290 {
2291  PGresult *result;
2292  PGresult *lastResult;
2293 
2294  /*
2295  * For backwards compatibility, return the last result if there are more
2296  * than one. (We used to have logic here to concatenate successive error
2297  * messages, but now that happens automatically, since conn->errorMessage
2298  * will continue to accumulate errors throughout this loop.)
2299  *
2300  * We have to stop if we see copy in/out/both, however. We will resume
2301  * parsing after application performs the data transfer.
2302  *
2303  * Also stop if the connection is lost (else we'll loop infinitely).
2304  */
2305  lastResult = NULL;
2306  while ((result = PQgetResult(conn)) != NULL)
2307  {
2308  if (lastResult)
2309  PQclear(lastResult);
2310  lastResult = result;
2311  if (result->resultStatus == PGRES_COPY_IN ||
2312  result->resultStatus == PGRES_COPY_OUT ||
2313  result->resultStatus == PGRES_COPY_BOTH ||
2314  conn->status == CONNECTION_BAD)
2315  break;
2316  }
2317 
2318  return lastResult;
2319 }
void PQclear(PGresult *res)
Definition: fe-exec.c:680
ConnStatusType status
Definition: libpq-int.h:409
ExecStatusType resultStatus
Definition: libpq-int.h:177
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1927

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

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

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

2164 {
2165  if (!PQexecStart(conn))
2166  return NULL;
2167  if (!PQsendQueryParams(conn, command,
2168  nParams, paramTypes, paramValues, paramLengths,
2169  paramFormats, resultFormat))
2170  return NULL;
2171  return PQexecFinish(conn);
2172 }
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:1387
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2289
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2224

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

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

Referenced by ecpg_execute(), and try_complete_step().

2210 {
2211  if (!PQexecStart(conn))
2212  return NULL;
2213  if (!PQsendQueryPrepared(conn, stmtName,
2214  nParams, paramValues, paramLengths,
2215  paramFormats, resultFormat))
2216  return NULL;
2217  return PQexecFinish(conn);
2218 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2289
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:1533
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2224

◆ PQexecStart()

static bool PQexecStart ( PGconn conn)
static

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

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

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

2225 {
2226  PGresult *result;
2227 
2228  if (!conn)
2229  return false;
2230 
2231  if (conn->pipelineStatus != PQ_PIPELINE_OFF)
2232  {
2234  libpq_gettext("synchronous command execution functions are not allowed in pipeline mode\n"));
2235  return false;
2236  }
2237 
2238  /*
2239  * Since this is the beginning of a query cycle, reset the error buffer.
2240  */
2242 
2243  /*
2244  * Silently discard any prior query result that application didn't eat.
2245  * This is probably poor design, but it's here for backward compatibility.
2246  */
2247  while ((result = PQgetResult(conn)) != NULL)
2248  {
2249  ExecStatusType resultStatus = result->resultStatus;
2250 
2251  PQclear(result); /* only need its status */
2252  if (resultStatus == PGRES_COPY_IN)
2253  {
2254  /* get out of a COPY IN state */
2255  if (PQputCopyEnd(conn,
2256  libpq_gettext("COPY terminated by new PQexec")) < 0)
2257  return false;
2258  /* keep waiting to swallow the copy's failure message */
2259  }
2260  else if (resultStatus == PGRES_COPY_OUT)
2261  {
2262  /*
2263  * Get out of a COPY OUT state: we just switch back to BUSY and
2264  * allow the remaining COPY data to be dropped on the floor.
2265  */
2266  conn->asyncStatus = PGASYNC_BUSY;
2267  /* keep waiting to swallow the copy's completion message */
2268  }
2269  else if (resultStatus == PGRES_COPY_BOTH)
2270  {
2271  /* We don't allow PQexec during COPY BOTH */
2273  libpq_gettext("PQexec not allowed during COPY BOTH\n"));
2274  return false;
2275  }
2276  /* check for loss of connection, too */
2277  if (conn->status == CONNECTION_BAD)
2278  return false;
2279  }
2280 
2281  /* OK to send a command */
2282  return true;
2283 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:416
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2550
ExecStatusType
Definition: libpq-fe.h:83
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
PQExpBufferData errorMessage
Definition: libpq-int.h:569
void PQclear(PGresult *res)
Definition: fe-exec.c:680
ConnStatusType status
Definition: libpq-int.h:409
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
ExecStatusType resultStatus
Definition: libpq-int.h:177
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1927
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQexitPipelineMode()

int PQexitPipelineMode ( PGconn conn)

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

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

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

2877 {
2878  if (!conn)
2879  return 0;
2880 
2881  if (conn->pipelineStatus == PQ_PIPELINE_OFF)
2882  return 1;
2883 
2884  switch (conn->asyncStatus)
2885  {
2886  case PGASYNC_READY:
2887  case PGASYNC_READY_MORE:
2888  /* there are some uncollected results */
2890  libpq_gettext("cannot exit pipeline mode with uncollected results\n"));
2891  return 0;
2892 
2893  case PGASYNC_BUSY:
2895  libpq_gettext("cannot exit pipeline mode while busy\n"));
2896  return 0;
2897 
2898  default:
2899  /* OK */
2900  break;
2901  }
2902 
2903  /* still work to process */
2904  if (conn->cmd_queue_head != NULL)
2905  {
2907  libpq_gettext("cannot exit pipeline mode with uncollected results\n"));
2908  return 0;
2909  }
2910 
2912  conn->asyncStatus = PGASYNC_IDLE;
2913 
2914  /* Flush any pending data in out buffer */
2915  if (pqFlush(conn) < 0)
2916  return 0; /* error message is setup already */
2917  return 1;
2918 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:965
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:433
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:416
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
PQExpBufferData errorMessage
Definition: libpq-int.h:569
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQfformat()

int PQfformat ( const PGresult res,
int  field_num 
)

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

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

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

3395 {
3396  if (!check_field_number(res, field_num))
3397  return 0;
3398  if (res->attDescs)
3399  return res->attDescs[field_num].format;
3400  else
3401  return 0;
3402 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3196

◆ PQflush()

int PQflush ( PGconn conn)

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

References pqFlush().

Referenced by CheckCopyStreamStop(), HandleEndOfCopyStream(), libpqrcv_endstreaming(), libpqrcv_send(), PQpipelineSync(), prepareToTerminate(), ProcessXLogDataMsg(), sendFeedback(), and test_pipelined_insert().

3686 {
3687  return pqFlush(conn);
3688 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:965

◆ PQfmod()

int PQfmod ( const PGresult res,
int  field_num 
)

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

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

Referenced by DescribeQuery(), and ECPGget_desc().

3428 {
3429  if (!check_field_number(res, field_num))
3430  return 0;
3431  if (res->attDescs)
3432  return res->attDescs[field_num].atttypmod;
3433  else
3434  return 0;
3435 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
int atttypmod
Definition: libpq-fe.h:258
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3196

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

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

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

2790 {
2791  *result_len = 0;
2792 
2793  if (!conn)
2794  return NULL;
2795 
2796  /*
2797  * Since this is the beginning of a query cycle, reset the error buffer.
2798  */
2800 
2801  if (conn->pipelineStatus != PQ_PIPELINE_OFF)
2802  {
2804  libpq_gettext("PQfn not allowed in pipeline mode\n"));
2805  return NULL;
2806  }
2807 
2808  if (conn->sock == PGINVALID_SOCKET || conn->asyncStatus != PGASYNC_IDLE ||
2809  conn->result != NULL)
2810  {
2812  libpq_gettext("connection in wrong state\n"));
2813  return NULL;
2814  }
2815 
2816  return pqFunctionCall3(conn, fnid,
2817  result_buf, result_len,
2818  result_is_int,
2819  args, nargs);
2820 }
PGresult * pqFunctionCall3(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:416
PGresult * result
Definition: libpq-int.h:499
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
pgsocket sock
Definition: libpq-int.h:443
#define PGINVALID_SOCKET
Definition: port.h:33
PQExpBufferData errorMessage
Definition: libpq-int.h:569
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQfname()

char* PQfname ( const PGresult res,
int  field_num 
)

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

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

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

3254 {
3255  if (!check_field_number(res, field_num))
3256  return NULL;
3257  if (res->attDescs)
3258  return res->attDescs[field_num].name;
3259  else
3260  return NULL;
3261 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3196
char * name
Definition: libpq-fe.h:252

◆ PQfnumber()

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

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

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

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

3276 {
3277  char *field_case;
3278  bool in_quotes;
3279  bool all_lower = true;
3280  const char *iptr;
3281  char *optr;
3282  int i;
3283 
3284  if (!res)
3285  return -1;
3286 
3287  /*
3288  * Note: it is correct to reject a zero-length input string; the proper
3289  * input to match a zero-length field name would be "".
3290  */
3291  if (field_name == NULL ||
3292  field_name[0] == '\0' ||
3293  res->attDescs == NULL)
3294  return -1;
3295 
3296  /*
3297  * Check if we can avoid the strdup() and related work because the
3298  * passed-in string wouldn't be changed before we do the check anyway.
3299  */
3300  for (iptr = field_name; *iptr; iptr++)
3301  {
3302  char c = *iptr;
3303 
3304  if (c == '"' || c != pg_tolower((unsigned char) c))
3305  {
3306  all_lower = false;
3307  break;
3308  }
3309  }
3310 
3311  if (all_lower)
3312  for (i = 0; i < res->numAttributes; i++)
3313  if (strcmp(field_name, res->attDescs[i].name) == 0)
3314  return i;
3315 
3316  /* Fall through to the normal check if that didn't work out. */
3317 
3318  /*
3319  * Note: this code will not reject partially quoted strings, eg
3320  * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
3321  * condition.
3322  */
3323  field_case = strdup(field_name);
3324  if (field_case == NULL)
3325  return -1; /* grotty */
3326 
3327  in_quotes = false;
3328  optr = field_case;
3329  for (iptr = field_case; *iptr; iptr++)
3330  {
3331  char c = *iptr;
3332 
3333  if (in_quotes)
3334  {
3335  if (c == '"')
3336  {
3337  if (iptr[1] == '"')
3338  {
3339  /* doubled quotes become a single quote */
3340  *optr++ = '"';
3341  iptr++;
3342  }
3343  else
3344  in_quotes = false;
3345  }
3346  else
3347  *optr++ = c;
3348  }
3349  else if (c == '"')
3350  in_quotes = true;
3351  else
3352  {
3353  c = pg_tolower((unsigned char) c);
3354  *optr++ = c;
3355  }
3356  }
3357  *optr = '\0';
3358 
3359  for (i = 0; i < res->numAttributes; i++)
3360  {
3361  if (strcmp(field_case, res->attDescs[i].name) == 0)
3362  {
3363  free(field_case);
3364  return i;
3365  }
3366  }
3367  free(field_case);
3368  return -1;
3369 }
unsigned char pg_tolower(unsigned char ch)
Definition: pgstrcasecmp.c:122
PGresAttDesc * attDescs
Definition: libpq-int.h:171
char * c
int numAttributes
Definition: libpq-int.h:170
#define free(a)
Definition: header.h:65
int i
char * name
Definition: libpq-fe.h:252

◆ PQfreemem()

◆ PQfreeNotify()

void PQfreeNotify ( PGnotify notify)

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

References PQfreemem().

Referenced by PQfreemem().

3733 {
3734  PQfreemem(notify);
3735 }
void PQfreemem(void *ptr)
Definition: fe-exec.c:3715

◆ PQfsize()

int PQfsize ( const PGresult res,
int  field_num 
)

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

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

Referenced by ecpg_build_compat_sqlda(), and ECPGget_desc().

3417 {
3418  if (!check_field_number(res, field_num))
3419  return 0;
3420  if (res->attDescs)
3421  return res->attDescs[field_num].typlen;
3422  else
3423  return 0;
3424 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3196

◆ PQftable()

Oid PQftable ( const PGresult res,
int  field_num 
)

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

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

3373 {
3374  if (!check_field_number(res, field_num))
3375  return InvalidOid;
3376  if (res->attDescs)
3377  return res->attDescs[field_num].tableid;
3378  else
3379  return InvalidOid;
3380 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
#define InvalidOid
Definition: postgres_ext.h:36
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3196

◆ PQftablecol()

int PQftablecol ( const PGresult res,
int  field_num 
)

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

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

3384 {
3385  if (!check_field_number(res, field_num))
3386  return 0;
3387  if (res->attDescs)
3388  return res->attDescs[field_num].columnid;
3389  else
3390  return 0;
3391 }
int columnid
Definition: libpq-fe.h:254
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3196

◆ PQftype()

Oid PQftype ( const PGresult res,
int  field_num 
)

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

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

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

3406 {
3407  if (!check_field_number(res, field_num))
3408  return InvalidOid;
3409  if (res->attDescs)
3410  return res->attDescs[field_num].typid;
3411  else
3412  return InvalidOid;
3413 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
#define InvalidOid
Definition: postgres_ext.h:36
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3196

◆ PQgetCopyData()

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

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

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

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

2619 {
2620  *buffer = NULL; /* for all failure cases */
2621  if (!conn)
2622  return -2;
2623  if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2624  conn->asyncStatus != PGASYNC_COPY_BOTH)
2625  {
2627  libpq_gettext("no COPY in progress\n"));
2628  return -2;
2629  }
2630  return pqGetCopyData3(conn, buffer, async);
2631 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
int pqGetCopyData3(PGconn *conn, char **buffer, int async)
PQExpBufferData errorMessage
Definition: libpq-int.h:569
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQgetisnull()

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

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

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

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

3587 {
3588  if (!check_tuple_field_number(res, tup_num, field_num))
3589  return 1; /* pretend it is null */
3590  if (res->tuples[tup_num][field_num].len == NULL_LEN)
3591  return 1;
3592  else
3593  return 0;
3594 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3211
#define NULL_LEN
Definition: libpq-int.h:133
PGresAttValue ** tuples
Definition: libpq-int.h:172

◆ PQgetlength()

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

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

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

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

3573 {
3574  if (!check_tuple_field_number(res, tup_num, field_num))
3575  return 0;
3576  if (res->tuples[tup_num][field_num].len != NULL_LEN)
3577  return res->tuples[tup_num][field_num].len;
3578  else
3579  return 0;
3580 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3211
#define NULL_LEN
Definition: libpq-int.h:133
PGresAttValue ** tuples
Definition: libpq-int.h:172

◆ PQgetline()

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

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

References pqGetline3().

2658 {
2659  if (!s || maxlen <= 0)
2660  return EOF;
2661  *s = '\0';
2662  /* maxlen must be at least 3 to hold the \. terminator! */
2663  if (maxlen < 3)
2664  return EOF;
2665 
2666  if (!conn)
2667  return EOF;
2668 
2669  return pqGetline3(conn, s, maxlen);
2670 }
int pqGetline3(PGconn *conn, char *s, int maxlen)

◆ PQgetlineAsync()

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

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

References pqGetlineAsync3().

Referenced by pqGetline3().

2705 {
2706  if (!conn)
2707  return -1;
2708 
2709  return pqGetlineAsync3(conn, buffer, bufsize);
2710 }
int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)

◆ PQgetResult()

PGresult* PQgetResult ( PGconn conn)

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

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

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

1928 {
1929  PGresult *res;
1930 
1931  if (!conn)
1932  return NULL;
1933 
1934  /* Parse any available data, if our state permits. */
1935  parseInput(conn);
1936 
1937  /* If not ready to return something, block until we are. */
1938  while (conn->asyncStatus == PGASYNC_BUSY)
1939  {
1940  int flushResult;
1941 
1942  /*
1943  * If data remains unsent, send it. Else we might be waiting for the
1944  * result of a command the backend hasn't even got yet.
1945  */
1946  while ((flushResult = pqFlush(conn)) > 0)
1947  {
1948  if (pqWait(false, true, conn))
1949  {
1950  flushResult = -1;
1951  break;
1952  }
1953  }
1954 
1955  /*
1956  * Wait for some more data, and load it. (Note: if the connection has
1957  * been lost, pqWait should return immediately because the socket
1958  * should be read-ready, either with the last server data or with an
1959  * EOF indication. We expect therefore that this won't result in any
1960  * undue delay in reporting a previous write failure.)
1961  */
1962  if (flushResult ||
1963  pqWait(true, false, conn) ||
1964  pqReadData(conn) < 0)
1965  {
1966  /*
1967  * conn->errorMessage has been set by pqWait or pqReadData. We
1968  * want to append it to any already-received error message.
1969  */
1970  pqSaveErrorResult(conn);
1971  conn->asyncStatus = PGASYNC_IDLE;
1972  return pqPrepareAsyncResult(conn);
1973  }
1974 
1975  /* Parse it. */
1976  parseInput(conn);
1977 
1978  /*
1979  * If we had a write error, but nothing above obtained a query result
1980  * or detected a read error, report the write error.
1981  */
1982  if (conn->write_failed && conn->asyncStatus == PGASYNC_BUSY)
1983  {
1984  pqSaveWriteError(conn);
1985  conn->asyncStatus = PGASYNC_IDLE;
1986  return pqPrepareAsyncResult(conn);
1987  }
1988  }
1989 
1990  /* Return the appropriate thing. */
1991  switch (conn->asyncStatus)
1992  {
1993  case PGASYNC_IDLE:
1994  res = NULL; /* query is complete */
1995  if (conn->pipelineStatus != PQ_PIPELINE_OFF)
1996  {
1997  /*
1998  * We're about to return the NULL that terminates the round of
1999  * results from the current query; prepare to send the results
2000  * of the next query when we're called next. Also, since this
2001  * is the start of the results of the next query, clear any
2002  * prior error message.
2003  */
2005  pqPipelineProcessQueue(conn);
2006  }
2007  break;
2008  case PGASYNC_READY:
2009 
2010  /*
2011  * For any query type other than simple query protocol, we advance
2012  * the command queue here. This is because for simple query
2013  * protocol we can get the READY state multiple times before the
2014  * command is actually complete, since the command string can
2015  * contain many queries. In simple query protocol, the queue
2016  * advance is done by fe-protocol3 when it receives ReadyForQuery.
2017  */
2018  if (conn->cmd_queue_head &&
2020  pqCommandQueueAdvance(conn);
2021  res = pqPrepareAsyncResult(conn);
2022  if (conn->pipelineStatus != PQ_PIPELINE_OFF)
2023  {
2024  /*
2025  * We're about to send the results of the current query. Set
2026  * us idle now, and ...
2027  */
2028  conn->asyncStatus = PGASYNC_IDLE;
2029 
2030  /*
2031  * ... in cases when we're sending a pipeline-sync result,
2032  * move queue processing forwards immediately, so that next
2033  * time we're called, we're prepared to return the next result
2034  * received from the server. In all other cases, leave the
2035  * queue state change for next time, so that a terminating
2036  * NULL result is sent.
2037  *
2038  * (In other words: we don't return a NULL after a pipeline
2039  * sync.)
2040  */
2041  if (res && res->resultStatus == PGRES_PIPELINE_SYNC)
2042  pqPipelineProcessQueue(conn);
2043  }
2044  else
2045  {
2046  /* Set the state back to BUSY, allowing parsing to proceed. */
2047  conn->asyncStatus = PGASYNC_BUSY;
2048  }
2049  break;
2050  case PGASYNC_READY_MORE:
2051  res = pqPrepareAsyncResult(conn);
2052  /* Set the state back to BUSY, allowing parsing to proceed. */
2053  conn->asyncStatus = PGASYNC_BUSY;
2054  break;
2055  case PGASYNC_COPY_IN:
2056  res = getCopyResult(conn, PGRES_COPY_IN);
2057  break;
2058  case PGASYNC_COPY_OUT:
2059  res = getCopyResult(conn, PGRES_COPY_OUT);
2060  break;
2061  case PGASYNC_COPY_BOTH:
2062  res = getCopyResult(conn, PGRES_COPY_BOTH);
2063  break;
2064  default:
2066  libpq_gettext("unexpected asyncStatus: %d\n"),
2067  (int) conn->asyncStatus);
2069  break;
2070  }
2071 
2072  if (res)
2073  {
2074  int i;
2075 
2076  for (i = 0; i < res->nEvents; i++)
2077  {
2078  PGEventResultCreate evt;
2079 
2080  evt.conn = conn;
2081  evt.result = res;
2082  if (!res->events[i].proc(PGEVT_RESULTCREATE, &evt,
2083  res->events[i].passThrough))
2084  {
2086  libpq_gettext("PGEventProc \"%s\" failed during PGEVT_RESULTCREATE event\n"),
2087  res->events[i].name);
2088  pqSetResultError(res, conn->errorMessage.data);
2090  break;
2091  }
2092  res->events[i].resultInitialized = true;
2093  }
2094  }
2095 
2096  return res;
2097 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:965
bool resultInitialized
Definition: libpq-int.h:164
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:433
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:416
int nEvents
Definition: libpq-int.h:188
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:790
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
PGQueryClass queryclass
Definition: libpq-int.h:321
bool write_failed
Definition: libpq-int.h:453
PGconn * conn
Definition: streamutil.c:54
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
int pqReadData(PGconn *conn)
Definition: fe-misc.c:568
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:990
static PGresult * getCopyResult(PGconn *conn, ExecStatusType copytype)
Definition: fe-exec.c:2104
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:146
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1889
void pqCommandQueueAdvance(PGconn *conn)
Definition: fe-exec.c:2926
PQExpBufferData errorMessage
Definition: libpq-int.h:569
void pqSetResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:665
PGEventProc proc
Definition: libpq-int.h:160
static void pqSaveWriteError(PGconn *conn)
Definition: fe-exec.c:763
int i
void * passThrough
Definition: libpq-int.h:162
static void pqPipelineProcessQueue(PGconn *conn)
Definition: fe-exec.c:2947
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:751
PGEvent * events
Definition: libpq-int.h:187
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
char * name
Definition: libpq-int.h:161
ExecStatusType resultStatus
Definition: libpq-int.h:177
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQgetvalue()

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

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

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

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

3562 {
3563  if (!check_tuple_field_number(res, tup_num, field_num))
3564  return NULL;
3565  return res->tuples[tup_num][field_num].value;
3566 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3211
PGresAttValue ** tuples
Definition: libpq-int.h:172
char * value
Definition: libpq-int.h:138

◆ pqInternalNotice()

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

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

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

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

826 {
827  char msgBuf[1024];
828  va_list args;
829  PGresult *res;
830 
831  if (hooks->noticeRec == NULL)
832  return; /* nobody home to receive notice? */
833 
834  /* Format the message */
835  va_start(args, fmt);
836  vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
837  va_end(args);
838  msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
839 
840  /* Make a PGresult to pass to the notice receiver */
842  if (!res)
843  return;
844  res->noticeHooks = *hooks;
845 
846  /*
847  * Set up fields of notice.
848  */
852  /* XXX should provide a SQLSTATE too? */
853 
854  /*
855  * Result text is always just the primary message + newline. If we can't
856  * allocate it, don't bother invoking the receiver.
857  */
858  res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, false);
859  if (res->errMsg)
860  {
861  sprintf(res->errMsg, "%s\n", msgBuf);
862 
863  /*
864  * Pass to receiver, then free it.
865  */
866  res->noticeHooks.noticeRec(res->noticeHooks.noticeRecArg, res);
867  }
868  PQclear(res);
869 }
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:58
#define sprintf
Definition: port.h:218
#define vsnprintf
Definition: port.h:215
PQnoticeReceiver noticeRec
Definition: libpq-int.h:152
#define PG_DIAG_SEVERITY
Definition: postgres_ext.h:55
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:146
void pqSaveMessageField(PGresult *res, char code, const char *value)
Definition: fe-exec.c:947
#define PG_DIAG_SEVERITY_NONLOCALIZED
Definition: postgres_ext.h:56
void PQclear(PGresult *res)
Definition: fe-exec.c:680
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:539
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQisBusy()

int PQisBusy ( PGconn conn)

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

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

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

1901 {
1902  if (!conn)
1903  return false;
1904 
1905  /* Parse any available data, if our state permits. */
1906  parseInput(conn);
1907 
1908  /*
1909  * PQgetResult will return immediately in all states except BUSY, or if we
1910  * had a write failure.
1911  */
1912  return conn->asyncStatus == PGASYNC_BUSY || conn->write_failed;
1913 }
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
bool write_failed
Definition: libpq-int.h:453
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1889

◆ PQisnonblocking()

int PQisnonblocking ( const PGconn conn)

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

References pqIsnonblocking.

Referenced by test_disallowed_in_pipeline(), and test_simple_pipeline().

3667 {
3668  return pqIsnonblocking(conn);
3669 }
#define pqIsnonblocking(conn)
Definition: libpq-int.h:835

◆ PQisthreadsafe()

int PQisthreadsafe ( void  )

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

3674 {
3675 #ifdef ENABLE_THREAD_SAFETY
3676  return true;
3677 #else
3678  return false;
3679 #endif
3680 }

◆ PQmakeEmptyPGresult()

PGresult* PQmakeEmptyPGresult ( PGconn conn,
ExecStatusType  status 
)

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

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

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

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

◆ PQnfields()

◆ PQnotifies()

PGnotify* PQnotifies ( PGconn conn)

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

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

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

2467 {
2468  PGnotify *event;
2469 
2470  if (!conn)
2471  return NULL;
2472 
2473  /* Parse any available data to see if we can extract NOTIFY messages. */
2474  parseInput(conn);
2475 
2476  event = conn->notifyHead;
2477  if (event)
2478  {
2479  conn->notifyHead = event->next;
2480  if (!conn->notifyHead)
2481  conn->notifyTail = NULL;
2482  event->next = NULL; /* don't let app see the internal state */
2483  }
2484  return event;
2485 }
PGnotify * notifyHead
Definition: libpq-int.h:420
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1889
struct pgNotify * next
Definition: libpq-fe.h:182
PGnotify * notifyTail
Definition: libpq-int.h:421

◆ PQnparams()

int PQnparams ( const PGresult res)

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

References pg_result::numParameters.

3601 {
3602  if (!res)
3603  return 0;
3604  return res->numParameters;
3605 }
int numParameters
Definition: libpq-int.h:175

◆ PQntuples()

int PQntuples ( const PGresult res)

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

References pg_result::ntups.

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

3168 {
3169  if (!res)
3170  return 0;
3171  return res->ntups;
3172 }
int ntups
Definition: libpq-int.h:169

◆ PQoidStatus()

char* PQoidStatus ( const PGresult res)

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

References buf, and pg_result::cmdStatus.

3452 {
3453  /*
3454  * This must be enough to hold the result. Don't laugh, this is better
3455  * than what this function used to do.
3456  */
3457  static char buf[24];
3458 
3459  size_t len;
3460 
3461  if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
3462  return "";
3463 
3464  len = strspn(res->cmdStatus + 7, "0123456789");
3465  if (len > sizeof(buf) - 1)
3466  len = sizeof(buf) - 1;
3467  memcpy(buf, res->cmdStatus + 7, len);
3468  buf[len] = '\0';
3469 
3470  return buf;
3471 }
static char * buf
Definition: pg_test_fsync.c:68
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178

◆ PQoidValue()

Oid PQoidValue ( const PGresult res)

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

References pg_result::cmdStatus, and InvalidOid.

Referenced by ecpg_process_output(), and PrintQueryStatus().

3480 {
3481  char *endptr = NULL;
3482  unsigned long result;
3483 
3484  if (!res ||
3485  strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
3486  res->cmdStatus[7] < '0' ||
3487  res->cmdStatus[7] > '9')
3488  return InvalidOid;
3489 
3490  result = strtoul(res->cmdStatus + 7, &endptr, 10);
3491 
3492  if (!endptr || (*endptr != ' ' && *endptr != '\0'))
3493  return InvalidOid;
3494  else
3495  return (Oid) result;
3496 }
unsigned int Oid
Definition: postgres_ext.h:31
#define InvalidOid
Definition: postgres_ext.h:36
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178

◆ PQparamtype()

Oid PQparamtype ( const PGresult res,
int  param_num 
)

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

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

3612 {
3613  if (!check_param_number(res, param_num))
3614  return InvalidOid;
3615  if (res->paramDescs)
3616  return res->paramDescs[param_num].typid;
3617  else
3618  return InvalidOid;
3619 }
static int check_param_number(const PGresult *res, int param_num)
Definition: fe-exec.c:3234
#define InvalidOid
Definition: postgres_ext.h:36
PGresParamDesc * paramDescs
Definition: libpq-int.h:176

◆ pqPipelineFlush()

static int pqPipelineFlush ( PGconn conn)
static

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

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

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

3700 {
3701  if ((conn->pipelineStatus != PQ_PIPELINE_ON) ||
3702  (conn->outCount >= OUTBUFFER_THRESHOLD))
3703  return pqFlush(conn);
3704  return 0;
3705 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:965
int outCount
Definition: libpq-int.h:487
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:416
#define OUTBUFFER_THRESHOLD
Definition: libpq-int.h:840

◆ pqPipelineProcessQueue()

void pqPipelineProcessQueue ( PGconn conn)
static

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

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

Referenced by PQgetResult(), and PQpipelineSync().

2948 {
2949  switch (conn->asyncStatus)
2950  {
2951  case PGASYNC_COPY_IN:
2952  case PGASYNC_COPY_OUT:
2953  case PGASYNC_COPY_BOTH:
2954  case PGASYNC_READY:
2955  case PGASYNC_READY_MORE:
2956  case PGASYNC_BUSY:
2957  /* client still has to process current query or results */
2958  return;
2959  case PGASYNC_IDLE:
2960  /* next query please */
2961  break;
2962  }
2963 
2964  /* Nothing to do if not in pipeline mode, or queue is empty */
2965  if (conn->pipelineStatus == PQ_PIPELINE_OFF ||
2966  conn->cmd_queue_head == NULL)
2967  return;
2968 
2969  /* Initialize async result-accumulation state */
2970  pqClearAsyncResult(conn);
2971 
2972  /*
2973  * Reset single-row processing mode. (Client has to set it up for each
2974  * query, if desired.)
2975  */
2976  conn->singleRowMode = false;
2977 
2978  if (conn->pipelineStatus == PQ_PIPELINE_ABORTED &&
2980  {
2981  /*
2982  * In an aborted pipeline we don't get anything from the server for
2983  * each result; we're just discarding commands from the queue until we
2984  * get to the next sync from the server.
2985  *
2986  * The PGRES_PIPELINE_ABORTED results tell the client that its queries
2987  * got aborted.
2988  */
2990  if (!conn->result)
2991  {
2993  libpq_gettext("out of memory\n"));
2994  pqSaveErrorResult(conn);
2995  return;
2996  }
2997  conn->asyncStatus = PGASYNC_READY;
2998  }
2999  else
3000  {
3001  /* allow parsing to continue */
3002  conn->asyncStatus = PGASYNC_BUSY;
3003  }
3004 }
bool singleRowMode
Definition: libpq-int.h:417
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:433
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:416
PGresult * result
Definition: libpq-int.h:499
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
PGQueryClass queryclass
Definition: libpq-int.h:321
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:146
PQExpBufferData errorMessage
Definition: libpq-int.h:569
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:735
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:751
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQpipelineSync()

int PQpipelineSync ( PGconn conn)

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

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

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

3028 {
3029  PGcmdQueueEntry *entry;
3030 
3031  if (!conn)
3032  return 0;
3033 
3034  if (conn->pipelineStatus == PQ_PIPELINE_OFF)
3035  {
3037  libpq_gettext("cannot send pipeline when not in pipeline mode\n"));
3038  return 0;
3039  }
3040 
3041  switch (conn->asyncStatus)
3042  {
3043  case PGASYNC_COPY_IN:
3044  case PGASYNC_COPY_OUT:
3045  case PGASYNC_COPY_BOTH:
3046  /* should be unreachable */
3048  "internal error: cannot send pipeline while in COPY\n");
3049  return 0;
3050  case PGASYNC_READY:
3051  case PGASYNC_READY_MORE:
3052  case PGASYNC_BUSY:
3053  case PGASYNC_IDLE:
3054  /* OK to send sync */
3055  break;
3056  }
3057 
3058  entry = pqAllocCmdQueueEntry(conn);
3059  if (entry == NULL)
3060  return 0; /* error msg already set */
3061 
3062  entry->queryclass = PGQUERY_SYNC;
3063  entry->query = NULL;
3064 
3065  /* construct the Sync message */
3066  if (pqPutMsgStart('S', conn) < 0 ||
3067  pqPutMsgEnd(conn) < 0)
3068  goto sendFailed;
3069 
3070  pqAppendCmdQueueEntry(conn, entry);
3071 
3072  /*
3073  * Give the data a push. In nonblock mode, don't complain if we're unable
3074  * to send it all; PQgetResult() will do any additional flushing needed.
3075  */
3076  if (PQflush(conn) < 0)
3077  goto sendFailed;
3078 
3079  /*
3080  * Call pqPipelineProcessQueue so the user can call start calling
3081  * PQgetResult.
3082  */
3083  pqPipelineProcessQueue(conn);
3084 
3085  return 1;
3086 
3087 sendFailed:
3088  pqRecycleCmdQueueEntry(conn, entry);
3089  /* error message should be set up already */
3090  return 0;
3091 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:416
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1249
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
PGQueryClass queryclass
Definition: libpq-int.h:321
int PQflush(PGconn *conn)
Definition: fe-exec.c:3685
PQExpBufferData errorMessage
Definition: libpq-int.h:569
static void pqAppendCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1232
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
static void pqPipelineProcessQueue(PGconn *conn)
Definition: fe-exec.c:2947
static PGcmdQueueEntry * pqAllocCmdQueueEntry(PGconn *conn)
Definition: fe-exec.c:1199
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQprepare()

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

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

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

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

2189 {
2190  if (!PQexecStart(conn))
2191  return NULL;
2192  if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
2193  return NULL;
2194  return PQexecFinish(conn);
2195 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2289
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2224
int PQsendPrepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:1432

◆ pqPrepareAsyncResult()

PGresult* pqPrepareAsyncResult ( PGconn conn)

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

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

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

791 {
792  PGresult *res;
793 
794  /*
795  * conn->result is the PGresult to return. If it is NULL (which probably
796  * shouldn't happen) we assume there is an appropriate error message in
797  * conn->errorMessage.
798  */
799  res = conn->result;
800  if (!res)
802 
803  /*
804  * Replace conn->result with next_result, if any. In the normal case
805  * there isn't a next result and we're just dropping ownership of the
806  * current result. In single-row mode this restores the situation to what
807  * it was before we created the current single-row result.
808  */
809  conn->result = conn->next_result;
810  conn->next_result = NULL;
811 
812  return res;
813 }
PGresult * result
Definition: libpq-int.h:499
PGresult * next_result
Definition: libpq-int.h:500
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:146

◆ PQputCopyData()

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

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

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

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

2495 {
2496  if (!conn)
2497  return -1;
2498  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2499  conn->asyncStatus != PGASYNC_COPY_BOTH)
2500  {
2502  libpq_gettext("no COPY in progress\n"));
2503  return -1;
2504  }
2505 
2506  /*
2507  * Process any NOTICE or NOTIFY messages that might be pending in the
2508  * input buffer. Since the server might generate many notices during the
2509  * COPY, we want to clean those out reasonably promptly to prevent
2510  * indefinite expansion of the input buffer. (Note: the actual read of
2511  * input data into the input buffer happens down inside pqSendSome, but
2512  * it's not authorized to get rid of the data again.)
2513  */
2514  parseInput(conn);
2515 
2516  if (nbytes > 0)
2517  {
2518  /*
2519  * Try to flush any previously sent data in preference to growing the
2520  * output buffer. If we can't enlarge the buffer enough to hold the
2521  * data, return 0 in the nonblock case, else hard error. (For
2522  * simplicity, always assume 5 bytes of overhead.)
2523  */
2524  if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2525  {
2526  if (pqFlush(conn) < 0)
2527  return -1;
2528  if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2529  conn))
2530  return pqIsnonblocking(conn) ? 0 : -1;
2531  }
2532  /* Send the data (too simple to delegate to fe-protocol files) */
2533  if (pqPutMsgStart('d', conn) < 0 ||
2534  pqPutnchar(buffer, nbytes, conn) < 0 ||
2535  pqPutMsgEnd(conn) < 0)
2536  return -1;
2537  }
2538  return 1;
2539 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:965
int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:290
#define pqIsnonblocking(conn)
Definition: libpq-int.h:835
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
int outCount
Definition: libpq-int.h:487
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1889
PQExpBufferData errorMessage
Definition: libpq-int.h:569
int outBufSize
Definition: libpq-int.h:486
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:205
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQputCopyEnd()

int PQputCopyEnd ( PGconn conn,
const char *  errormsg 
)

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

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

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

2551 {
2552  if (!conn)
2553  return -1;
2554  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2555  conn->asyncStatus != PGASYNC_COPY_BOTH)
2556  {
2558  libpq_gettext("no COPY in progress\n"));
2559  return -1;
2560  }
2561 
2562  /*
2563  * Send the COPY END indicator. This is simple enough that we don't
2564  * bother delegating it to the fe-protocol files.
2565  */
2566  if (errormsg)
2567  {
2568  /* Send COPY FAIL */
2569  if (pqPutMsgStart('f', conn) < 0 ||
2570  pqPuts(errormsg, conn) < 0 ||
2571  pqPutMsgEnd(conn) < 0)
2572  return -1;
2573  }
2574  else
2575  {
2576  /* Send COPY DONE */
2577  if (pqPutMsgStart('c', conn) < 0 ||
2578  pqPutMsgEnd(conn) < 0)
2579  return -1;
2580  }
2581 
2582  /*
2583  * If we sent the COPY command in extended-query mode, we must issue a
2584  * Sync as well.
2585  */
2586  if (conn->cmd_queue_head &&
2588  {
2589  if (pqPutMsgStart('S', conn) < 0 ||
2590  pqPutMsgEnd(conn) < 0)
2591  return -1;
2592  }
2593 
2594  /* Return to active duty */
2595  if (conn->asyncStatus == PGASYNC_COPY_BOTH)
2596  conn->asyncStatus = PGASYNC_COPY_OUT;
2597  else
2598  conn->asyncStatus = PGASYNC_BUSY;
2599 
2600  /* Try to flush data */
2601  if (pqFlush(conn) < 0)
2602  return -1;
2603 
2604  return 1;
2605 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:965
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:433
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
PGQueryClass queryclass
Definition: libpq-int.h:321
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:155
PQExpBufferData errorMessage
Definition: libpq-int.h:569
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQputline()

int PQputline ( PGconn conn,
const char *  s 
)

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

References PQputnbytes().

Referenced by initGenerateDataClientSide().

2722 {
2723  return PQputnbytes(conn, s, strlen(s));
2724 }
int PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2731

◆ PQputnbytes()

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

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

References PQputCopyData().

Referenced by PQputline().

2732 {
2733  if (PQputCopyData(conn, buffer, nbytes) > 0)
2734  return 0;
2735  else
2736  return EOF;
2737 }
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2494

◆ pqRecycleCmdQueueEntry()

static void pqRecycleCmdQueueEntry ( PGconn conn,
PGcmdQueueEntry entry 
)
static

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

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

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

1250 {
1251  if (entry == NULL)
1252  return;
1253 
1254  /* recyclable entries should not have a follow-on command */
1255  Assert(entry->next == NULL);
1256 
1257  if (entry->query)
1258  {
1259  free(entry->query);
1260  entry->query = NULL;
1261  }
1262 
1263  entry->next = conn->cmd_queue_recycle;
1264  conn->cmd_queue_recycle = entry;
1265 }
struct PGcmdQueueEntry * next
Definition: libpq-int.h:323
#define free(a)
Definition: header.h:65
#define Assert(condition)
Definition: c.h:804
PGcmdQueueEntry * cmd_queue_recycle
Definition: libpq-int.h:440

◆ PQresStatus()

char* PQresStatus ( ExecStatusType  status)

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

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

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

3106 {
3107  if ((unsigned int) status >= lengthof(pgresStatus))
3108  return libpq_gettext("invalid ExecStatusType code");
3109  return pgresStatus[status];
3110 }
#define lengthof(array)
Definition: c.h:734
char *const pgresStatus[]
Definition: fe-exec.c:32
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQresultAlloc()

void* PQresultAlloc ( PGresult res,
size_t  nBytes 
)

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

References pqResultAlloc().

Referenced by PQsetResultAttrs().

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

◆ pqResultAlloc()

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

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

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

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

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

◆ PQresultErrorField()

char* PQresultErrorField ( const PGresult res,
int  fieldcode 
)

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

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

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

3153 {
3154  PGMessageField *pfield;
3155 
3156  if (!res)
3157  return NULL;
3158  for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
3159  {
3160  if (pfield->code == fieldcode)
3161  return pfield->contents;
3162  }
3163  return NULL;
3164 }
PGMessageField * errFields
Definition: libpq-int.h:197
struct pgMessageField * next
Definition: libpq-int.h:144
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:146

◆ PQresultErrorMessage()

char* PQresultErrorMessage ( const PGresult res)

◆ PQresultMemorySize()

size_t PQresultMemorySize ( const PGresult res)

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

References pg_result::memorySize.

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

◆ PQresultStatus()

ExecStatusType PQresultStatus ( const PGresult res)

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

References PGRES_FATAL_ERROR, and pg_result::resultStatus.

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

3098 {
3099  if (!res)
3100  return PGRES_FATAL_ERROR;
3101  return res->resultStatus;
3102 }
ExecStatusType resultStatus
Definition: libpq-int.h:177

◆ pqResultStrdup()

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

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

References pqResultAlloc().

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

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

◆ PQresultVerboseErrorMessage()

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

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

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

Referenced by exec_command_errverbose().

3124 {
3125  PQExpBufferData workBuf;
3126 
3127  /*
3128  * Because the caller is expected to free the result string, we must
3129  * strdup any constant result. We use plain strdup and document that
3130  * callers should expect NULL if out-of-memory.
3131  */
3132  if (!res ||
3133  (res->resultStatus != PGRES_FATAL_ERROR &&
3135  return strdup(libpq_gettext("PGresult is not an error result\n"));
3136 
3137  initPQExpBuffer(&workBuf);
3138 
3139  pqBuildErrorMessage3(&workBuf, res, verbosity, show_context);
3140 
3141  /* If insufficient memory to format the message, fail cleanly */
3142  if (PQExpBufferDataBroken(workBuf))
3143  {
3144  termPQExpBuffer(&workBuf);
3145  return strdup(libpq_gettext("out of memory\n"));
3146  }
3147 
3148  return workBuf.data;
3149 }
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
ExecStatusType resultStatus
Definition: libpq-int.h:177
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ pqRowProcessor()

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

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

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

Referenced by getAnotherTuple().

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

◆ pqSaveErrorResult()

void pqSaveErrorResult ( PGconn conn)

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

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

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

752 {
753  pqClearAsyncResult(conn);
755 }
PGresult * result
Definition: libpq-int.h:499
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:146
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:735

◆ pqSaveMessageField()

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

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

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

Referenced by pqGetErrorNotice3(), and pqInternalNotice().

948 {
949  PGMessageField *pfield;
950 
951  pfield = (PGMessageField *)
952  pqResultAlloc(res,
953  offsetof(PGMessageField, contents) +
954  strlen(value) + 1,
955  true);
956  if (!pfield)
957  return; /* out of memory? */
958  pfield->code = code;
959  strcpy(pfield->contents, value);
960  pfield->next = res->errFields;
961  res->errFields = pfield;
962 }
PGMessageField * errFields
Definition: libpq-int.h:197
static struct @142 value
struct pgMessageField * next
Definition: libpq-int.h:144
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:539
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:146
#define offsetof(type, field)
Definition: c.h:727

◆ pqSaveParameterStatus()

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

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

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

Referenced by getParameterStatus().

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

◆ pqSaveWriteError()

static void pqSaveWriteError ( PGconn conn)
static

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

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

Referenced by PQgetResult().

764 {
765  /*
766  * If write_err_msg is null because of previous strdup failure, do what we
767  * can. (It's likely our machinations here will get OOM failures as well,
768  * but might as well try.)
769  */
770  if (conn->write_err_msg)
771  {
773  /* Avoid possibly appending the same message twice */
774  conn->write_err_msg[0] = '\0';
775  }
776  else
778  libpq_gettext("write to server failed\n"));
779 
780  pqSaveErrorResult(conn);
781 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
char * write_err_msg
Definition: libpq-int.h:454
PQExpBufferData errorMessage
Definition: libpq-int.h:569
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:751
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQsendDescribe()

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

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

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

2400 {
2401  PGcmdQueueEntry *entry = NULL;
2402 
2403  /* Treat null desc_target as empty string */
2404  if (!desc_target)
2405  desc_target = "";
2406 
2407  if (!PQsendQueryStart(conn, true))
2408  return 0;
2409 
2410  entry = pqAllocCmdQueueEntry(conn);
2411  if (entry == NULL)
2412  return 0; /* error msg already set */
2413 
2414  /* construct the Describe message */
2415  if (pqPutMsgStart('D', conn) < 0 ||
2416  pqPutc(desc_type, conn) < 0 ||
2417  pqPuts(desc_target, conn) < 0 ||
2418  pqPutMsgEnd(conn) < 0)
2419  goto sendFailed;
2420 
2421  /* construct the Sync message */
2422  if (conn->pipelineStatus == PQ_PIPELINE_OFF)
2423  {
2424  if (pqPutMsgStart('S', conn) < 0 ||
2425  pqPutMsgEnd(conn) < 0)
2426  goto sendFailed;
2427  }
2428 
2429  /* remember we are doing a Describe */
2430  entry->queryclass = PGQUERY_DESCRIBE;
2431 
2432  /*
2433  * Give the data a push (in pipeline mode, only if we're past the size
2434  * threshold). In nonblock mode, don't complain if we're unable to send
2435  * it all; PQgetResult() will do any additional flushing needed.
2436  */
2437  if (pqPipelineFlush(conn) < 0)
2438  goto sendFailed;
2439 
2440  /* OK, it's launched! */
2441  pqAppendCmdQueueEntry(conn, entry);
2442  if (conn->pipelineStatus == PQ_PIPELINE_OFF)
2443  conn->asyncStatus = PGASYNC_BUSY;
2444  return 1;
2445 
2446 sendFailed:
2447  pqRecycleCmdQueueEntry(conn, entry);
2448  /* error message should be set up already */
2449  return 0;
2450 }
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:416
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1249
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
PGQueryClass queryclass
Definition: libpq-int.h:321
static int pqPipelineFlush(PGconn *conn)
Definition: fe-exec.c:3699
static bool PQsendQueryStart(PGconn *conn, bool newQuery)
Definition: fe-exec.c:1574
int pqPutc(char c, PGconn *conn)
Definition: fe-misc.c:95
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:155
static void pqAppendCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1232
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
static PGcmdQueueEntry * pqAllocCmdQueueEntry(PGconn *conn)
Definition: fe-exec.c:1199

◆ PQsendDescribePortal()

int PQsendDescribePortal ( PGconn conn,
const char *  portal 
)

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

References PQsendDescribe().

Referenced by test_prepared().

2385 {
2386  return PQsendDescribe(conn, 'P', portal);
2387 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2399

◆ PQsendDescribePrepared()

int PQsendDescribePrepared ( PGconn conn,
const char *  stmt 
)

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

References PQsendDescribe().

Referenced by test_prepared().

2372 {
2373  return PQsendDescribe(conn, 'S', stmt);
2374 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2399

◆ PQsendPrepare()

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

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

References appendPQExpBufferStr(), pg_conn::asyncStatus, pg_conn::errorMessage, i, libpq_gettext, PGASYNC_BUSY, PGQUERY_PREPARE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, 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().

1435 {
1436  PGcmdQueueEntry *entry = NULL;
1437 
1438  if (!PQsendQueryStart(conn, true))
1439  return 0;
1440 
1441  /* check the arguments */
1442  if (!stmtName)
1443  {
1445  libpq_gettext("statement name is a null pointer\n"));
1446  return 0;
1447  }
1448  if (!query)
1449  {
1451  libpq_gettext("command string is a null pointer\n"));
1452  return 0;
1453  }
1454  if (nParams < 0 || nParams > 65535)
1455  {
1457  libpq_gettext("number of parameters must be between 0 and 65535\n"));
1458  return 0;
1459  }
1460 
1461  entry = pqAllocCmdQueueEntry(conn);
1462  if (entry == NULL)
1463  return 0; /* error msg already set */
1464 
1465  /* construct the Parse message */
1466  if (pqPutMsgStart('P', conn) < 0 ||
1467  pqPuts(stmtName, conn) < 0 ||
1468  pqPuts(query, conn) < 0)
1469  goto sendFailed;
1470 
1471  if (nParams > 0 && paramTypes)
1472  {
1473  int i;
1474 
1475  if (pqPutInt(nParams, 2, conn) < 0)
1476  goto sendFailed;
1477  for (i = 0; i < nParams; i++)
1478  {
1479  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1480  goto sendFailed;
1481  }
1482  }
1483  else
1484  {
1485  if (pqPutInt(0, 2, conn) < 0)
1486  goto sendFailed;
1487  }
1488  if (pqPutMsgEnd(conn) < 0)
1489  goto sendFailed;
1490 
1491  /* Add a Sync, unless in pipeline mode. */
1492  if (conn->pipelineStatus == PQ_PIPELINE_OFF)
1493  {
1494  if (pqPutMsgStart('S', conn) < 0 ||
1495  pqPutMsgEnd(conn) < 0)
1496  goto sendFailed;
1497  }
1498 
1499  /* remember we are doing just a Parse */
1500  entry->queryclass = PGQUERY_PREPARE;
1501 
1502  /* and remember the query text too, if possible */
1503  /* if insufficient memory, query just winds up NULL */
1504  entry->query = strdup(query);
1505 
1506  pqAppendCmdQueueEntry(conn, entry);
1507 
1508  if (conn->pipelineStatus == PQ_PIPELINE_OFF)
1509  conn->asyncStatus = PGASYNC_BUSY;
1510 
1511  /*
1512  * Give the data a push (in pipeline mode, only if we're past the size
1513  * threshold). In nonblock mode, don't complain if we're unable to send
1514  * it all; PQgetResult() will do any additional flushing needed.
1515  */
1516  if (pqPipelineFlush(conn) < 0)
1517  goto sendFailed;
1518 
1519  return 1;
1520 
1521 sendFailed:
1522  pqRecycleCmdQueueEntry(conn, entry);
1523  /* error message should be set up already */
1524  return 0;
1525 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:416
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1249
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:256
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
PGQueryClass queryclass
Definition: libpq-int.h:321
static int pqPipelineFlush(PGconn *conn)
Definition: fe-exec.c:3699
static bool PQsendQueryStart(PGconn *conn, bool newQuery)
Definition: fe-exec.c:1574
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:155
PQExpBufferData errorMessage
Definition: libpq-int.h:569
static void pqAppendCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1232
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
int i
static PGcmdQueueEntry * pqAllocCmdQueueEntry(PGconn *conn)
Definition: fe-exec.c:1199
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQsendQuery()

int PQsendQuery ( PGconn conn,
const char *  query 
)

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

References PQsendQueryInternal().

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

1280 {
1281  return PQsendQueryInternal(conn, query, true);
1282 }
static int PQsendQueryInternal(PGconn *conn, const char *query, bool newQuery)
Definition: fe-exec.c:1291

◆ PQsendQueryContinue()

int PQsendQueryContinue ( PGconn conn,
const char *  query 
)

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

References PQsendQueryInternal().

Referenced by PQconnectPoll().

1286 {
1287  return PQsendQueryInternal(conn, query, false);
1288 }
static int PQsendQueryInternal(PGconn *conn, const char *query, bool newQuery)
Definition: fe-exec.c:1291

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

References appendPQExpBufferStr(), pg_conn::asyncStatus, pg_conn::errorMessage, i, libpq_gettext, PGASYNC_BUSY, 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().

1664 {
1665  int i;
1666  PGcmdQueueEntry *entry;
1667 
1668  entry = pqAllocCmdQueueEntry(conn);
1669  if (entry == NULL)
1670  return 0; /* error msg already set */
1671 
1672  /*
1673  * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync
1674  * (if not in pipeline mode), using specified statement name and the
1675  * unnamed portal.
1676  */
1677 
1678  if (command)
1679  {
1680  /* construct the Parse message */
1681  if (pqPutMsgStart('P', conn) < 0 ||
1682  pqPuts(stmtName, conn) < 0 ||
1683  pqPuts(command, conn) < 0)
1684  goto sendFailed;
1685  if (nParams > 0 && paramTypes)
1686  {
1687  if (pqPutInt(nParams, 2, conn) < 0)
1688  goto sendFailed;
1689  for (i = 0; i < nParams; i++)
1690  {
1691  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1692  goto sendFailed;
1693  }
1694  }
1695  else
1696  {
1697  if (pqPutInt(0, 2, conn) < 0)
1698  goto sendFailed;
1699  }
1700  if (pqPutMsgEnd(conn) < 0)
1701  goto sendFailed;
1702  }
1703 
1704  /* Construct the Bind message */
1705  if (pqPutMsgStart('B', conn) < 0 ||
1706  pqPuts("", conn) < 0 ||
1707  pqPuts(stmtName, conn) < 0)
1708  goto sendFailed;
1709 
1710  /* Send parameter formats */
1711  if (nParams > 0 && paramFormats)
1712  {
1713  if (pqPutInt(nParams, 2, conn) < 0)
1714  goto sendFailed;
1715  for (i = 0; i < nParams; i++)
1716  {
1717  if (pqPutInt(paramFormats[i], 2, conn) < 0)
1718  goto sendFailed;
1719  }
1720  }
1721  else
1722  {
1723  if (pqPutInt(0, 2, conn) < 0)
1724  goto sendFailed;
1725  }
1726 
1727  if (pqPutInt(nParams, 2, conn) < 0)
1728  goto sendFailed;
1729 
1730  /* Send parameters */
1731  for (i = 0; i < nParams; i++)
1732  {
1733  if (paramValues && paramValues[i])
1734  {
1735  int nbytes;
1736 
1737  if (paramFormats && paramFormats[i] != 0)
1738  {
1739  /* binary parameter */
1740  if (paramLengths)
1741  nbytes = paramLengths[i];
1742  else
1743  {
1745  libpq_gettext("length must be given for binary parameter\n"));
1746  goto sendFailed;
1747  }
1748  }
1749  else
1750  {
1751  /* text parameter, do not use paramLengths */
1752  nbytes = strlen(paramValues[i]);
1753  }
1754  if (pqPutInt(nbytes, 4, conn) < 0 ||
1755  pqPutnchar(paramValues[i], nbytes, conn) < 0)
1756  goto sendFailed;
1757  }
1758  else
1759  {
1760  /* take the param as NULL */
1761  if (pqPutInt(-1, 4, conn) < 0)
1762  goto sendFailed;
1763  }
1764  }
1765  if (pqPutInt(1, 2, conn) < 0 ||
1766  pqPutInt(resultFormat, 2, conn))
1767  goto sendFailed;
1768  if (pqPutMsgEnd(conn) < 0)
1769  goto sendFailed;
1770 
1771  /* construct the Describe Portal message */
1772  if (pqPutMsgStart('D', conn) < 0 ||
1773  pqPutc('P', conn) < 0 ||
1774  pqPuts("", conn) < 0 ||
1775  pqPutMsgEnd(conn) < 0)
1776  goto sendFailed;
1777 
1778  /* construct the Execute message */
1779  if (pqPutMsgStart('E', conn) < 0 ||
1780  pqPuts("", conn) < 0 ||
1781  pqPutInt(0, 4, conn) < 0 ||
1782  pqPutMsgEnd(conn) < 0)
1783  goto sendFailed;
1784 
1785  /* construct the Sync message if not in pipeline mode */
1786  if (conn->pipelineStatus == PQ_PIPELINE_OFF)
1787  {
1788  if (pqPutMsgStart('S', conn) < 0 ||
1789  pqPutMsgEnd(conn) < 0)
1790  goto sendFailed;
1791  }
1792 
1793  /* remember we are using extended query protocol */
1794  entry->queryclass = PGQUERY_EXTENDED;
1795 
1796  /* and remember the query text too, if possible */
1797  /* if insufficient memory, query just winds up NULL */
1798  if (command)
1799  entry->query = strdup(command);
1800 
1801  /*
1802  * Give the data a push (in pipeline mode, only if we're past the size
1803  * threshold). In nonblock mode, don't complain if we're unable to send
1804  * it all; PQgetResult() will do any additional flushing needed.
1805  */
1806  if (pqPipelineFlush(conn) < 0)
1807  goto sendFailed;
1808 
1809  /* OK, it's launched! */
1810  pqAppendCmdQueueEntry(conn, entry);
1811  if (conn->pipelineStatus == PQ_PIPELINE_OFF)
1812  conn->asyncStatus = PGASYNC_BUSY;
1813  return 1;
1814 
1815 sendFailed:
1816  pqRecycleCmdQueueEntry(conn, entry);
1817  /* error message should be set up already */
1818  return 0;
1819 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:416
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1249
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:256
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:410
PGQueryClass queryclass
Definition: libpq-int.h:321
static int pqPipelineFlush(PGconn *conn)
Definition: fe-exec.c:3699
int pqPutc(char c, PGconn *conn)
Definition: fe-misc.c:95
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:155
PQExpBufferData errorMessage
Definition: libpq-int.h:569
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:205
static void pqAppendCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1232
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
int i
static PGcmdQueueEntry * pqAllocCmdQueueEntry(PGconn *conn)
Definition: fe-exec.c:1199
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ PQsendQueryInternal()

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