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 bool PQsendQueryStart (PGconn *conn)
 
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)
 
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 pqCatenateResultError (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)
 
int PQsendQuery (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)
 
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 3734 of file fe-exec.c.

Referenced by PQunescapeBytea().

◆ ISOCTDIGIT

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

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

Referenced by PQunescapeBytea().

◆ OCTVAL

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

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

Referenced by PQunescapeBytea().

◆ PGRESULT_ALIGN_BOUNDARY

#define PGRESULT_ALIGN_BOUNDARY   MAXIMUM_ALIGNOF /* from configure */

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

Referenced by pqResultAlloc().

◆ PGRESULT_DATA_BLOCKSIZE

#define PGRESULT_DATA_BLOCKSIZE   2048

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

Referenced by pqResultAlloc().

◆ PGRESULT_SEP_ALLOC_THRESHOLD

#define PGRESULT_SEP_ALLOC_THRESHOLD   (PGRESULT_DATA_BLOCKSIZE / 2)

Definition at line 131 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 2798 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().

2799 {
2800  if (!res)
2801  return false; /* no way to display error message... */
2802  if (field_num < 0 || field_num >= res->numAttributes)
2803  {
2805  "column number %d is out of range 0..%d",
2806  field_num, res->numAttributes - 1);
2807  return false;
2808  }
2809  return true;
2810 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:871
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 2836 of file fe-exec.c.

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

Referenced by PQparamtype().

2837 {
2838  if (!res)
2839  return false; /* no way to display error message... */
2840  if (param_num < 0 || param_num >= res->numParameters)
2841  {
2843  "parameter number %d is out of range 0..%d",
2844  param_num, res->numParameters - 1);
2845  return false;
2846  }
2847 
2848  return true;
2849 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:871
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 2813 of file fe-exec.c.

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

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

2815 {
2816  if (!res)
2817  return false; /* no way to display error message... */
2818  if (tup_num < 0 || tup_num >= res->ntups)
2819  {
2821  "row number %d is out of range 0..%d",
2822  tup_num, res->ntups - 1);
2823  return false;
2824  }
2825  if (field_num < 0 || field_num >= res->numAttributes)
2826  {
2828  "column number %d is out of range 0..%d",
2829  field_num, res->numAttributes - 1);
2830  return false;
2831  }
2832  return true;
2833 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:871
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 387 of file fe-exec.c.

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

Referenced by PQcopyResult(), and PQmakeEmptyPGresult().

388 {
389  PGEvent *newEvents;
390  size_t msize;
391  int i;
392 
393  if (!events || count <= 0)
394  return NULL;
395 
396  msize = count * sizeof(PGEvent);
397  newEvents = (PGEvent *) malloc(msize);
398  if (!newEvents)
399  return NULL;
400 
401  for (i = 0; i < count; i++)
402  {
403  newEvents[i].proc = events[i].proc;
404  newEvents[i].passThrough = events[i].passThrough;
405  newEvents[i].data = NULL;
406  newEvents[i].resultInitialized = false;
407  newEvents[i].name = strdup(events[i].name);
408  if (!newEvents[i].name)
409  {
410  while (--i >= 0)
411  free(newEvents[i].name);
412  free(newEvents);
413  return NULL;
414  }
415  msize += strlen(events[i].name) + 1;
416  }
417 
418  *memSize += msize;
419  return newEvents;
420 }
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:521
int i
void * passThrough
Definition: libpq-int.h:162

◆ get_hex()

static char get_hex ( char  c)
inlinestatic

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

References hexlookup.

Referenced by PQunescapeBytea().

3591 {
3592  int res = -1;
3593 
3594  if (c > 0 && c < 127)
3595  res = hexlookup[(unsigned char) c];
3596 
3597  return (char) res;
3598 }
static const int8 hexlookup[128]
Definition: fe-exec.c:3578
char * c

◆ getCopyResult()

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

Definition at line 1901 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().

1902 {
1903  /*
1904  * If the server connection has been lost, don't pretend everything is
1905  * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
1906  * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
1907  * error in the earlier steps in PQgetResult). The text returned in the
1908  * result is whatever is in conn->errorMessage; we hope that was filled
1909  * with something relevant when the lost connection was detected.
1910  */
1911  if (conn->status != CONNECTION_OK)
1912  {
1913  pqSaveErrorResult(conn);
1914  conn->asyncStatus = PGASYNC_IDLE;
1915  return pqPrepareAsyncResult(conn);
1916  }
1917 
1918  /* If we have an async result for the COPY, return that */
1919  if (conn->result && conn->result->resultStatus == copytype)
1920  return pqPrepareAsyncResult(conn);
1921 
1922  /* Otherwise, invent a suitable PGresult */
1923  return PQmakeEmptyPGresult(conn, copytype);
1924 }
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:826
PGresult * result
Definition: libpq-int.h:462
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:386
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:141
ConnStatusType status
Definition: libpq-int.h:385
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:772
ExecStatusType resultStatus
Definition: libpq-int.h:177

◆ parseInput()

static void parseInput ( PGconn conn)
static

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

References PG_PROTOCOL_MAJOR, pqParseInput2(), pqParseInput3(), and pg_conn::pversion.

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

1741 {
1742  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1743  pqParseInput3(conn);
1744  else
1745  pqParseInput2(conn);
1746 }
void pqParseInput2(PGconn *conn)
Definition: fe-protocol2.c:408
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
ProtocolVersion pversion
Definition: libpq-int.h:411
void pqParseInput3(PGconn *conn)
Definition: fe-protocol3.c:63

◆ pqAddTuple()

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

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

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

Referenced by pqRowProcessor(), and PQsetvalue().

927 {
928  if (res->ntups >= res->tupArrSize)
929  {
930  /*
931  * Try to grow the array.
932  *
933  * We can use realloc because shallow copying of the structure is
934  * okay. Note that the first time through, res->tuples is NULL. While
935  * ANSI says that realloc() should act like malloc() in that case,
936  * some old C libraries (like SunOS 4.1.x) coredump instead. On
937  * failure realloc is supposed to return NULL without damaging the
938  * existing allocation. Note that the positions beyond res->ntups are
939  * garbage, not necessarily NULL.
940  */
941  int newSize;
942  PGresAttValue **newTuples;
943 
944  /*
945  * Since we use integers for row numbers, we can't support more than
946  * INT_MAX rows. Make sure we allow that many, though.
947  */
948  if (res->tupArrSize <= INT_MAX / 2)
949  newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
950  else if (res->tupArrSize < INT_MAX)
951  newSize = INT_MAX;
952  else
953  {
954  *errmsgp = libpq_gettext("PGresult cannot support more than INT_MAX tuples");
955  return false;
956  }
957 
958  /*
959  * Also, on 32-bit platforms we could, in theory, overflow size_t even
960  * before newSize gets to INT_MAX. (In practice we'd doubtless hit
961  * OOM long before that, but let's check.)
962  */
963 #if INT_MAX >= (SIZE_MAX / 2)
964  if (newSize > SIZE_MAX / sizeof(PGresAttValue *))
965  {
966  *errmsgp = libpq_gettext("size_t overflow");
967  return false;
968  }
969 #endif
970 
971  if (res->tuples == NULL)
972  newTuples = (PGresAttValue **)
973  malloc(newSize * sizeof(PGresAttValue *));
974  else
975  newTuples = (PGresAttValue **)
976  realloc(res->tuples, newSize * sizeof(PGresAttValue *));
977  if (!newTuples)
978  return false; /* malloc or realloc failed */
979  res->memorySize +=
980  (newSize - res->tupArrSize) * sizeof(PGresAttValue *);
981  res->tupArrSize = newSize;
982  res->tuples = newTuples;
983  }
984  res->tuples[res->ntups] = tup;
985  res->ntups++;
986  return true;
987 }
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
#define SIZE_MAX
Definition: c.h:453
int ntups
Definition: libpq-int.h:169
#define realloc(a, b)
Definition: header.h:60
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQbinaryTuples()

int PQbinaryTuples ( const PGresult res)

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

References pg_result::binary.

Referenced by ProcessResult().

2786 {
2787  if (!res)
2788  return 0;
2789  return res->binary;
2790 }
int binary
Definition: libpq-int.h:179

◆ pqCatenateResultError()

void pqCatenateResultError ( PGresult res,
const char *  msg 
)

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

References appendPQExpBufferStr(), PQExpBufferData::data, pg_result::errMsg, initPQExpBuffer(), pqSetResultError(), and termPQExpBuffer().

Referenced by PQexecFinish(), pqSaveErrorResult(), and pqSaveWriteError().

676 {
677  PQExpBufferData errorBuf;
678 
679  if (!res || !msg)
680  return;
681  initPQExpBuffer(&errorBuf);
682  if (res->errMsg)
683  appendPQExpBufferStr(&errorBuf, res->errMsg);
684  appendPQExpBufferStr(&errorBuf, msg);
685  pqSetResultError(res, errorBuf.data);
686  termPQExpBuffer(&errorBuf);
687 }
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
char * errMsg
Definition: libpq-int.h:196
void pqSetResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:660
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92

◆ PQclear()

void PQclear ( PGresult res)

Definition at line 694 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(), 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_is_install_user(), check_loadable_libraries(), check_prepare_conn(), check_proper_datallowconn(), ClearOrSaveResult(), close_cursor(), cluster_all_databases(), connectDatabase(), ConnectDatabase(), connectToServer(), convertTSFunction(), create_cursor(), CreateReplicationSlot(), createViewAsClause(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_res_error(), deallocate_one(), 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(), 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_schema_name_patterns(), expand_table_name_patterns(), fail_lo_xact(), fetch_more_data(), findLastBuiltinOid_V71(), finish_foreign_modify(), finish_lo_xact(), get_create_object_cmd(), get_db_infos(), get_language_name(), get_loadable_libraries(), 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(), initGenerateDataClientSide(), libpq_executeFileMap(), libpqConnect(), libpqGetFile(), libpqProcessFileList(), 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(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listOneExtensionContents(), 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(), pqEndcopy2(), pqEndcopy3(), PQexecFinish(), PQexecStart(), pqGetErrorNotice2(), pqGetErrorNotice3(), pqInternalNotice(), PQmakeEmptyPGresult(), pqRowProcessor(), PQsetClientEncoding(), pqSetenvPoll(), prepare_common(), prepare_foreign_modify(), processExtensionTables(), processQueryResult(), ProcessResult(), PSQLexecWatch(), readCommandResponse(), receiveFileChunks(), ReceiveXlogStream(), ReconnectToServer(), 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(), try_complete_step(), tryExecuteStatement(), vacuum_all_databases(), vacuum_one_database(), and vacuumlo().

695 {
696  PGresult_data *block;
697  int i;
698 
699  if (!res)
700  return;
701 
702  for (i = 0; i < res->nEvents; i++)
703  {
704  /* only send DESTROY to successfully-initialized event procs */
705  if (res->events[i].resultInitialized)
706  {
708 
709  evt.result = res;
710  (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
711  res->events[i].passThrough);
712  }
713  free(res->events[i].name);
714  }
715 
716  if (res->events)
717  free(res->events);
718 
719  /* Free all the subsidiary blocks */
720  while ((block = res->curBlock) != NULL)
721  {
722  res->curBlock = block->next;
723  free(block);
724  }
725 
726  /* Free the top-level tuple pointer array */
727  if (res->tuples)
728  free(res->tuples);
729 
730  /* zero out the pointer fields to catch programming errors */
731  res->attDescs = NULL;
732  res->tuples = NULL;
733  res->paramDescs = NULL;
734  res->errFields = NULL;
735  res->events = NULL;
736  res->nEvents = 0;
737  /* res->curBlock was zeroed out earlier */
738 
739  /* Free the PGresult structure itself */
740  free(res);
741 }
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 749 of file fe-exec.c.

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

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

750 {
751  if (conn->result)
752  PQclear(conn->result);
753  conn->result = NULL;
754  if (conn->next_result)
755  PQclear(conn->next_result);
756  conn->next_result = NULL;
757 }
PGresult * result
Definition: libpq-int.h:462
PGresult * next_result
Definition: libpq-int.h:463
void PQclear(PGresult *res)
Definition: fe-exec.c:694

◆ PQcmdStatus()

char* PQcmdStatus ( PGresult res)

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

References pg_result::cmdStatus.

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

3041 {
3042  if (!res)
3043  return NULL;
3044  return res->cmdStatus;
3045 }
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178

◆ PQcmdTuples()

char* PQcmdTuples ( PGresult res)

Definition at line 3110 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().

3111 {
3112  char *p,
3113  *c;
3114 
3115  if (!res)
3116  return "";
3117 
3118  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3119  {
3120  p = res->cmdStatus + 7;
3121  /* INSERT: skip oid and space */
3122  while (*p && *p != ' ')
3123  p++;
3124  if (*p == 0)
3125  goto interpret_error; /* no space? */
3126  p++;
3127  }
3128  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3129  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3130  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3131  p = res->cmdStatus + 7;
3132  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
3133  p = res->cmdStatus + 6;
3134  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3135  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3136  p = res->cmdStatus + 5;
3137  else
3138  return "";
3139 
3140  /* check that we have an integer (at least one digit, nothing else) */
3141  for (c = p; *c; c++)
3142  {
3143  if (!isdigit((unsigned char) *c))
3144  goto interpret_error;
3145  }
3146  if (c == p)
3147  goto interpret_error;
3148 
3149  return p;
3150 
3151 interpret_error:
3153  "could not interpret result from server: %s",
3154  res->cmdStatus);
3155  return "";
3156 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
char * c
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:871
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178

◆ PQconsumeInput()

int PQconsumeInput ( PGconn conn)

Definition at line 1704 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(), ParallelSlotsGetIdle(), pgfdw_get_cleanup_result(), pgfdw_get_result(), PQconnectPoll(), PrintNotifications(), StreamLogicalLog(), and try_complete_step().

1705 {
1706  if (!conn)
1707  return 0;
1708 
1709  /*
1710  * for non-blocking connections try to flush the send-queue, otherwise we
1711  * may never get a response for something that may not have already been
1712  * sent because it's in our write buffer!
1713  */
1714  if (pqIsnonblocking(conn))
1715  {
1716  if (pqFlush(conn) < 0)
1717  return 0;
1718  }
1719 
1720  /*
1721  * Load more data, if available. We do this no matter what state we are
1722  * in, since we are probably getting called because the application wants
1723  * to get rid of a read-select condition. Note that we will NOT block
1724  * waiting for more input.
1725  */
1726  if (pqReadData(conn) < 0)
1727  return 0;
1728 
1729  /* Parsing of the data waits till later. */
1730  return 1;
1731 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:997
#define pqIsnonblocking(conn)
Definition: libpq-int.h:784
int pqReadData(PGconn *conn)
Definition: fe-misc.c:628

◆ PQcopyResult()

PGresult* PQcopyResult ( const PGresult src,
int  flags 
)

Definition at line 294 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().

295 {
296  PGresult *dest;
297  int i;
298 
299  if (!src)
300  return NULL;
301 
302  dest = PQmakeEmptyPGresult(NULL, PGRES_TUPLES_OK);
303  if (!dest)
304  return NULL;
305 
306  /* Always copy these over. Is cmdStatus really useful here? */
307  dest->client_encoding = src->client_encoding;
308  strcpy(dest->cmdStatus, src->cmdStatus);
309 
310  /* Wants attrs? */
311  if (flags & (PG_COPYRES_ATTRS | PG_COPYRES_TUPLES))
312  {
313  if (!PQsetResultAttrs(dest, src->numAttributes, src->attDescs))
314  {
315  PQclear(dest);
316  return NULL;
317  }
318  }
319 
320  /* Wants to copy tuples? */
321  if (flags & PG_COPYRES_TUPLES)
322  {
323  int tup,
324  field;
325 
326  for (tup = 0; tup < src->ntups; tup++)
327  {
328  for (field = 0; field < src->numAttributes; field++)
329  {
330  if (!PQsetvalue(dest, tup, field,
331  src->tuples[tup][field].value,
332  src->tuples[tup][field].len))
333  {
334  PQclear(dest);
335  return NULL;
336  }
337  }
338  }
339  }
340 
341  /* Wants to copy notice hooks? */
342  if (flags & PG_COPYRES_NOTICEHOOKS)
343  dest->noticeHooks = src->noticeHooks;
344 
345  /* Wants to copy PGEvents? */
346  if ((flags & PG_COPYRES_EVENTS) && src->nEvents > 0)
347  {
348  dest->events = dupEvents(src->events, src->nEvents,
349  &dest->memorySize);
350  if (!dest->events)
351  {
352  PQclear(dest);
353  return NULL;
354  }
355  dest->nEvents = src->nEvents;
356  }
357 
358  /* Okay, trigger PGEVT_RESULTCOPY event */
359  for (i = 0; i < dest->nEvents; i++)
360  {
361  if (src->events[i].resultInitialized)
362  {
363  PGEventResultCopy evt;
364 
365  evt.src = src;
366  evt.dest = dest;
367  if (!dest->events[i].proc(PGEVT_RESULTCOPY, &evt,
368  dest->events[i].passThrough))
369  {
370  PQclear(dest);
371  return NULL;
372  }
373  dest->events[i].resultInitialized = true;
374  }
375  }
376 
377  return dest;
378 }
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:431
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:229
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:141
int numAttributes
Definition: libpq-int.h:170
#define PG_COPYRES_ATTRS
Definition: libpq-fe.h:34
void PQclear(PGresult *res)
Definition: fe-exec.c:694
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:387
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 2175 of file fe-exec.c.

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

2176 {
2177  if (!PQexecStart(conn))
2178  return NULL;
2179  if (!PQsendDescribe(conn, 'P', portal))
2180  return NULL;
2181  return PQexecFinish(conn);
2182 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2220
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2095
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2021

◆ PQdescribePrepared()

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

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

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

Referenced by DescribeQuery(), and ECPGdescribe().

2157 {
2158  if (!PQexecStart(conn))
2159  return NULL;
2160  if (!PQsendDescribe(conn, 'S', stmt))
2161  return NULL;
2162  return PQexecFinish(conn);
2163 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2220
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2095
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2021

◆ PQendcopy()

int PQendcopy ( PGconn conn)

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

References PG_PROTOCOL_MAJOR, pqEndcopy2(), pqEndcopy3(), and pg_conn::pversion.

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

2619 {
2620  if (!conn)
2621  return 0;
2622 
2623  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2624  return pqEndcopy3(conn);
2625  else
2626  return pqEndcopy2(conn);
2627 }
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
int pqEndcopy3(PGconn *conn)
ProtocolVersion pversion
Definition: libpq-int.h:411
int pqEndcopy2(PGconn *conn)

◆ PQescapeBytea()

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

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

References PQescapeByteaInternal(), and static_std_strings.

3727 {
3728  return PQescapeByteaInternal(NULL, from, from_length, to_length,
3730  false /* can't use hex */ );
3731 }
static bool static_std_strings
Definition: fe-exec.c:50
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:3617

◆ PQescapeByteaConn()

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

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

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

3717 {
3718  if (!conn)
3719  return NULL;
3720  return PQescapeByteaInternal(conn, from, from_length, to_length,
3721  conn->std_strings,
3722  (conn->sversion >= 90000));
3723 }
int sversion
Definition: libpq-int.h:412
bool std_strings
Definition: libpq-int.h:435
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:3617

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

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

Referenced by PQescapeBytea(), and PQescapeByteaConn().

3620 {
3621  const unsigned char *vp;
3622  unsigned char *rp;
3623  unsigned char *result;
3624  size_t i;
3625  size_t len;
3626  size_t bslash_len = (std_strings ? 1 : 2);
3627 
3628  /*
3629  * empty string has 1 char ('\0')
3630  */
3631  len = 1;
3632 
3633  if (use_hex)
3634  {
3635  len += bslash_len + 1 + 2 * from_length;
3636  }
3637  else
3638  {
3639  vp = from;
3640  for (i = from_length; i > 0; i--, vp++)
3641  {
3642  if (*vp < 0x20 || *vp > 0x7e)
3643  len += bslash_len + 3;
3644  else if (*vp == '\'')
3645  len += 2;
3646  else if (*vp == '\\')
3647  len += bslash_len + bslash_len;
3648  else
3649  len++;
3650  }
3651  }
3652 
3653  *to_length = len;
3654  rp = result = (unsigned char *) malloc(len);
3655  if (rp == NULL)
3656  {
3657  if (conn)
3659  libpq_gettext("out of memory\n"));
3660  return NULL;
3661  }
3662 
3663  if (use_hex)
3664  {
3665  if (!std_strings)
3666  *rp++ = '\\';
3667  *rp++ = '\\';
3668  *rp++ = 'x';
3669  }
3670 
3671  vp = from;
3672  for (i = from_length; i > 0; i--, vp++)
3673  {
3674  unsigned char c = *vp;
3675 
3676  if (use_hex)
3677  {
3678  *rp++ = hextbl[(c >> 4) & 0xF];
3679  *rp++ = hextbl[c & 0xF];
3680  }
3681  else if (c < 0x20 || c > 0x7e)
3682  {
3683  if (!std_strings)
3684  *rp++ = '\\';
3685  *rp++ = '\\';
3686  *rp++ = (c >> 6) + '0';
3687  *rp++ = ((c >> 3) & 07) + '0';
3688  *rp++ = (c & 07) + '0';
3689  }
3690  else if (c == '\'')
3691  {
3692  *rp++ = '\'';
3693  *rp++ = '\'';
3694  }
3695  else if (c == '\\')
3696  {
3697  if (!std_strings)
3698  {
3699  *rp++ = '\\';
3700  *rp++ = '\\';
3701  }
3702  *rp++ = '\\';
3703  *rp++ = '\\';
3704  }
3705  else
3706  *rp++ = c;
3707  }
3708  *rp = '\0';
3709 
3710  return result;
3711 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
#define malloc(a)
Definition: header.h:50
char * c
PQExpBufferData errorMessage
Definition: libpq-int.h:511
static const char hextbl[]
Definition: fe-exec.c:3576
int i
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQescapeIdentifier()

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

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

References PQescapeInternal().

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

3571 {
3572  return PQescapeInternal(conn, str, len, true);
3573 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:3443

◆ PQescapeInternal()

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

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

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

Referenced by PQescapeIdentifier(), and PQescapeLiteral().

3444 {
3445  const char *s;
3446  char *result;
3447  char *rp;
3448  int num_quotes = 0; /* single or double, depending on as_ident */
3449  int num_backslashes = 0;
3450  int input_len;
3451  int result_size;
3452  char quote_char = as_ident ? '"' : '\'';
3453 
3454  /* We must have a connection, else fail immediately. */
3455  if (!conn)
3456  return NULL;
3457 
3458  /* Scan the string for characters that must be escaped. */
3459  for (s = str; (s - str) < len && *s != '\0'; ++s)
3460  {
3461  if (*s == quote_char)
3462  ++num_quotes;
3463  else if (*s == '\\')
3464  ++num_backslashes;
3465  else if (IS_HIGHBIT_SET(*s))
3466  {
3467  int charlen;
3468 
3469  /* Slow path for possible multibyte characters */
3470  charlen = pg_encoding_mblen(conn->client_encoding, s);
3471 
3472  /* Multibyte character overruns allowable length. */
3473  if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
3474  {
3476  libpq_gettext("incomplete multibyte character\n"));
3477  return NULL;
3478  }
3479 
3480  /* Adjust s, bearing in mind that for loop will increment it. */
3481  s += charlen - 1;
3482  }
3483  }
3484 
3485  /* Allocate output buffer. */
3486  input_len = s - str;
3487  result_size = input_len + num_quotes + 3; /* two quotes, plus a NUL */
3488  if (!as_ident && num_backslashes > 0)
3489  result_size += num_backslashes + 2;
3490  result = rp = (char *) malloc(result_size);
3491  if (rp == NULL)
3492  {
3494  libpq_gettext("out of memory\n"));
3495  return NULL;
3496  }
3497 
3498  /*
3499  * If we are escaping a literal that contains backslashes, we use the
3500  * escape string syntax so that the result is correct under either value
3501  * of standard_conforming_strings. We also emit a leading space in this
3502  * case, to guard against the possibility that the result might be
3503  * interpolated immediately following an identifier.
3504  */
3505  if (!as_ident && num_backslashes > 0)
3506  {
3507  *rp++ = ' ';
3508  *rp++ = 'E';
3509  }
3510 
3511  /* Opening quote. */
3512  *rp++ = quote_char;
3513 
3514  /*
3515  * Use fast path if possible.
3516  *
3517  * We've already verified that the input string is well-formed in the
3518  * current encoding. If it contains no quotes and, in the case of
3519  * literal-escaping, no backslashes, then we can just copy it directly to
3520  * the output buffer, adding the necessary quotes.
3521  *
3522  * If not, we must rescan the input and process each character
3523  * individually.
3524  */
3525  if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
3526  {
3527  memcpy(rp, str, input_len);
3528  rp += input_len;
3529  }
3530  else
3531  {
3532  for (s = str; s - str < input_len; ++s)
3533  {
3534  if (*s == quote_char || (!as_ident && *s == '\\'))
3535  {
3536  *rp++ = *s;
3537  *rp++ = *s;
3538  }
3539  else if (!IS_HIGHBIT_SET(*s))
3540  *rp++ = *s;
3541  else
3542  {
3543  int i = pg_encoding_mblen(conn->client_encoding, s);
3544 
3545  while (1)
3546  {
3547  *rp++ = *s;
3548  if (--i == 0)
3549  break;
3550  ++s; /* for loop will provide the final increment */
3551  }
3552  }
3553  }
3554  }
3555 
3556  /* Closing quote and terminating NUL. */
3557  *rp++ = quote_char;
3558  *rp = '\0';
3559 
3560  return result;
3561 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
#define malloc(a)
Definition: header.h:50
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1100
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1833
PQExpBufferData errorMessage
Definition: libpq-int.h:511
int i
int client_encoding
Definition: libpq-int.h:434
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQescapeLiteral()

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

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

References PQescapeInternal().

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

3565 {
3566  return PQescapeInternal(conn, str, len, false);
3567 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:3443

◆ PQescapeString()

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

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

References PQescapeStringInternal(), static_client_encoding, and static_std_strings.

Referenced by get_comma_elts(), and quote_postgres().

3429 {
3430  return PQescapeStringInternal(NULL, to, from, length, NULL,
3433 }
static bool static_std_strings
Definition: fe-exec.c:50
static int static_client_encoding
Definition: fe-exec.c:49
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:3335

◆ PQescapeStringConn()

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

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

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

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

3413 {
3414  if (!conn)
3415  {
3416  /* force empty-string result */
3417  *to = '\0';
3418  if (error)
3419  *error = 1;
3420  return 0;
3421  }
3422  return PQescapeStringInternal(conn, to, from, length, error,
3423  conn->client_encoding,
3424  conn->std_strings);
3425 }
static void error(void)
Definition: sql-dyntest.c:147
bool std_strings
Definition: libpq-int.h:435
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:3335
int client_encoding
Definition: libpq-int.h:434

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

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

Referenced by PQescapeString(), and PQescapeStringConn().

3339 {
3340  const char *source = from;
3341  char *target = to;
3342  size_t remaining = length;
3343 
3344  if (error)
3345  *error = 0;
3346 
3347  while (remaining > 0 && *source != '\0')
3348  {
3349  char c = *source;
3350  int len;
3351  int i;
3352 
3353  /* Fast path for plain ASCII */
3354  if (!IS_HIGHBIT_SET(c))
3355  {
3356  /* Apply quoting if needed */
3357  if (SQL_STR_DOUBLE(c, !std_strings))
3358  *target++ = c;
3359  /* Copy the character */
3360  *target++ = c;
3361  source++;
3362  remaining--;
3363  continue;
3364  }
3365 
3366  /* Slow path for possible multibyte characters */
3367  len = pg_encoding_mblen(encoding, source);
3368 
3369  /* Copy the character */
3370  for (i = 0; i < len; i++)
3371  {
3372  if (remaining == 0 || *source == '\0')
3373  break;
3374  *target++ = *source++;
3375  remaining--;
3376  }
3377 
3378  /*
3379  * If we hit premature end of string (ie, incomplete multibyte
3380  * character), try to pad out to the correct length with spaces. We
3381  * may not be able to pad completely, but we will always be able to
3382  * insert at least one pad space (since we'd not have quoted a
3383  * multibyte character). This should be enough to make a string that
3384  * the server will error out on.
3385  */
3386  if (i < len)
3387  {
3388  if (error)
3389  *error = 1;
3390  if (conn)
3392  libpq_gettext("incomplete multibyte character\n"));
3393  for (; i < len; i++)
3394  {
3395  if (((size_t) (target - to)) / 2 >= length)
3396  break;
3397  *target++ = ' ';
3398  }
3399  break;
3400  }
3401  }
3402 
3403  /* Write the terminating NUL character. */
3404  *target = '\0';
3405 
3406  return target - to;
3407 }
int remaining
Definition: informix.c:687
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
static void error(void)
Definition: sql-dyntest.c:147
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1100
char * c
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1833
PQExpBufferData errorMessage
Definition: libpq-int.h:511
int32 encoding
Definition: pg_database.h:41
int i
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:1108
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQexec()

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

Definition at line 1939 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(), initGenerateDataClientSide(), libpq_executeFileMap(), libpqConnect(), libpqProcessFileList(), 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(), tryExecuteStatement(), and vacuumlo().

1940 {
1941  if (!PQexecStart(conn))
1942  return NULL;
1943  if (!PQsendQuery(conn, query))
1944  return NULL;
1945  return PQexecFinish(conn);
1946 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1234
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2095
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2021

◆ PQexecFinish()

static PGresult * PQexecFinish ( PGconn conn)
static

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

References appendPQExpBufferStr(), CONNECTION_BAD, pg_result::errMsg, pg_conn::errorMessage, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_FATAL_ERROR, pqCatenateResultError(), PQclear(), PQgetResult(), resetPQExpBuffer(), pg_result::resultStatus, and pg_conn::status.

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

2096 {
2097  PGresult *result;
2098  PGresult *lastResult;
2099 
2100  /*
2101  * For backwards compatibility, return the last result if there are more
2102  * than one --- but merge error messages if we get more than one error
2103  * result.
2104  *
2105  * We have to stop if we see copy in/out/both, however. We will resume
2106  * parsing after application performs the data transfer.
2107  *
2108  * Also stop if the connection is lost (else we'll loop infinitely).
2109  */
2110  lastResult = NULL;
2111  while ((result = PQgetResult(conn)) != NULL)
2112  {
2113  if (lastResult)
2114  {
2115  if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
2116  result->resultStatus == PGRES_FATAL_ERROR)
2117  {
2118  pqCatenateResultError(lastResult, result->errMsg);
2119  PQclear(result);
2120  result = lastResult;
2121 
2122  /*
2123  * Make sure PQerrorMessage agrees with concatenated result
2124  */
2126  appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
2127  }
2128  else
2129  PQclear(lastResult);
2130  }
2131  lastResult = result;
2132  if (result->resultStatus == PGRES_COPY_IN ||
2133  result->resultStatus == PGRES_COPY_OUT ||
2134  result->resultStatus == PGRES_COPY_BOTH ||
2135  conn->status == CONNECTION_BAD)
2136  break;
2137  }
2138 
2139  return lastResult;
2140 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
char * errMsg
Definition: libpq-int.h:196
PQExpBufferData errorMessage
Definition: libpq-int.h:511
void PQclear(PGresult *res)
Definition: fe-exec.c:694
ConnStatusType status
Definition: libpq-int.h:385
void pqCatenateResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:675
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
ExecStatusType resultStatus
Definition: libpq-int.h:177
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1778

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

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

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

1961 {
1962  if (!PQexecStart(conn))
1963  return NULL;
1964  if (!PQsendQueryParams(conn, command,
1965  nParams, paramTypes, paramValues, paramLengths,
1966  paramFormats, resultFormat))
1967  return NULL;
1968  return PQexecFinish(conn);
1969 }
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:1285
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2095
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2021

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

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

Referenced by ecpg_execute(), and try_complete_step().

2007 {
2008  if (!PQexecStart(conn))
2009  return NULL;
2010  if (!PQsendQueryPrepared(conn, stmtName,
2011  nParams, paramValues, paramLengths,
2012  paramFormats, resultFormat))
2013  return NULL;
2014  return PQexecFinish(conn);
2015 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2095
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:1427
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2021

◆ PQexecStart()

static bool PQexecStart ( PGconn conn)
static

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

References pg_conn::asyncStatus, CONNECTION_BAD, pg_conn::errorMessage, libpq_gettext, PG_PROTOCOL_MAJOR, PGASYNC_BUSY, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PQclear(), PQgetResult(), PQputCopyEnd(), printfPQExpBuffer(), pg_conn::pversion, pg_result::resultStatus, and pg_conn::status.

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

2022 {
2023  PGresult *result;
2024 
2025  if (!conn)
2026  return false;
2027 
2028  /*
2029  * Silently discard any prior query result that application didn't eat.
2030  * This is probably poor design, but it's here for backward compatibility.
2031  */
2032  while ((result = PQgetResult(conn)) != NULL)
2033  {
2034  ExecStatusType resultStatus = result->resultStatus;
2035 
2036  PQclear(result); /* only need its status */
2037  if (resultStatus == PGRES_COPY_IN)
2038  {
2039  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2040  {
2041  /* In protocol 3, we can get out of a COPY IN state */
2042  if (PQputCopyEnd(conn,
2043  libpq_gettext("COPY terminated by new PQexec")) < 0)
2044  return false;
2045  /* keep waiting to swallow the copy's failure message */
2046  }
2047  else
2048  {
2049  /* In older protocols we have to punt */
2051  libpq_gettext("COPY IN state must be terminated first\n"));
2052  return false;
2053  }
2054  }
2055  else if (resultStatus == PGRES_COPY_OUT)
2056  {
2057  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2058  {
2059  /*
2060  * In protocol 3, we can get out of a COPY OUT state: we just
2061  * switch back to BUSY and allow the remaining COPY data to be
2062  * dropped on the floor.
2063  */
2064  conn->asyncStatus = PGASYNC_BUSY;
2065  /* keep waiting to swallow the copy's completion message */
2066  }
2067  else
2068  {
2069  /* In older protocols we have to punt */
2071  libpq_gettext("COPY OUT state must be terminated first\n"));
2072  return false;
2073  }
2074  }
2075  else if (resultStatus == PGRES_COPY_BOTH)
2076  {
2077  /* We don't allow PQexec during COPY BOTH */
2079  libpq_gettext("PQexec not allowed during COPY BOTH\n"));
2080  return false;
2081  }
2082  /* check for loss of connection, too */
2083  if (conn->status == CONNECTION_BAD)
2084  return false;
2085  }
2086 
2087  /* OK to send a command */
2088  return true;
2089 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2384
ExecStatusType
Definition: libpq-fe.h:84
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:386
PQExpBufferData errorMessage
Definition: libpq-int.h:511
void PQclear(PGresult *res)
Definition: fe-exec.c:694
ProtocolVersion pversion
Definition: libpq-int.h:411
ConnStatusType status
Definition: libpq-int.h:385
ExecStatusType resultStatus
Definition: libpq-int.h:177
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1778
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQfformat()

int PQfformat ( const PGresult res,
int  field_num 
)

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

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

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

2997 {
2998  if (!check_field_number(res, field_num))
2999  return 0;
3000  if (res->attDescs)
3001  return res->attDescs[field_num].format;
3002  else
3003  return 0;
3004 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2798

◆ PQflush()

int PQflush ( PGconn conn)

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

References pqFlush().

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

3284 {
3285  return pqFlush(conn);
3286 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:997

◆ PQfmod()

int PQfmod ( const PGresult res,
int  field_num 
)

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

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

Referenced by DescribeQuery(), and ECPGget_desc().

3030 {
3031  if (!check_field_number(res, field_num))
3032  return 0;
3033  if (res->attDescs)
3034  return res->attDescs[field_num].atttypmod;
3035  else
3036  return 0;
3037 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
int atttypmod
Definition: libpq-fe.h:246
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2798

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

References pg_conn::asyncStatus, pg_conn::errorMessage, libpq_gettext, PG_PROTOCOL_MAJOR, PGASYNC_IDLE, PGINVALID_SOCKET, pqFunctionCall2(), pqFunctionCall3(), printfPQExpBuffer(), pg_conn::pversion, 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().

2659 {
2660  *result_len = 0;
2661 
2662  if (!conn)
2663  return NULL;
2664 
2665  /* clear the error string */
2667 
2668  if (conn->sock == PGINVALID_SOCKET || conn->asyncStatus != PGASYNC_IDLE ||
2669  conn->result != NULL)
2670  {
2672  libpq_gettext("connection in wrong state\n"));
2673  return NULL;
2674  }
2675 
2676  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2677  return pqFunctionCall3(conn, fnid,
2678  result_buf, result_len,
2679  result_is_int,
2680  args, nargs);
2681  else
2682  return pqFunctionCall2(conn, fnid,
2683  result_buf, result_len,
2684  result_is_int,
2685  args, nargs);
2686 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
PGresult * pqFunctionCall2(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
PGresult * pqFunctionCall3(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGresult * result
Definition: libpq-int.h:462
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:386
pgsocket sock
Definition: libpq-int.h:407
#define PGINVALID_SOCKET
Definition: port.h:33
PQExpBufferData errorMessage
Definition: libpq-int.h:511
ProtocolVersion pversion
Definition: libpq-int.h:411
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQfname()

char* PQfname ( const PGresult res,
int  field_num 
)

Definition at line 2855 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().

2856 {
2857  if (!check_field_number(res, field_num))
2858  return NULL;
2859  if (res->attDescs)
2860  return res->attDescs[field_num].name;
2861  else
2862  return NULL;
2863 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2798
char * name
Definition: libpq-fe.h:240

◆ PQfnumber()

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

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

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

Referenced by 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_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().

2878 {
2879  char *field_case;
2880  bool in_quotes;
2881  bool all_lower = true;
2882  const char *iptr;
2883  char *optr;
2884  int i;
2885 
2886  if (!res)
2887  return -1;
2888 
2889  /*
2890  * Note: it is correct to reject a zero-length input string; the proper
2891  * input to match a zero-length field name would be "".
2892  */
2893  if (field_name == NULL ||
2894  field_name[0] == '\0' ||
2895  res->attDescs == NULL)
2896  return -1;
2897 
2898  /*
2899  * Check if we can avoid the strdup() and related work because the
2900  * passed-in string wouldn't be changed before we do the check anyway.
2901  */
2902  for (iptr = field_name; *iptr; iptr++)
2903  {
2904  char c = *iptr;
2905 
2906  if (c == '"' || c != pg_tolower((unsigned char) c))
2907  {
2908  all_lower = false;
2909  break;
2910  }
2911  }
2912 
2913  if (all_lower)
2914  for (i = 0; i < res->numAttributes; i++)
2915  if (strcmp(field_name, res->attDescs[i].name) == 0)
2916  return i;
2917 
2918  /* Fall through to the normal check if that didn't work out. */
2919 
2920  /*
2921  * Note: this code will not reject partially quoted strings, eg
2922  * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
2923  * condition.
2924  */
2925  field_case = strdup(field_name);
2926  if (field_case == NULL)
2927  return -1; /* grotty */
2928 
2929  in_quotes = false;
2930  optr = field_case;
2931  for (iptr = field_case; *iptr; iptr++)
2932  {
2933  char c = *iptr;
2934 
2935  if (in_quotes)
2936  {
2937  if (c == '"')
2938  {
2939  if (iptr[1] == '"')
2940  {
2941  /* doubled quotes become a single quote */
2942  *optr++ = '"';
2943  iptr++;
2944  }
2945  else
2946  in_quotes = false;
2947  }
2948  else
2949  *optr++ = c;
2950  }
2951  else if (c == '"')
2952  in_quotes = true;
2953  else
2954  {
2955  c = pg_tolower((unsigned char) c);
2956  *optr++ = c;
2957  }
2958  }
2959  *optr = '\0';
2960 
2961  for (i = 0; i < res->numAttributes; i++)
2962  {
2963  if (strcmp(field_case, res->attDescs[i].name) == 0)
2964  {
2965  free(field_case);
2966  return i;
2967  }
2968  }
2969  free(field_case);
2970  return -1;
2971 }
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:240

◆ PQfreemem()

◆ PQfreeNotify()

void PQfreeNotify ( PGnotify notify)

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

References PQfreemem().

Referenced by PQfreemem().

3314 {
3315  PQfreemem(notify);
3316 }
void PQfreemem(void *ptr)
Definition: fe-exec.c:3296

◆ PQfsize()

int PQfsize ( const PGresult res,
int  field_num 
)

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

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

Referenced by ecpg_build_compat_sqlda(), and ECPGget_desc().

3019 {
3020  if (!check_field_number(res, field_num))
3021  return 0;
3022  if (res->attDescs)
3023  return res->attDescs[field_num].typlen;
3024  else
3025  return 0;
3026 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2798

◆ PQftable()

Oid PQftable ( const PGresult res,
int  field_num 
)

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

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

2975 {
2976  if (!check_field_number(res, field_num))
2977  return InvalidOid;
2978  if (res->attDescs)
2979  return res->attDescs[field_num].tableid;
2980  else
2981  return InvalidOid;
2982 }
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:2798

◆ PQftablecol()

int PQftablecol ( const PGresult res,
int  field_num 
)

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

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

2986 {
2987  if (!check_field_number(res, field_num))
2988  return 0;
2989  if (res->attDescs)
2990  return res->attDescs[field_num].columnid;
2991  else
2992  return 0;
2993 }
int columnid
Definition: libpq-fe.h:242
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2798

◆ PQftype()

Oid PQftype ( const PGresult res,
int  field_num 
)

Definition at line 3007 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(), receiveFileChunks(), and sqlda_common_total_size().

3008 {
3009  if (!check_field_number(res, field_num))
3010  return InvalidOid;
3011  if (res->attDescs)
3012  return res->attDescs[field_num].typid;
3013  else
3014  return InvalidOid;
3015 }
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:2798

◆ PQgetCopyData()

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

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

References pg_conn::asyncStatus, pg_conn::errorMessage, libpq_gettext, PG_PROTOCOL_MAJOR, PGASYNC_COPY_BOTH, PGASYNC_COPY_OUT, pqGetCopyData2(), pqGetCopyData3(), printfPQExpBuffer(), and pg_conn::pversion.

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

2474 {
2475  *buffer = NULL; /* for all failure cases */
2476  if (!conn)
2477  return -2;
2478  if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2479  conn->asyncStatus != PGASYNC_COPY_BOTH)
2480  {
2482  libpq_gettext("no COPY in progress\n"));
2483  return -2;
2484  }
2485  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2486  return pqGetCopyData3(conn, buffer, async);
2487  else
2488  return pqGetCopyData2(conn, buffer, async);
2489 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:386
int pqGetCopyData3(PGconn *conn, char **buffer, int async)
PQExpBufferData errorMessage
Definition: libpq-int.h:511
ProtocolVersion pversion
Definition: libpq-int.h:411
int pqGetCopyData2(PGconn *conn, char **buffer, int async)
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQgetisnull()

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

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

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

Referenced by BaseBackup(), binary_upgrade_set_type_oids_by_rel_oid(), describeOneTableDetails(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpDatabaseConfig(), dumpDomain(), 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(), libpqGetFile(), libpqProcessFileList(), libpqrcv_create_slot(), libpqrcv_processTuples(), listTSConfigsVerbose(), listTSParsersVerbose(), make_tuple_from_result_row(), materializeResult(), postgresImportForeignSchema(), printCrosstab(), printQuery(), PrintResultsInCrosstab(), ReceiveAndUnpackTarFile(), receiveFileChunks(), ReceiveTarFile(), run_simple_query(), RunIdentifySystem(), sqlda_common_total_size(), StoreQueryTuple(), storeRow(), and vacuum_one_database().

3189 {
3190  if (!check_tuple_field_number(res, tup_num, field_num))
3191  return 1; /* pretend it is null */
3192  if (res->tuples[tup_num][field_num].len == NULL_LEN)
3193  return 1;
3194  else
3195  return 0;
3196 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:2813
#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 3174 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(), libpqGetFile(), libpqrcv_readtimelinehistoryfile(), PQdisplayTuples(), receiveFileChunks(), and show_binary_results().

3175 {
3176  if (!check_tuple_field_number(res, tup_num, field_num))
3177  return 0;
3178  if (res->tuples[tup_num][field_num].len != NULL_LEN)
3179  return res->tuples[tup_num][field_num].len;
3180  else
3181  return 0;
3182 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:2813
#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 2515 of file fe-exec.c.

References PG_PROTOCOL_MAJOR, pqGetline2(), pqGetline3(), and pg_conn::pversion.

2516 {
2517  if (!s || maxlen <= 0)
2518  return EOF;
2519  *s = '\0';
2520  /* maxlen must be at least 3 to hold the \. terminator! */
2521  if (maxlen < 3)
2522  return EOF;
2523 
2524  if (!conn)
2525  return EOF;
2526 
2527  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2528  return pqGetline3(conn, s, maxlen);
2529  else
2530  return pqGetline2(conn, s, maxlen);
2531 }
int pqGetline3(PGconn *conn, char *s, int maxlen)
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
int pqGetline2(PGconn *conn, char *s, int maxlen)
ProtocolVersion pversion
Definition: libpq-int.h:411

◆ PQgetlineAsync()

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

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

References PG_PROTOCOL_MAJOR, pqGetlineAsync2(), pqGetlineAsync3(), and pg_conn::pversion.

Referenced by pqGetline3().

2566 {
2567  if (!conn)
2568  return -1;
2569 
2570  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2571  return pqGetlineAsync3(conn, buffer, bufsize);
2572  else
2573  return pqGetlineAsync2(conn, buffer, bufsize);
2574 }
int pqGetlineAsync2(PGconn *conn, char *buffer, int bufsize)
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)
ProtocolVersion pversion
Definition: libpq-int.h:411

◆ PQgetResult()

PGresult* PQgetResult ( PGconn conn)

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

References pg_conn::asyncStatus, 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, PGEVT_RESULTCREATE, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_FATAL_ERROR, pqFlush(), PQmakeEmptyPGresult(), pqPrepareAsyncResult(), pqReadData(), pqSaveErrorResult(), pqSaveWriteError(), pqSetResultError(), pqWait(), printfPQExpBuffer(), PGEvent::proc, 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(), libpq_executeFileMap(), libpqrcv_PQgetResult(), ParallelSlotsGetIdle(), pgfdw_get_cleanup_result(), pgfdw_get_result(), PQconnectPoll(), pqEndcopy2(), pqEndcopy3(), PQexecFinish(), PQexecStart(), pqSetenvPoll(), ProcessResult(), readCommandResponse(), ReceiveAndUnpackTarFile(), receiveFileChunks(), ReceiveTarFile(), ReceiveXlogStream(), storeQueryResult(), StreamLogicalLog(), and try_complete_step().

1779 {
1780  PGresult *res;
1781 
1782  if (!conn)
1783  return NULL;
1784 
1785  /* Parse any available data, if our state permits. */
1786  parseInput(conn);
1787 
1788  /* If not ready to return something, block until we are. */
1789  while (conn->asyncStatus == PGASYNC_BUSY)
1790  {
1791  int flushResult;
1792 
1793  /*
1794  * If data remains unsent, send it. Else we might be waiting for the
1795  * result of a command the backend hasn't even got yet.
1796  */
1797  while ((flushResult = pqFlush(conn)) > 0)
1798  {
1799  if (pqWait(false, true, conn))
1800  {
1801  flushResult = -1;
1802  break;
1803  }
1804  }
1805 
1806  /*
1807  * Wait for some more data, and load it. (Note: if the connection has
1808  * been lost, pqWait should return immediately because the socket
1809  * should be read-ready, either with the last server data or with an
1810  * EOF indication. We expect therefore that this won't result in any
1811  * undue delay in reporting a previous write failure.)
1812  */
1813  if (flushResult ||
1814  pqWait(true, false, conn) ||
1815  pqReadData(conn) < 0)
1816  {
1817  /*
1818  * conn->errorMessage has been set by pqWait or pqReadData. We
1819  * want to append it to any already-received error message.
1820  */
1821  pqSaveErrorResult(conn);
1822  conn->asyncStatus = PGASYNC_IDLE;
1823  return pqPrepareAsyncResult(conn);
1824  }
1825 
1826  /* Parse it. */
1827  parseInput(conn);
1828 
1829  /*
1830  * If we had a write error, but nothing above obtained a query result
1831  * or detected a read error, report the write error.
1832  */
1833  if (conn->write_failed && conn->asyncStatus == PGASYNC_BUSY)
1834  {
1835  pqSaveWriteError(conn);
1836  conn->asyncStatus = PGASYNC_IDLE;
1837  return pqPrepareAsyncResult(conn);
1838  }
1839  }
1840 
1841  /* Return the appropriate thing. */
1842  switch (conn->asyncStatus)
1843  {
1844  case PGASYNC_IDLE:
1845  res = NULL; /* query is complete */
1846  break;
1847  case PGASYNC_READY:
1848  res = pqPrepareAsyncResult(conn);
1849  /* Set the state back to BUSY, allowing parsing to proceed. */
1850  conn->asyncStatus = PGASYNC_BUSY;
1851  break;
1852  case PGASYNC_COPY_IN:
1853  res = getCopyResult(conn, PGRES_COPY_IN);
1854  break;
1855  case PGASYNC_COPY_OUT:
1856  res = getCopyResult(conn, PGRES_COPY_OUT);
1857  break;
1858  case PGASYNC_COPY_BOTH:
1859  res = getCopyResult(conn, PGRES_COPY_BOTH);
1860  break;
1861  default:
1863  libpq_gettext("unexpected asyncStatus: %d\n"),
1864  (int) conn->asyncStatus);
1866  break;
1867  }
1868 
1869  if (res)
1870  {
1871  int i;
1872 
1873  for (i = 0; i < res->nEvents; i++)
1874  {
1875  PGEventResultCreate evt;
1876 
1877  evt.conn = conn;
1878  evt.result = res;
1879  if (!res->events[i].proc(PGEVT_RESULTCREATE, &evt,
1880  res->events[i].passThrough))
1881  {
1883  libpq_gettext("PGEventProc \"%s\" failed during PGEVT_RESULTCREATE event\n"),
1884  res->events[i].name);
1885  pqSetResultError(res, conn->errorMessage.data);
1887  break;
1888  }
1889  res->events[i].resultInitialized = true;
1890  }
1891  }
1892 
1893  return res;
1894 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:997
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
bool resultInitialized
Definition: libpq-int.h:164
int nEvents
Definition: libpq-int.h:188
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:826
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:386
bool write_failed
Definition: libpq-int.h:417
PGconn * conn
Definition: streamutil.c:54
int pqReadData(PGconn *conn)
Definition: fe-misc.c:628
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:1020
static PGresult * getCopyResult(PGconn *conn, ExecStatusType copytype)
Definition: fe-exec.c:1901
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:141
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1740
PQExpBufferData errorMessage
Definition: libpq-int.h:511
void pqSetResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:660
PGEventProc proc
Definition: libpq-int.h:160
static void pqSaveWriteError(PGconn *conn)
Definition: fe-exec.c:798
int i
void * passThrough
Definition: libpq-int.h:162
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:772
PGEvent * events
Definition: libpq-int.h:187
char * name
Definition: libpq-int.h:161
ExecStatusType resultStatus
Definition: libpq-int.h:177
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQgetvalue()

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

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

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

Referenced by _check_database_version(), add_tablespace_footer(), 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_is_install_user(), check_proper_datallowconn(), cluster_all_databases(), collectComments(), collectSecLabels(), 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(), 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_schema_name_patterns(), expand_table_name_patterns(), findLastBuiltinOid_V71(), get_create_object_cmd(), get_db_infos(), get_language_name(), get_loadable_libraries(), 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(), libpqGetFile(), libpqProcessFileList(), 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(), pqSetenvPoll(), printCrosstab(), printQuery(), printResultSet(), PrintResultsInCrosstab(), processExtensionTables(), readCommandResponse(), ReadEndOfStreamingResult(), ReceiveAndUnpackTarFile(), receiveFileChunks(), ReceiveTarFile(), ReceiveXlogStream(), reindex_all_databases(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_simple_query(), RunIdentifySystem(), set_frozenxids(), show_binary_results(), sql_exec(), sqlda_common_total_size(), StoreQueryTuple(), storeRow(), try_complete_step(), vacuum_all_databases(), vacuum_one_database(), and vacuumlo().

3164 {
3165  if (!check_tuple_field_number(res, tup_num, field_num))
3166  return NULL;
3167  return res->tuples[tup_num][field_num].value;
3168 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:2813
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 871 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(), pqEndcopy2(), pqEndcopy3(), pqGetInt(), pqParseInput2(), pqParseInput3(), pqPutInt(), and PQsetvalue().

872 {
873  char msgBuf[1024];
874  va_list args;
875  PGresult *res;
876 
877  if (hooks->noticeRec == NULL)
878  return; /* nobody home to receive notice? */
879 
880  /* Format the message */
881  va_start(args, fmt);
882  vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
883  va_end(args);
884  msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
885 
886  /* Make a PGresult to pass to the notice receiver */
888  if (!res)
889  return;
890  res->noticeHooks = *hooks;
891 
892  /*
893  * Set up fields of notice.
894  */
898  /* XXX should provide a SQLSTATE too? */
899 
900  /*
901  * Result text is always just the primary message + newline. If we can't
902  * allocate it, don't bother invoking the receiver.
903  */
904  res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, false);
905  if (res->errMsg)
906  {
907  sprintf(res->errMsg, "%s\n", msgBuf);
908 
909  /*
910  * Pass to receiver, then free it.
911  */
912  res->noticeHooks.noticeRec(res->noticeHooks.noticeRecArg, res);
913  }
914  PQclear(res);
915 }
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:58
#define sprintf
Definition: port.h:194
#define vsnprintf
Definition: port.h:191
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:141
void pqSaveMessageField(PGresult *res, char code, const char *value)
Definition: fe-exec.c:993
#define PG_DIAG_SEVERITY_NONLOCALIZED
Definition: postgres_ext.h:56
void PQclear(PGresult *res)
Definition: fe-exec.c:694
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:534
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQisBusy()

int PQisBusy ( PGconn conn)

Definition at line 1754 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(), ParallelSlotsGetIdle(), pgfdw_get_cleanup_result(), pgfdw_get_result(), PQconnectPoll(), pqEndcopy2(), pqEndcopy3(), pqSetenvPoll(), and try_complete_step().

1755 {
1756  if (!conn)
1757  return false;
1758 
1759  /* Parse any available data, if our state permits. */
1760  parseInput(conn);
1761 
1762  /*
1763  * PQgetResult will return immediately in all states except BUSY, or if we
1764  * had a write failure.
1765  */
1766  return conn->asyncStatus == PGASYNC_BUSY || conn->write_failed;
1767 }
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:386
bool write_failed
Definition: libpq-int.h:417
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1740

◆ PQisnonblocking()

int PQisnonblocking ( const PGconn conn)

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

References pqIsnonblocking.

3265 {
3266  return pqIsnonblocking(conn);
3267 }
#define pqIsnonblocking(conn)
Definition: libpq-int.h:784

◆ PQisthreadsafe()

int PQisthreadsafe ( void  )

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

3272 {
3273 #ifdef ENABLE_THREAD_SAFETY
3274  return true;
3275 #else
3276  return false;
3277 #endif
3278 }

◆ PQmakeEmptyPGresult()

PGresult* PQmakeEmptyPGresult ( PGconn conn,
ExecStatusType  status 
)

Definition at line 141 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(), getAnotherTuple(), getCopyResult(), getCopyStart(), getParamDescriptions(), getRowDescriptions(), PQcopyResult(), pqFunctionCall2(), pqFunctionCall3(), pqGetErrorNotice2(), pqGetErrorNotice3(), PQgetResult(), pqInternalNotice(), pqParseInput2(), pqParseInput3(), pqPrepareAsyncResult(), and pqSaveErrorResult().

142 {
143  PGresult *result;
144 
145  result = (PGresult *) malloc(sizeof(PGresult));
146  if (!result)
147  return NULL;
148 
149  result->ntups = 0;
150  result->numAttributes = 0;
151  result->attDescs = NULL;
152  result->tuples = NULL;
153  result->tupArrSize = 0;
154  result->numParameters = 0;
155  result->paramDescs = NULL;
156  result->resultStatus = status;
157  result->cmdStatus[0] = '\0';
158  result->binary = 0;
159  result->events = NULL;
160  result->nEvents = 0;
161  result->errMsg = NULL;
162  result->errFields = NULL;
163  result->errQuery = NULL;
164  result->null_field[0] = '\0';
165  result->curBlock = NULL;
166  result->curOffset = 0;
167  result->spaceLeft = 0;
168  result->memorySize = sizeof(PGresult);
169 
170  if (conn)
171  {
172  /* copy connection data we might need for operations on PGresult */
173  result->noticeHooks = conn->noticeHooks;
174  result->client_encoding = conn->client_encoding;
175 
176  /* consider copying conn's errorMessage */
177  switch (status)
178  {
179  case PGRES_EMPTY_QUERY:
180  case PGRES_COMMAND_OK:
181  case PGRES_TUPLES_OK:
182  case PGRES_COPY_OUT:
183  case PGRES_COPY_IN:
184  case PGRES_COPY_BOTH:
185  case PGRES_SINGLE_TUPLE:
186  /* non-error cases */
187  break;
188  default:
189  pqSetResultError(result, conn->errorMessage.data);
190  break;
191  }
192 
193  /* copy events last; result must be valid if we need to PQclear */
194  if (conn->nEvents > 0)
195  {
196  result->events = dupEvents(conn->events, conn->nEvents,
197  &result->memorySize);
198  if (!result->events)
199  {
200  PQclear(result);
201  return NULL;
202  }
203  result->nEvents = conn->nEvents;
204  }
205  }
206  else
207  {
208  /* defaults... */
209  result->noticeHooks.noticeRec = NULL;
210  result->noticeHooks.noticeRecArg = NULL;
211  result->noticeHooks.noticeProc = NULL;
212  result->noticeHooks.noticeProcArg = NULL;
213  result->client_encoding = PG_SQL_ASCII;
214  }
215 
216  return result;
217 }
size_t memorySize
Definition: libpq-int.h:212
PGMessageField * errFields
Definition: libpq-int.h:197
PGEvent * events
Definition: libpq-int.h:380
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:150
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
PGNoticeHooks noticeHooks
Definition: libpq-int.h:377
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:511
void pqSetResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:660
void PQclear(PGresult *res)
Definition: fe-exec.c:694
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:381
int client_encoding
Definition: libpq-int.h:434
static PGEvent * dupEvents(PGEvent *events, int count, size_t *memSize)
Definition: fe-exec.c:387
PGEvent * events
Definition: libpq-int.h:187
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:226
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 2289 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().

2290 {
2291  PGnotify *event;
2292 
2293  if (!conn)
2294  return NULL;
2295 
2296  /* Parse any available data to see if we can extract NOTIFY messages. */
2297  parseInput(conn);
2298 
2299  event = conn->notifyHead;
2300  if (event)
2301  {
2302  conn->notifyHead = event->next;
2303  if (!conn->notifyHead)
2304  conn->notifyTail = NULL;
2305  event->next = NULL; /* don't let app see the internal state */
2306  }
2307  return event;
2308 }
PGnotify * notifyHead
Definition: libpq-int.h:397
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1740
struct pgNotify * next
Definition: libpq-fe.h:170
PGnotify * notifyTail
Definition: libpq-int.h:398

◆ PQnparams()

int PQnparams ( const PGresult res)

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

References pg_result::numParameters.

3203 {
3204  if (!res)
3205  return 0;
3206  return res->numParameters;
3207 }
int numParameters
Definition: libpq-int.h:175

◆ PQntuples()

int PQntuples ( const PGresult res)

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

References pg_result::ntups.

Referenced by add_tablespace_footer(), 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_is_install_user(), check_proper_datallowconn(), cluster_all_databases(), collectComments(), collectSecLabels(), 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_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(), libpqGetFile(), libpqProcessFileList(), 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(), pqSetenvPoll(), printCrosstab(), printQuery(), printResultSet(), PrintResultsInCrosstab(), processExtensionTables(), readCommandResponse(), ReadEndOfStreamingResult(), receiveFileChunks(), ReceiveXlogStream(), reindex_all_databases(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_simple_query(), RunIdentifySystem(), set_frozenxids(), show_binary_results(), sql_exec(), StoreQueryTuple(), storeRow(), try_complete_step(), vacuum_all_databases(), vacuum_one_database(), and vacuumlo().

2770 {
2771  if (!res)
2772  return 0;
2773  return res->ntups;
2774 }
int ntups
Definition: libpq-int.h:169

◆ PQoidStatus()

char* PQoidStatus ( const PGresult res)

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

References buf, and pg_result::cmdStatus.

3054 {
3055  /*
3056  * This must be enough to hold the result. Don't laugh, this is better
3057  * than what this function used to do.
3058  */
3059  static char buf[24];
3060 
3061  size_t len;
3062 
3063  if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
3064  return "";
3065 
3066  len = strspn(res->cmdStatus + 7, "0123456789");
3067  if (len > sizeof(buf) - 1)
3068  len = sizeof(buf) - 1;
3069  memcpy(buf, res->cmdStatus + 7, len);
3070  buf[len] = '\0';
3071 
3072  return buf;
3073 }
static char * buf
Definition: pg_test_fsync.c:67
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178

◆ PQoidValue()

Oid PQoidValue ( const PGresult res)

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

References pg_result::cmdStatus, and InvalidOid.

Referenced by ecpg_process_output(), and PrintQueryStatus().

3082 {
3083  char *endptr = NULL;
3084  unsigned long result;
3085 
3086  if (!res ||
3087  strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
3088  res->cmdStatus[7] < '0' ||
3089  res->cmdStatus[7] > '9')
3090  return InvalidOid;
3091 
3092  result = strtoul(res->cmdStatus + 7, &endptr, 10);
3093 
3094  if (!endptr || (*endptr != ' ' && *endptr != '\0'))
3095  return InvalidOid;
3096  else
3097  return (Oid) result;
3098 }
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 3213 of file fe-exec.c.

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

3214 {
3215  if (!check_param_number(res, param_num))
3216  return InvalidOid;
3217  if (res->paramDescs)
3218  return res->paramDescs[param_num].typid;
3219  else
3220  return InvalidOid;
3221 }
static int check_param_number(const PGresult *res, int param_num)
Definition: fe-exec.c:2836
#define InvalidOid
Definition: postgres_ext.h:36
PGresParamDesc * paramDescs
Definition: libpq-int.h:176

◆ PQprepare()

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

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

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

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

1986 {
1987  if (!PQexecStart(conn))
1988  return NULL;
1989  if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
1990  return NULL;
1991  return PQexecFinish(conn);
1992 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2095
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2021
int PQsendPrepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:1330

◆ pqPrepareAsyncResult()

PGresult* pqPrepareAsyncResult ( PGconn conn)

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

References appendPQExpBufferStr(), pg_conn::errorMessage, pg_conn::next_result, PGRES_FATAL_ERROR, PQmakeEmptyPGresult(), PQresultErrorMessage(), resetPQExpBuffer(), and pg_conn::result.

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

827 {
828  PGresult *res;
829 
830  /*
831  * conn->result is the PGresult to return. If it is NULL (which probably
832  * shouldn't happen) we assume there is an appropriate error message in
833  * conn->errorMessage.
834  */
835  res = conn->result;
836  if (!res)
838  else
839  {
840  /*
841  * Make sure PQerrorMessage agrees with result; it could be different
842  * if we have concatenated messages.
843  */
846  PQresultErrorMessage(res));
847  }
848 
849  /*
850  * Replace conn->result with next_result, if any. In the normal case
851  * there isn't a next result and we're just dropping ownership of the
852  * current result. In single-row mode this restores the situation to what
853  * it was before we created the current single-row result.
854  */
855  conn->result = conn->next_result;
856  conn->next_result = NULL;
857 
858  return res;
859 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGresult * result
Definition: libpq-int.h:462
PGresult * next_result
Definition: libpq-int.h:463
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:141
PQExpBufferData errorMessage
Definition: libpq-int.h:511
char * PQresultErrorMessage(const PGresult *res)
Definition: fe-exec.c:2708
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148

◆ PQputCopyData()

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

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

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

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

2318 {
2319  if (!conn)
2320  return -1;
2321  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2322  conn->asyncStatus != PGASYNC_COPY_BOTH)
2323  {
2325  libpq_gettext("no COPY in progress\n"));
2326  return -1;
2327  }
2328 
2329  /*
2330  * Process any NOTICE or NOTIFY messages that might be pending in the
2331  * input buffer. Since the server might generate many notices during the
2332  * COPY, we want to clean those out reasonably promptly to prevent
2333  * indefinite expansion of the input buffer. (Note: the actual read of
2334  * input data into the input buffer happens down inside pqSendSome, but
2335  * it's not authorized to get rid of the data again.)
2336  */
2337  parseInput(conn);
2338 
2339  if (nbytes > 0)
2340  {
2341  /*
2342  * Try to flush any previously sent data in preference to growing the
2343  * output buffer. If we can't enlarge the buffer enough to hold the
2344  * data, return 0 in the nonblock case, else hard error. (For
2345  * simplicity, always assume 5 bytes of overhead even in protocol 2.0
2346  * case.)
2347  */
2348  if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2349  {
2350  if (pqFlush(conn) < 0)
2351  return -1;
2352  if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2353  conn))
2354  return pqIsnonblocking(conn) ? 0 : -1;
2355  }
2356  /* Send the data (too simple to delegate to fe-protocol files) */
2357  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2358  {
2359  if (pqPutMsgStart('d', false, conn) < 0 ||
2360  pqPutnchar(buffer, nbytes, conn) < 0 ||
2361  pqPutMsgEnd(conn) < 0)
2362  return -1;
2363  }
2364  else
2365  {
2366  if (pqPutMsgStart(0, false, conn) < 0 ||
2367  pqPutnchar(buffer, nbytes, conn) < 0 ||
2368  pqPutMsgEnd(conn) < 0)
2369  return -1;
2370  }
2371  }
2372  return 1;
2373 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:997
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:343
#define pqIsnonblocking(conn)
Definition: libpq-int.h:784
int outCount
Definition: libpq-int.h:450
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:518
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:386
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1740
PQExpBufferData errorMessage
Definition: libpq-int.h:511
int outBufSize
Definition: libpq-int.h:449
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:245
ProtocolVersion pversion
Definition: libpq-int.h:411
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:586
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQputCopyEnd()

int PQputCopyEnd ( PGconn conn,
const char *  errormsg 
)

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

References pg_conn::asyncStatus, pg_conn::errorMessage, libpq_gettext, PG_PROTOCOL_MAJOR, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGQUERY_SIMPLE, pqFlush(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), pqPuts(), printfPQExpBuffer(), pg_conn::pversion, pg_conn::queryclass, and resetPQExpBuffer().

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

2385 {
2386  if (!conn)
2387  return -1;
2388  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2389  conn->asyncStatus != PGASYNC_COPY_BOTH)
2390  {
2392  libpq_gettext("no COPY in progress\n"));
2393  return -1;
2394  }
2395 
2396  /*
2397  * Send the COPY END indicator. This is simple enough that we don't
2398  * bother delegating it to the fe-protocol files.
2399  */
2400  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2401  {
2402  if (errormsg)
2403  {
2404  /* Send COPY FAIL */
2405  if (pqPutMsgStart('f', false, conn) < 0 ||
2406  pqPuts(errormsg, conn) < 0 ||
2407  pqPutMsgEnd(conn) < 0)
2408  return -1;
2409  }
2410  else
2411  {
2412  /* Send COPY DONE */
2413  if (pqPutMsgStart('c', false, conn) < 0 ||
2414  pqPutMsgEnd(conn) < 0)
2415  return -1;
2416  }
2417 
2418  /*
2419  * If we sent the COPY command in extended-query mode, we must issue a
2420  * Sync as well.
2421  */
2422  if (conn->queryclass != PGQUERY_SIMPLE)
2423  {
2424  if (pqPutMsgStart('S', false, conn) < 0 ||
2425  pqPutMsgEnd(conn) < 0)
2426  return -1;
2427  }
2428  }
2429  else
2430  {
2431  if (errormsg)
2432  {
2433  /* Oops, no way to do this in 2.0 */
2435  libpq_gettext("function requires at least protocol version 3.0\n"));
2436  return -1;
2437  }
2438  else
2439  {
2440  /* Send old-style end-of-data marker */
2441  if (pqPutMsgStart(0, false, conn) < 0 ||
2442  pqPutnchar("\\.\n", 3, conn) < 0 ||
2443  pqPutMsgEnd(conn) < 0)
2444  return -1;
2445  }
2446  }
2447 
2448  /* Return to active duty */
2449  if (conn->asyncStatus == PGASYNC_COPY_BOTH)
2450  conn->asyncStatus = PGASYNC_COPY_OUT;
2451  else
2452  conn->asyncStatus = PGASYNC_BUSY;
2454 
2455  /* Try to flush data */
2456  if (pqFlush(conn) < 0)
2457  return -1;
2458 
2459  return 1;
2460 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:997
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
PGQueryClass queryclass
Definition: libpq-int.h:388
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:518
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:386
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:178
PQExpBufferData errorMessage
Definition: libpq-int.h:511
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:245
ProtocolVersion pversion
Definition: libpq-int.h:411
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:586
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQputline()

int PQputline ( PGconn conn,
const char *  s 
)

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

References PQputnbytes().

Referenced by initGenerateDataClientSide().

2586 {
2587  return PQputnbytes(conn, s, strlen(s));
2588 }
int PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2595

◆ PQputnbytes()

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

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

References PQputCopyData().

Referenced by PQputline().

2596 {
2597  if (PQputCopyData(conn, buffer, nbytes) > 0)
2598  return 0;
2599  else
2600  return EOF;
2601 }
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2317

◆ PQresStatus()

char* PQresStatus ( ExecStatusType  status)

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

References libpq_gettext, pgresStatus, and status().

Referenced by try_complete_step().

2701 {
2702  if ((unsigned int) status >= sizeof pgresStatus / sizeof pgresStatus[0])
2703  return libpq_gettext("invalid ExecStatusType code");
2704  return pgresStatus[status];
2705 }
char *const pgresStatus[]
Definition: fe-exec.c:32
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:226
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQresultAlloc()

void* PQresultAlloc ( PGresult res,
size_t  nBytes 
)

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

References pqResultAlloc().

Referenced by PQsetResultAttrs().

519 {
520  return pqResultAlloc(res, nBytes, true);
521 }
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:534

◆ pqResultAlloc()

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

Definition at line 534 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().

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

◆ PQresultErrorField()

char* PQresultErrorField ( const PGresult res,
int  fieldcode 
)

Definition at line 2754 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(), minimal_error_message(), pgfdw_report_error(), pgpassfileWarning(), pqBuildErrorMessage3(), PQconnectPoll(), processQueryResult(), SetResultVariables(), and try_complete_step().

2755 {
2756  PGMessageField *pfield;
2757 
2758  if (!res)
2759  return NULL;
2760  for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
2761  {
2762  if (pfield->code == fieldcode)
2763  return pfield->contents;
2764  }
2765  return NULL;
2766 }
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 634 of file fe-exec.c.

References pg_result::memorySize.

635 {
636  if (!res)
637  return 0;
638  return res->memorySize;
639 }
size_t memorySize
Definition: libpq-int.h:212

◆ PQresultStatus()

ExecStatusType PQresultStatus ( const PGresult res)

Definition at line 2692 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(), create_cursor(), CreateReplicationSlot(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_record_internal(), 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(), finish_foreign_modify(), get_create_object_cmd(), get_remote_estimate(), GetConnection(), GetTableInfo(), handleCopyIn(), handleCopyOut(), HandleEndOfCopyStream(), initGenerateDataClientSide(), libpq_executeFileMap(), libpqConnect(), libpqGetFile(), libpqProcessFileList(), 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(), pqSetenvPoll(), prepare_foreign_modify(), PrintQueryResults(), PrintResultsInCrosstab(), processQueryResult(), ProcessResult(), PSQLexecWatch(), readCommandResponse(), ReceiveAndUnpackTarFile(), receiveFileChunks(), ReceiveTarFile(), ReceiveXlogStream(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_permutation(), run_simple_command(), run_simple_query(), RunIdentifySystem(), sendCommand(), SendQuery(), sql_conn(), sql_exec(), storeQueryResult(), StreamLogicalLog(), try_complete_step(), tryExecuteStatement(), and vacuumlo().

2693 {
2694  if (!res)
2695  return PGRES_FATAL_ERROR;
2696  return res->resultStatus;
2697 }
ExecStatusType resultStatus
Definition: libpq-int.h:177

◆ pqResultStrdup()

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

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

References pqResultAlloc().

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

647 {
648  char *space = (char *) pqResultAlloc(res, strlen(str) + 1, false);
649 
650  if (space)
651  strcpy(space, str);
652  return space;
653 }
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:534

◆ PQresultVerboseErrorMessage()

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

Definition at line 2716 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().

2719 {
2720  PQExpBufferData workBuf;
2721 
2722  /*
2723  * Because the caller is expected to free the result string, we must
2724  * strdup any constant result. We use plain strdup and document that
2725  * callers should expect NULL if out-of-memory.
2726  */
2727  if (!res ||
2728  (res->resultStatus != PGRES_FATAL_ERROR &&
2730  return strdup(libpq_gettext("PGresult is not an error result\n"));
2731 
2732  initPQExpBuffer(&workBuf);
2733 
2734  /*
2735  * Currently, we pass this off to fe-protocol3.c in all cases; it will
2736  * behave reasonably sanely with an error reported by fe-protocol2.c as
2737  * well. If necessary, we could record the protocol version in PGresults
2738  * so as to be able to invoke a version-specific message formatter, but
2739  * for now there's no need.
2740  */
2741  pqBuildErrorMessage3(&workBuf, res, verbosity, show_context);
2742 
2743  /* If insufficient memory to format the message, fail cleanly */
2744  if (PQExpBufferDataBroken(workBuf))
2745  {
2746  termPQExpBuffer(&workBuf);
2747  return strdup(libpq_gettext("out of memory\n"));
2748  }
2749 
2750  return workBuf.data;
2751 }
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)
Definition: fe-protocol3.c:987
ExecStatusType resultStatus
Definition: libpq-int.h:177
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ pqRowProcessor()

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

Definition at line 1132 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, 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().

1133 {
1134  PGresult *res = conn->result;
1135  int nfields = res->numAttributes;
1136  const PGdataValue *columns = conn->rowBuf;
1137  PGresAttValue *tup;
1138  int i;
1139 
1140  /*
1141  * In single-row mode, make a new PGresult that will hold just this one
1142  * row; the original conn->result is left unchanged so that it can be used
1143  * again as the template for future rows.
1144  */
1145  if (conn->singleRowMode)
1146  {
1147  /* Copy everything that should be in the result at this point */
1148  res = PQcopyResult(res,
1151  if (!res)
1152  return 0;
1153  }
1154 
1155  /*
1156  * Basically we just allocate space in the PGresult for each field and
1157  * copy the data over.
1158  *
1159  * Note: on malloc failure, we return 0 leaving *errmsgp still NULL, which
1160  * caller will take to mean "out of memory". This is preferable to trying
1161  * to set up such a message here, because evidently there's not enough
1162  * memory for gettext() to do anything.
1163  */
1164  tup = (PGresAttValue *)
1165  pqResultAlloc(res, nfields * sizeof(PGresAttValue), true);
1166  if (tup == NULL)
1167  goto fail;
1168 
1169  for (i = 0; i < nfields; i++)
1170  {
1171  int clen = columns[i].len;
1172 
1173  if (clen < 0)
1174  {
1175  /* null field */
1176  tup[i].len = NULL_LEN;
1177  tup[i].value = res->null_field;
1178  }
1179  else
1180  {
1181  bool isbinary = (res->attDescs[i].format != 0);
1182  char *val;
1183 
1184  val = (char *) pqResultAlloc(res, clen + 1, isbinary);
1185  if (val == NULL)
1186  goto fail;
1187 
1188  /* copy and zero-terminate the data (even if it's binary) */
1189  memcpy(val, columns[i].value, clen);
1190  val[clen] = '\0';
1191 
1192  tup[i].len = clen;
1193  tup[i].value = val;
1194  }
1195  }
1196 
1197  /* And add the tuple to the PGresult's tuple array */
1198  if (!pqAddTuple(res, tup, errmsgp))
1199  goto fail;
1200 
1201  /*
1202  * Success. In single-row mode, make the result available to the client
1203  * immediately.
1204  */
1205  if (conn->singleRowMode)
1206  {
1207  /* Change result status to special single-row value */
1209  /* Stash old result for re-use later */
1210  conn->next_result = conn->result;
1211  conn->result = res;
1212  /* And mark the result ready to return */
1213  conn->asyncStatus = PGASYNC_READY;
1214  }
1215 
1216  return 1;
1217 
1218 fail:
1219  /* release locally allocated PGresult, if we made one */
1220  if (res != conn->result)
1221  PQclear(res);
1222  return 0;
1223 }
bool singleRowMode
Definition: libpq-int.h:394
PGresult * PQcopyResult(const PGresult *src, int flags)
Definition: fe-exec.c:294
static struct @145 value
#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:462
PGresult * next_result
Definition: libpq-int.h:463
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:386
#define PG_COPYRES_EVENTS
Definition: libpq-fe.h:36
static bool pqAddTuple(PGresult *res, PGresAttValue *tup, const char **errmsgp)
Definition: fe-exec.c:926
#define PG_COPYRES_NOTICEHOOKS
Definition: libpq-fe.h:37
PGdataValue * rowBuf
Definition: libpq-int.h:458
int numAttributes
Definition: libpq-int.h:170
#define PG_COPYRES_ATTRS
Definition: libpq-fe.h:34
void PQclear(PGresult *res)
Definition: fe-exec.c:694
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:534
int i
char * value
Definition: libpq-int.h:138
ExecStatusType resultStatus
Definition: libpq-int.h:177
long val
Definition: informix.c:684

◆ pqSaveErrorResult()

void pqSaveErrorResult ( PGconn conn)

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

References PQExpBufferData::data, pg_result::errMsg, pg_conn::errorMessage, PGRES_FATAL_ERROR, pqCatenateResultError(), pqClearAsyncResult(), PQmakeEmptyPGresult(), pg_conn::result, and pg_result::resultStatus.

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

773 {
774  /*
775  * If no old async result, just let PQmakeEmptyPGresult make one. Likewise
776  * if old result is not an error message.
777  */
778  if (conn->result == NULL ||
780  conn->result->errMsg == NULL)
781  {
782  pqClearAsyncResult(conn);
784  }
785  else
786  {
787  /* Else, concatenate error message to existing async result. */
789  }
790 }
char * errMsg
Definition: libpq-int.h:196
PGresult * result
Definition: libpq-int.h:462
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:141
PQExpBufferData errorMessage
Definition: libpq-int.h:511
void pqCatenateResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:675
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:749
ExecStatusType resultStatus
Definition: libpq-int.h:177

◆ pqSaveMessageField()

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

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

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

Referenced by pqGetErrorNotice2(), pqGetErrorNotice3(), and pqInternalNotice().

994 {
995  PGMessageField *pfield;
996 
997  pfield = (PGMessageField *)
998  pqResultAlloc(res,
999  offsetof(PGMessageField, contents) +
1000  strlen(value) + 1,
1001  true);
1002  if (!pfield)
1003  return; /* out of memory? */
1004  pfield->code = code;
1005  strcpy(pfield->contents, value);
1006  pfield->next = res->errFields;
1007  res->errFields = pfield;
1008 }
PGMessageField * errFields
Definition: libpq-int.h:197
static struct @145 value
struct pgMessageField * next
Definition: libpq-int.h:144
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:534
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:146
#define offsetof(type, field)
Definition: c.h:656

◆ pqSaveParameterStatus()

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

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

References pg_conn::client_encoding, fprintf, free, malloc, pgParameterStatus::name, pgParameterStatus::next, pg_conn::Pfdebug, 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(), PQsetClientEncoding(), and pqSetenvPoll().

1015 {
1016  pgParameterStatus *pstatus;
1017  pgParameterStatus *prev;
1018 
1019  if (conn->Pfdebug)
1020  fprintf(conn->Pfdebug, "pqSaveParameterStatus: '%s' = '%s'\n",
1021  name, value);
1022 
1023  /*
1024  * Forget any old information about the parameter
1025  */
1026  for (pstatus = conn->pstatus, prev = NULL;
1027  pstatus != NULL;
1028  prev = pstatus, pstatus = pstatus->next)
1029  {
1030  if (strcmp(pstatus->name, name) == 0)
1031  {
1032  if (prev)
1033  prev->next = pstatus->next;
1034  else
1035  conn->pstatus = pstatus->next;
1036  free(pstatus); /* frees name and value strings too */
1037  break;
1038  }
1039  }
1040 
1041  /*
1042  * Store new info as a single malloc block
1043  */
1044  pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
1045  strlen(name) + strlen(value) + 2);
1046  if (pstatus)
1047  {
1048  char *ptr;
1049 
1050  ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
1051  pstatus->name = ptr;
1052  strcpy(ptr, name);
1053  ptr += strlen(name) + 1;
1054  pstatus->value = ptr;
1055  strcpy(ptr, value);
1056  pstatus->next = conn->pstatus;
1057  conn->pstatus = pstatus;
1058  }
1059 
1060  /*
1061  * Special hacks: remember client_encoding and
1062  * standard_conforming_strings, and convert server version to a numeric
1063  * form. We keep the first two of these in static variables as well, so
1064  * that PQescapeString and PQescapeBytea can behave somewhat sanely (at
1065  * least in single-connection-using programs).
1066  */
1067  if (strcmp(name, "client_encoding") == 0)
1068  {
1070  /* if we don't recognize the encoding name, fall back to SQL_ASCII */
1071  if (conn->client_encoding < 0)
1072  conn->client_encoding = PG_SQL_ASCII;
1074  }
1075  else if (strcmp(name, "standard_conforming_strings") == 0)
1076  {
1077  conn->std_strings = (strcmp(value, "on") == 0);
1079  }
1080  else if (strcmp(name, "server_version") == 0)
1081  {
1082  int cnt;
1083  int vmaj,
1084  vmin,
1085  vrev;
1086 
1087  cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
1088 
1089  if (cnt == 3)
1090  {
1091  /* old style, e.g. 9.6.1 */
1092  conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
1093  }
1094  else if (cnt == 2)
1095  {
1096  if (vmaj >= 10)
1097  {
1098  /* new style, e.g. 10.1 */
1099  conn->sversion = 100 * 100 * vmaj + vmin;
1100  }
1101  else
1102  {
1103  /* old style without minor version, e.g. 9.6devel */
1104  conn->sversion = (100 * vmaj + vmin) * 100;
1105  }
1106  }
1107  else if (cnt == 1)
1108  {
1109  /* new style without minor version, e.g. 10devel */
1110  conn->sversion = 100 * 100 * vmaj;
1111  }
1112  else
1113  conn->sversion = 0; /* unknown */
1114  }
1115 }
static bool static_std_strings
Definition: fe-exec.c:50
int pg_char_to_encoding(const char *name)
Definition: encnames.c:551
static struct @145 value
#define fprintf
Definition: port.h:196
FILE * Pfdebug
Definition: libpq-int.h:374
#define malloc(a)
Definition: header.h:50
int sversion
Definition: libpq-int.h:412
struct pgParameterStatus pgParameterStatus
static int static_client_encoding
Definition: fe-exec.c:49
pgParameterStatus * pstatus
Definition: libpq-int.h:433
bool std_strings
Definition: libpq-int.h:435
#define free(a)
Definition: header.h:65
struct pgParameterStatus * next
Definition: libpq-int.h:261
const char * name
Definition: encode.c:521
int client_encoding
Definition: libpq-int.h:434

◆ pqSaveWriteError()

static void pqSaveWriteError ( PGconn conn)
static

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

References libpq_gettext, pqCatenateResultError(), pqSaveErrorResult(), pg_conn::result, and pg_conn::write_err_msg.

Referenced by PQgetResult().

799 {
800  /*
801  * Ensure conn->result is an error result, and add anything in
802  * conn->errorMessage to it.
803  */
804  pqSaveErrorResult(conn);
805 
806  /*
807  * Now append write_err_msg to that. If it's null because of previous
808  * strdup failure, do what we can. (It's likely our machinations here are
809  * all getting OOM failures as well, but ...)
810  */
811  if (conn->write_err_msg && conn->write_err_msg[0] != '\0')
813  else
815  libpq_gettext("write to server failed\n"));
816 }
char * write_err_msg
Definition: libpq-int.h:418
PGresult * result
Definition: libpq-int.h:462
void pqCatenateResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:675
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:772
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQsendDescribe()

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

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

References pg_conn::asyncStatus, pg_conn::errorMessage, free, pg_conn::last_query, libpq_gettext, PG_PROTOCOL_MAJOR, PGASYNC_BUSY, PGQUERY_DESCRIBE, pqFlush(), pqPutc(), pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), PQsendQueryStart(), printfPQExpBuffer(), pg_conn::pversion, and pg_conn::queryclass.

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

2221 {
2222  /* Treat null desc_target as empty string */
2223  if (!desc_target)
2224  desc_target = "";
2225 
2226  if (!PQsendQueryStart(conn))
2227  return 0;
2228 
2229  /* This isn't gonna work on a 2.0 server */
2230  if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2231  {
2233  libpq_gettext("function requires at least protocol version 3.0\n"));
2234  return 0;
2235  }
2236 
2237  /* construct the Describe message */
2238  if (pqPutMsgStart('D', false, conn) < 0 ||
2239  pqPutc(desc_type, conn) < 0 ||
2240  pqPuts(desc_target, conn) < 0 ||
2241  pqPutMsgEnd(conn) < 0)
2242  goto sendFailed;
2243 
2244  /* construct the Sync message */
2245  if (pqPutMsgStart('S', false, conn) < 0 ||
2246  pqPutMsgEnd(conn) < 0)
2247  goto sendFailed;
2248 
2249  /* remember we are doing a Describe */
2250  conn->queryclass = PGQUERY_DESCRIBE;
2251 
2252  /* reset last_query string (not relevant now) */
2253  if (conn->last_query)
2254  {
2255  free(conn->last_query);
2256  conn->last_query = NULL;
2257  }
2258 
2259  /*
2260  * Give the data a push. In nonblock mode, don't complain if we're unable
2261  * to send it all; PQgetResult() will do any additional flushing needed.
2262  */
2263  if (pqFlush(conn) < 0)
2264  goto sendFailed;
2265 
2266  /* OK, it's launched! */
2267  conn->asyncStatus = PGASYNC_BUSY;
2268  return 1;
2269 
2270 sendFailed:
2271  /* error message should be set up already */
2272  return 0;
2273 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:997
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
PGQueryClass queryclass
Definition: libpq-int.h:388
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:518
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:386
int pqPutc(char c, PGconn *conn)
Definition: fe-misc.c:111
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:178
char * last_query
Definition: libpq-int.h:389
static bool PQsendQueryStart(PGconn *conn)
Definition: fe-exec.c:1467
PQExpBufferData errorMessage
Definition: libpq-int.h:511
#define free(a)
Definition: header.h:65
ProtocolVersion pversion
Definition: libpq-int.h:411
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:586
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQsendDescribePortal()

int PQsendDescribePortal ( PGconn conn,
const char *  portal 
)

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

References PQsendDescribe().

2206 {
2207  return PQsendDescribe(conn, 'P', portal);
2208 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2220

◆ PQsendDescribePrepared()

int PQsendDescribePrepared ( PGconn conn,
const char *  stmt 
)

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

References PQsendDescribe().

2193 {
2194  return PQsendDescribe(conn, 'S', stmt);
2195 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2220

◆ PQsendPrepare()

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

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

References pg_conn::asyncStatus, pg_conn::errorMessage, free, i, pg_conn::last_query, libpq_gettext, PG_PROTOCOL_MAJOR, PGASYNC_BUSY, PGQUERY_PREPARE, pqFlush(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), PQsendQueryStart(), printfPQExpBuffer(), pg_conn::pversion, and pg_conn::queryclass.

Referenced by PQprepare(), and prepare_foreign_modify().

1333 {
1334  if (!PQsendQueryStart(conn))
1335  return 0;
1336 
1337  /* check the arguments */
1338  if (!stmtName)
1339  {
1341  libpq_gettext("statement name is a null pointer\n"));
1342  return 0;
1343  }
1344  if (!query)
1345  {
1347  libpq_gettext("command string is a null pointer\n"));
1348  return 0;
1349  }
1350  if (nParams < 0 || nParams > 65535)
1351  {
1353  libpq_gettext("number of parameters must be between 0 and 65535\n"));
1354  return 0;
1355  }
1356 
1357  /* This isn't gonna work on a 2.0 server */
1358  if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1359  {
1361  libpq_gettext("function requires at least protocol version 3.0\n"));
1362  return 0;
1363  }
1364 
1365  /* construct the Parse message */
1366  if (pqPutMsgStart('P', false, conn) < 0 ||
1367  pqPuts(stmtName, conn) < 0 ||
1368  pqPuts(query, conn) < 0)
1369  goto sendFailed;
1370 
1371  if (nParams > 0 && paramTypes)
1372  {
1373  int i;
1374 
1375  if (pqPutInt(nParams, 2, conn) < 0)
1376  goto sendFailed;
1377  for (i = 0; i < nParams; i++)
1378  {
1379  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1380  goto sendFailed;
1381  }
1382  }
1383  else
1384  {
1385  if (pqPutInt(0, 2, conn) < 0)
1386  goto sendFailed;
1387  }
1388  if (pqPutMsgEnd(conn) < 0)
1389  goto sendFailed;
1390 
1391  /* construct the Sync message */
1392  if (pqPutMsgStart('S', false, conn) < 0 ||
1393  pqPutMsgEnd(conn) < 0)
1394  goto sendFailed;
1395 
1396  /* remember we are doing just a Parse */
1397  conn->queryclass = PGQUERY_PREPARE;
1398 
1399  /* and remember the query text too, if possible */
1400  /* if insufficient memory, last_query just winds up NULL */
1401  if (conn->last_query)
1402  free(conn->last_query);
1403  conn->last_query = strdup(query);
1404 
1405  /*
1406  * Give the data a push. In nonblock mode, don't complain if we're unable
1407  * to send it all; PQgetResult() will do any additional flushing needed.
1408  */
1409  if (pqFlush(conn) < 0)
1410  goto sendFailed;
1411 
1412  /* OK, it's launched! */
1413  conn->asyncStatus = PGASYNC_BUSY;
1414  return 1;
1415 
1416 sendFailed:
1417  /* error message should be set up already */
1418  return 0;
1419 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:997
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
PGQueryClass queryclass
Definition: libpq-int.h:388
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:518
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:306
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:386
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:178
char * last_query
Definition: libpq-int.h:389
static bool PQsendQueryStart(PGconn *conn)
Definition: fe-exec.c:1467
PQExpBufferData errorMessage
Definition: libpq-int.h:511
#define free(a)
Definition: header.h:65
ProtocolVersion pversion
Definition: libpq-int.h:411
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:586
int i
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQsendQuery()

int PQsendQuery ( PGconn conn,
const char *  query 
)

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

References pg_conn::asyncStatus, pg_conn::errorMessage, free, pg_conn::last_query, libpq_gettext, PGASYNC_BUSY, PGQUERY_SIMPLE, pqFlush(), pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), PQsendQueryStart(), printfPQExpBuffer(), and pg_conn::queryclass.

Referenced by BaseBackup(), dblink_send_query(), do_sql_command(), libpqrcv_PQexec(), pgfdw_exec_cleanup_query(), pgfdw_exec_query(), PQconnectPoll(), PQexec(), pqSetenvPoll(), run_permutation(), run_reindex_command(), run_vacuum_command(), sendCommand(), and storeQueryResult().

1235 {
1236  if (!PQsendQueryStart(conn))
1237  return 0;
1238 
1239  /* check the argument */
1240  if (!query)
1241  {
1243  libpq_gettext("command string is a null pointer\n"));
1244  return 0;
1245  }
1246 
1247  /* construct the outgoing Query message */
1248  if (pqPutMsgStart('Q', false, conn) < 0 ||
1249  pqPuts(query, conn) < 0 ||
1250  pqPutMsgEnd(conn) < 0)
1251  {
1252  /* error message should be set up already */
1253  return 0;
1254  }
1255 
1256  /* remember we are using simple query protocol */
1257  conn->queryclass = PGQUERY_SIMPLE;
1258 
1259  /* and remember the query text too, if possible */
1260  /* if insufficient memory, last_query just winds up NULL */
1261  if (conn->last_query)
1262  free(conn->last_query);
1263  conn->last_query = strdup(query);
1264 
1265  /*
1266  * Give the data a push. In nonblock mode, don't complain if we're unable
1267  * to send it all; PQgetResult() will do any additional flushing needed.
1268  */
1269  if (pqFlush(conn) < 0)
1270  {
1271  /* error message should be set up already */
1272  return 0;
1273  }
1274 
1275  /* OK, it's launched! */
1276  conn->asyncStatus = PGASYNC_BUSY;
1277  return 1;
1278 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:997
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
PGQueryClass queryclass
Definition: libpq-int.h:388
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:518
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:386
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:178
char * last_query
Definition: libpq-int.h:389
static bool PQsendQueryStart(PGconn *conn)
Definition: fe-exec.c:1467
PQExpBufferData errorMessage
Definition: libpq-int.h:511
#define free(a)
Definition: header.h:65
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:586
#define libpq_gettext(x)
Definition: libpq-int.h:790

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

References pg_conn::asyncStatus, pg_conn::errorMessage, free, i, pg_conn::last_query, libpq_gettext, PG_PROTOCOL_MAJOR, PGASYNC_BUSY, PGQUERY_EXTENDED, pqFlush(), pqPutc(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), pqPuts(), printfPQExpBuffer(), pg_conn::pversion, and pg_conn::queryclass.

Referenced by PQsendQueryParams(), and PQsendQueryPrepared().

1517 {
1518  int i;
1519 
1520  /* This isn't gonna work on a 2.0 server */
1521  if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1522  {
1524  libpq_gettext("function requires at least protocol version 3.0\n"));
1525  return 0;
1526  }
1527 
1528  /*
1529  * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync,
1530  * using specified statement name and the unnamed portal.
1531  */
1532 
1533  if (command)
1534  {
1535  /* construct the Parse message */
1536  if (pqPutMsgStart('P', false, conn) < 0 ||
1537  pqPuts(stmtName, conn) < 0 ||
1538  pqPuts(command, conn) < 0)
1539  goto sendFailed;
1540  if (nParams > 0 && paramTypes)
1541  {
1542  if (pqPutInt(nParams, 2, conn) < 0)
1543  goto sendFailed;
1544  for (i = 0; i < nParams; i++)
1545  {
1546  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1547  goto sendFailed;
1548  }
1549  }
1550  else
1551  {
1552  if (pqPutInt(0, 2, conn) < 0)
1553  goto sendFailed;
1554  }
1555  if (pqPutMsgEnd(conn) < 0)
1556  goto sendFailed;
1557  }
1558 
1559  /* Construct the Bind message */
1560  if (pqPutMsgStart('B', false, conn) < 0 ||
1561  pqPuts("", conn) < 0 ||
1562  pqPuts(stmtName, conn) < 0)
1563  goto sendFailed;
1564 
1565  /* Send parameter formats */
1566  if (nParams > 0 && paramFormats)
1567  {
1568  if (pqPutInt(nParams, 2, conn) < 0)
1569  goto sendFailed;
1570  for (i = 0; i < nParams; i++)
1571  {
1572  if (pqPutInt(paramFormats[i], 2, conn) < 0)
1573  goto sendFailed;
1574  }
1575  }
1576  else
1577  {
1578  if (pqPutInt(0, 2, conn) < 0)
1579  goto sendFailed;
1580  }
1581 
1582  if (pqPutInt(nParams, 2, conn) < 0)
1583  goto sendFailed;
1584 
1585  /* Send parameters */
1586  for (i = 0; i < nParams; i++)
1587  {
1588  if (paramValues && paramValues[i])
1589  {
1590  int nbytes;
1591 
1592  if (paramFormats && paramFormats[i] != 0)
1593  {
1594  /* binary parameter */
1595  if (paramLengths)
1596  nbytes = paramLengths[i];
1597  else
1598  {
1600  libpq_gettext("length must be given for binary parameter\n"));
1601  goto sendFailed;
1602  }
1603  }
1604  else
1605  {
1606  /* text parameter, do not use paramLengths */
1607  nbytes = strlen(paramValues[i]);
1608  }
1609  if (pqPutInt(nbytes, 4, conn) < 0 ||
1610  pqPutnchar(paramValues[i], nbytes, conn) < 0)
1611  goto sendFailed;
1612  }
1613  else
1614  {
1615  /* take the param as NULL */
1616  if (pqPutInt(-1, 4, conn) < 0)
1617  goto sendFailed;
1618  }
1619  }
1620  if (pqPutInt(1, 2, conn) < 0 ||
1621  pqPutInt(resultFormat, 2, conn))
1622  goto sendFailed;
1623  if (pqPutMsgEnd(conn) < 0)
1624  goto sendFailed;
1625 
1626  /* construct the Describe Portal message */
1627  if (pqPutMsgStart('D', false, conn) < 0 ||
1628  pqPutc('P', conn) < 0 ||
1629  pqPuts("", conn) < 0 ||
1630  pqPutMsgEnd(conn) < 0)
1631  goto sendFailed;
1632 
1633  /* construct the Execute message */
1634  if (pqPutMsgStart('E', false, conn) < 0 ||
1635  pqPuts("", conn) < 0 ||
1636  pqPutInt(0, 4, conn) < 0 ||
1637  pqPutMsgEnd(conn) < 0)
1638  goto sendFailed;
1639 
1640  /* construct the Sync message */
1641  if (pqPutMsgStart('S', false, conn) < 0 ||
1642  pqPutMsgEnd(conn) < 0)
1643  goto sendFailed;
1644 
1645  /* remember we are using extended query protocol */
1646  conn->queryclass = PGQUERY_EXTENDED;
1647 
1648  /* and remember the query text too, if possible */
1649  /* if insufficient memory, last_query just winds up NULL */
1650  if (conn->last_query)
1651  free(conn->last_query);
1652  if (command)
1653  conn->last_query = strdup(command);
1654  else
1655  conn->last_query = NULL;
1656 
1657  /*
1658  * Give the data a push. In nonblock mode, don't complain if we're unable
1659  * to send it all; PQgetResult() will do any additional flushing needed.
1660  */
1661  if (pqFlush(conn) < 0)
1662  goto sendFailed;
1663 
1664  /* OK, it's launched! */
1665  conn->asyncStatus = PGASYNC_BUSY;
1666  return 1;
1667 
1668 sendFailed:
1669  /* error message should be set up already */
1670  return 0;
1671 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:997
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
PGQueryClass queryclass
Definition: libpq-int.h:388
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:518
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:306
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:386
int pqPutc(char c, PGconn *conn)
Definition: fe-misc.c:111
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:178
char * last_query
Definition: libpq-int.h:389
PQExpBufferData errorMessage
Definition: libpq-int.h:511
#define free(a)
Definition: header.h:65
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:245
ProtocolVersion pversion
Definition: libpq-int.h:411
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:586
int i
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQsendQueryParams()

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

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

References pg_conn::errorMessage, libpq_gettext, PQsendQueryGuts(), PQsendQueryStart(), and printfPQExpBuffer().

Referenced by create_cursor(), execute_dml_stmt(), PQexecParams(), receiveFileChunks(), and sendCommand().

1293 {
1294  if (!PQsendQueryStart(conn))
1295  return 0;
1296 
1297  /* check the arguments */
1298  if (!command)
1299  {
1301  libpq_gettext("command string is a null pointer\n"));
1302  return 0;
1303  }
1304  if (nParams < 0 || nParams > 65535)
1305  {
1307  libpq_gettext("number of parameters must be between 0 and 65535\n"));
1308  return 0;
1309  }
1310 
1311  return PQsendQueryGuts(conn,
1312  command,
1313  "", /* use unnamed statement */
1314  nParams,
1315  paramTypes,
1316  paramValues,
1317  paramLengths,
1318  paramFormats,
1319  resultFormat);
1320 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
static int PQsendQueryGuts(PGconn *conn, const char *command, const char *stmtName, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:1508
static bool PQsendQueryStart(PGconn *conn)
Definition: fe-exec.c:1467
PQExpBufferData errorMessage
Definition: libpq-int.h:511
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQsendQueryPrepared()

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

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

References pg_conn::errorMessage, libpq_gettext, PQsendQueryGuts(), PQsendQueryStart(), and printfPQExpBuffer().

Referenced by execute_foreign_modify(), PQexecPrepared(), and sendCommand().

1434 {
1435  if (!PQsendQueryStart(conn))
1436  return 0;
1437 
1438  /* check the arguments */
1439  if (!stmtName)
1440  {
1442  libpq_gettext("statement name is a null pointer\n"));
1443  return 0;
1444  }
1445  if (nParams < 0 || nParams > 65535)
1446  {
1448  libpq_gettext("number of parameters must be between 0 and 65535\n"));
1449  return 0;
1450  }
1451 
1452  return PQsendQueryGuts(conn,
1453  NULL, /* no command to parse */
1454  stmtName,
1455  nParams,
1456  NULL, /* no param types */
1457  paramValues,
1458  paramLengths,
1459  paramFormats,
1460  resultFormat);
1461 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
static int PQsendQueryGuts(PGconn *conn, const char *command, const char *stmtName, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:1508
static bool PQsendQueryStart(PGconn *conn)
Definition: fe-exec.c:1467
PQExpBufferData errorMessage
Definition: libpq-int.h:511
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQsendQueryStart()

static bool PQsendQueryStart ( PGconn conn)
static

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

References pg_conn::asyncStatus, CONNECTION_OK, pg_conn::errorMessage, libpq_gettext, PGASYNC_IDLE, pqClearAsyncResult(), printfPQExpBuffer(), resetPQExpBuffer(), pg_conn::singleRowMode, and pg_conn::status.

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

1468 {
1469  if (!conn)
1470  return false;
1471 
1472  /* clear the error string */
1474 
1475  /* Don't try to send if we know there's no live connection. */
1476  if (conn->status != CONNECTION_OK)
1477  {
1479  libpq_gettext("no connection to the server\n"));
1480  return false;
1481  }
1482  /* Can't send while already busy, either. */
1483  if (conn->asyncStatus != PGASYNC_IDLE)
1484  {
1486  libpq_gettext("another command is already in progress\n"));
1487  return false;
1488  }
1489 
1490  /* initialize async result-accumulation state */
1491  pqClearAsyncResult(conn);
1492 
1493  /* reset single-row processing mode */
1494  conn->singleRowMode = false;
1495 
1496  /* ready to send command message */
1497  return true;
1498 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
bool singleRowMode
Definition: libpq-int.h:394
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:386
PQExpBufferData errorMessage
Definition: libpq-int.h:511
ConnStatusType status
Definition: libpq-int.h:385
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:749
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQsetnonblocking()

int PQsetnonblocking ( PGconn conn,
int  arg 
)

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

References CONNECTION_BAD, pg_conn::nonblocking, pqFlush(), pg_conn::status, and true.

3232 {
3233  bool barg;
3234 
3235  if (!conn || conn->status == CONNECTION_BAD)
3236  return -1;
3237 
3238  barg = (arg ? true : false);
3239 
3240  /* early out if the socket is already in the state requested */
3241  if (barg == conn->nonblocking)
3242  return 0;
3243 
3244  /*
3245  * to guarantee constancy for flushing/query/result-polling behavior we
3246  * need to flush the send queue at this point in order to guarantee proper
3247  * behavior. this is ok because either they are making a transition _from_
3248  * or _to_ blocking mode, either way we can block them.
3249  */
3250  /* if we are going from blocking to non-blocking flush here */
3251  if (pqFlush(conn))
3252  return -1;
3253 
3254  conn->nonblocking = barg;
3255 
3256  return 0;
3257 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:997
#define true
Definition: c.h:313
ConnStatusType status
Definition: libpq-int.h:385
bool nonblocking
Definition: libpq-int.h:392
void * arg

◆ PQsetResultAttrs()

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

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

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

Referenced by PQcopyResult().

230 {
231  int i;
232 
233  /* If attrs already exist, they cannot be overwritten. */
234  if (!res || res->numAttributes > 0)
235  return false;
236 
237  /* ignore no-op request */
238  if (numAttributes <= 0 || !attDescs)
239  return true;
240 
241  res->attDescs = (PGresAttDesc *)
242  PQresultAlloc(res, numAttributes * sizeof(PGresAttDesc));
243 
244  if (!res->attDescs)
245  return false;
246 
247  res->numAttributes = numAttributes;
248  memcpy(res->attDescs, attDescs, numAttributes * sizeof(PGresAttDesc));
249 
250  /* deep-copy the attribute names, and determine format */
251  res->binary = 1;
252  for (i = 0; i < res->numAttributes; i++)
253  {
254  if (res->attDescs[i].name)
255  res->attDescs[i].name = pqResultStrdup(res, res->attDescs[i].name);
256  else
257  res->attDescs[i].name = res->null_field;
258 
259  if (!res->attDescs[i].name)
260  return false;
261 
262  if (res->attDescs[i].format == 0)
263  res->binary = 0;
264  }
265 
266  return true;
267 }
char null_field[1]
Definition: libpq-int.h:201
PGresAttDesc * attDescs
Definition: libpq-int.h:171
int binary
Definition: libpq-int.h:179
int numAttributes
Definition: libpq-int.h:170
int i
char * name
Definition: libpq-fe.h:240
char * pqResultStrdup(PGresult *res, const char *str)
Definition: fe-exec.c:646
void * PQresultAlloc(PGresult *res, size_t nBytes)
Definition: fe-exec.c:518

◆ pqSetResultError()

void pqSetResultError ( PGresult res,
const char *  msg 
)

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

References pg_result::errMsg, and pqResultStrdup().

Referenced by pqCatenateResultError(), PQgetResult(), and PQmakeEmptyPGresult().

661 {
662  if (!res)
663  return;
664  if (msg && *msg)
665  res->errMsg = pqResultStrdup(res, msg);
666  else
667  res->errMsg = NULL;
668 }
char * errMsg
Definition: libpq-int.h:196
char * pqResultStrdup(PGresult *res, const char *str)
Definition: fe-exec.c:646

◆ PQsetSingleRowMode()

int PQsetSingleRowMode ( PGconn conn)

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

References pg_conn::asyncStatus, PGASYNC_BUSY, PGQUERY_EXTENDED, PGQUERY_SIMPLE, pg_conn::queryclass, pg_conn::result, and pg_conn::singleRowMode.

Referenced by receiveFileChunks(), and storeQueryResult().

1678 {
1679  /*
1680  * Only allow setting the flag when we have launched a query and not yet
1681  * received any results.
1682  */
1683  if (!conn)
1684  return 0;
1685  if (conn->asyncStatus != PGASYNC_BUSY)
1686  return 0;
1687  if (conn->queryclass != PGQUERY_SIMPLE &&
1688  conn->queryclass != PGQUERY_EXTENDED)
1689  return 0;
1690  if (conn->result)
1691  return 0;
1692 
1693  /* OK, set flag */
1694  conn->singleRowMode = true;
1695  return 1;
1696 }
bool singleRowMode
Definition: libpq-int.h:394
PGQueryClass queryclass
Definition: libpq-int.h:388
PGresult * result
Definition: libpq-int.h:462
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:386

◆ PQsetvalue()

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

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

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

Referenced by PQcopyResult().

432 {
433  PGresAttValue *attval;
434  const char *errmsg = NULL;
435 
436  /* Note that this check also protects us against null "res" */
437  if (!check_field_number(res, field_num))
438  return false;
439 
440  /* Invalid tup_num, must be <= ntups */
441  if (tup_num < 0 || tup_num > res->ntups)
442  {
444  "row number %d is out of range 0..%d",
445  tup_num, res->ntups);
446  return false;
447  }
448 
449  /* need to allocate a new tuple? */
450  if (tup_num == res->ntups)
451  {
452  PGresAttValue *tup;
453  int i;
454 
455  tup = (PGresAttValue *)
456  pqResultAlloc(res, res->numAttributes * sizeof(PGresAttValue),
457  true);
458 
459  if (!tup)
460  goto fail;
461 
462  /* initialize each column to NULL */
463  for (i = 0; i < res->numAttributes; i++)
464  {
465  tup[i].len = NULL_LEN;
466  tup[i].value = res->null_field;
467  }
468 
469  /* add it to the array */
470  if (!pqAddTuple(res, tup, &errmsg))
471  goto fail;
472  }
473 
474  attval = &res->tuples[tup_num][field_num];
475 
476  /* treat either NULL_LEN or NULL value pointer as a NULL field */
477  if (len == NULL_LEN || value == NULL)
478  {
479  attval->len = NULL_LEN;
480  attval->value = res->null_field;
481  }
482  else if (len <= 0)
483  {
484  attval->len = 0;
485  attval->value = res->null_field;
486  }
487  else
488  {
489  attval->value = (char *) pqResultAlloc(res, len + 1, true);
490  if (!attval->value)
491  goto fail;
492  attval->len = len;
493  memcpy(attval->value, value, len);
494  attval->value[len] = '\0';
495  }
496 
497  return true;
498 
499  /*
500  * Report failure via pqInternalNotice. If preceding code didn't provide
501  * an error message, assume "out of memory" was meant.
502  */
503 fail:
504  if (!errmsg)
505  errmsg = libpq_gettext("out of memory");
506  pqInternalNotice(&res->noticeHooks, "%s", errmsg);
507 
508  return false;
509 }
static struct @145 value
#define NULL_LEN
Definition: libpq-int.h:133
char null_field[1]
Definition: libpq-int.h:201
PGresAttValue ** tuples
Definition: libpq-int.h:172
static bool pqAddTuple(PGresult *res, PGresAttValue *tup, const char **errmsgp)
Definition: fe-exec.c:926
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:871
int numAttributes
Definition: libpq-int.h:170
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2798
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:534
int ntups
Definition: libpq-int.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:822
int i
char * value
Definition: libpq-int.h:138
#define libpq_gettext(x)
Definition: libpq-int.h:790

◆ PQunescapeBytea()

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

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

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

Referenced by dumpTrigger().

3752 {
3753  size_t strtextlen,
3754  buflen;
3755  unsigned char *buffer,
3756  *tmpbuf;
3757  size_t i,