PostgreSQL Source Code  git master
fe-exec.c File Reference
#include "postgres_fe.h"
#include <ctype.h>
#include <fcntl.h>
#include <limits.h>
#include "libpq-fe.h"
#include "libpq-int.h"
#include "mb/pg_wchar.h"
#include <unistd.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)
 
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)
 
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)
 
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)
 
void pqHandleSendFailure (PGconn *conn)
 
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 3689 of file fe-exec.c.

Referenced by PQunescapeBytea().

◆ ISOCTDIGIT

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

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

Referenced by PQunescapeBytea().

◆ OCTVAL

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

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

Referenced by PQunescapeBytea().

◆ PGRESULT_ALIGN_BOUNDARY

#define PGRESULT_ALIGN_BOUNDARY   MAXIMUM_ALIGNOF /* from configure */

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

Referenced by pqResultAlloc().

◆ PGRESULT_DATA_BLOCKSIZE

#define PGRESULT_DATA_BLOCKSIZE   2048

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

Referenced by pqResultAlloc().

◆ PGRESULT_SEP_ALLOC_THRESHOLD

#define PGRESULT_SEP_ALLOC_THRESHOLD   (PGRESULT_DATA_BLOCKSIZE / 2)

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

2754 {
2755  if (!res)
2756  return false; /* no way to display error message... */
2757  if (field_num < 0 || field_num >= res->numAttributes)
2758  {
2760  "column number %d is out of range 0..%d",
2761  field_num, res->numAttributes - 1);
2762  return false;
2763  }
2764  return true;
2765 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:822
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 2791 of file fe-exec.c.

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

Referenced by PQparamtype().

2792 {
2793  if (!res)
2794  return false; /* no way to display error message... */
2795  if (param_num < 0 || param_num >= res->numParameters)
2796  {
2798  "parameter number %d is out of range 0..%d",
2799  param_num, res->numParameters - 1);
2800  return false;
2801  }
2802 
2803  return true;
2804 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:822
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 2768 of file fe-exec.c.

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

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

2770 {
2771  if (!res)
2772  return false; /* no way to display error message... */
2773  if (tup_num < 0 || tup_num >= res->ntups)
2774  {
2776  "row number %d is out of range 0..%d",
2777  tup_num, res->ntups - 1);
2778  return false;
2779  }
2780  if (field_num < 0 || field_num >= res->numAttributes)
2781  {
2783  "column number %d is out of range 0..%d",
2784  field_num, res->numAttributes - 1);
2785  return false;
2786  }
2787  return true;
2788 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:822
int numAttributes
Definition: libpq-int.h:170
int ntups
Definition: libpq-int.h:169

◆ dupEvents()

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

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

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

Referenced by PQcopyResult(), and PQmakeEmptyPGresult().

385 {
386  PGEvent *newEvents;
387  int i;
388 
389  if (!events || count <= 0)
390  return NULL;
391 
392  newEvents = (PGEvent *) malloc(count * sizeof(PGEvent));
393  if (!newEvents)
394  return NULL;
395 
396  for (i = 0; i < count; i++)
397  {
398  newEvents[i].proc = events[i].proc;
399  newEvents[i].passThrough = events[i].passThrough;
400  newEvents[i].data = NULL;
401  newEvents[i].resultInitialized = false;
402  newEvents[i].name = strdup(events[i].name);
403  if (!newEvents[i].name)
404  {
405  while (--i >= 0)
406  free(newEvents[i].name);
407  free(newEvents);
408  return NULL;
409  }
410  }
411 
412  return newEvents;
413 }
bool resultInitialized
Definition: libpq-int.h:164
#define malloc(a)
Definition: header.h:50
void * data
Definition: libpq-int.h:163
#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
char * name
Definition: libpq-int.h:161

◆ get_hex()

static char get_hex ( char  c)
inlinestatic

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

References hexlookup.

Referenced by PQunescapeBytea().

3546 {
3547  int res = -1;
3548 
3549  if (c > 0 && c < 127)
3550  res = hexlookup[(unsigned char) c];
3551 
3552  return (char) res;
3553 }
static const int8 hexlookup[128]
Definition: fe-exec.c:3533
char * c

◆ getCopyResult()

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

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

1860 {
1861  /*
1862  * If the server connection has been lost, don't pretend everything is
1863  * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
1864  * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
1865  * error in the earlier steps in PQgetResult). The text returned in the
1866  * result is whatever is in conn->errorMessage; we hope that was filled
1867  * with something relevant when the lost connection was detected.
1868  */
1869  if (conn->status != CONNECTION_OK)
1870  {
1871  pqSaveErrorResult(conn);
1872  conn->asyncStatus = PGASYNC_IDLE;
1873  return pqPrepareAsyncResult(conn);
1874  }
1875 
1876  /* If we have an async result for the COPY, return that */
1877  if (conn->result && conn->result->resultStatus == copytype)
1878  return pqPrepareAsyncResult(conn);
1879 
1880  /* Otherwise, invent a suitable PGresult */
1881  return PQmakeEmptyPGresult(conn, copytype);
1882 }
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:777
PGresult * result
Definition: libpq-int.h:450
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:380
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:142
ConnStatusType status
Definition: libpq-int.h:379
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:749
ExecStatusType resultStatus
Definition: libpq-int.h:177

◆ parseInput()

static void parseInput ( PGconn conn)
static

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

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

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

1719 {
1720  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1721  pqParseInput3(conn);
1722  else
1723  pqParseInput2(conn);
1724 }
void pqParseInput2(PGconn *conn)
Definition: fe-protocol2.c:410
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
ProtocolVersion pversion
Definition: libpq-int.h:404
void pqParseInput3(PGconn *conn)
Definition: fe-protocol3.c:65

◆ pqAddTuple()

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

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

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

Referenced by pqRowProcessor(), and PQsetvalue().

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

◆ PQbinaryTuples()

int PQbinaryTuples ( const PGresult res)

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

References pg_result::binary.

Referenced by ProcessResult().

2741 {
2742  if (!res)
2743  return 0;
2744  return res->binary;
2745 }
int binary
Definition: libpq-int.h:179

◆ pqCatenateResultError()

void pqCatenateResultError ( PGresult res,
const char *  msg 
)

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

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

Referenced by PQexecFinish(), and pqSaveErrorResult().

653 {
654  PQExpBufferData errorBuf;
655 
656  if (!res || !msg)
657  return;
658  initPQExpBuffer(&errorBuf);
659  if (res->errMsg)
660  appendPQExpBufferStr(&errorBuf, res->errMsg);
661  appendPQExpBufferStr(&errorBuf, msg);
662  pqSetResultError(res, errorBuf.data);
663  termPQExpBuffer(&errorBuf);
664 }
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
char * errMsg
Definition: libpq-int.h:196
void pqSetResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:637
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89

◆ PQclear()

void PQclear ( PGresult res)

Definition at line 671 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(), _doSetWithOids(), _selectOutputSchema(), _selectTablespace(), add_tablespace_footer(), 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_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_is_install_user(), check_loadable_libraries(), check_proper_datallowconn(), ClearOrSaveResult(), close_cursor(), cluster_all_databases(), 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(), discard_response(), do_lo_import(), do_lo_list(), do_sql_command(), doCustom(), dropDBs(), DropReplicationSlot(), dropRoles(), dropTablespaces(), dumpAgg(), dumpBaseType(), dumpBlobs(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpCreateDB(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpDbRoleConfig(), dumpDomain(), dumpEnumType(), dumpFunc(), dumpGroups(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSequence(), dumpSequenceData(), 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(), executeCommand(), executeMaintenanceCommand(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlStatement(), executeStatement(), expand_schema_name_patterns(), expand_table_name_patterns(), fail_lo_xact(), fetch_more_data(), findLastBuiltinOid_V71(), finish_lo_xact(), get_create_object_cmd(), get_db_infos(), get_language_name(), get_loadable_libraries(), get_rel_infos(), get_remote_estimate(), get_returning_data(), get_synchronized_snapshot(), get_tablespace_paths(), getAccessMethods(), getAggregates(), getBlobs(), getCasts(), getCollations(), 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(), GetQueryResult(), getRowDescriptions(), getRules(), getSubscriptions(), getTableAttrs(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), handleCopyIn(), HandleEndOfCopyStream(), initGenerateData(), 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(), 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(), materializeQueryResult(), materializeResult(), new_9_0_populate_pg_largeobject_metadata(), objectDescription(), old_9_3_check_for_line_data_type_usage(), old_9_6_check_for_unknown_data_type_usage(), 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(), postgresEndForeignModify(), postgresExecForeignDelete(), postgresExecForeignInsert(), postgresExecForeignUpdate(), postgresImportForeignSchema(), postgresReScanForeignScan(), pqClearAsyncResult(), PQconnectPoll(), PQcopyResult(), PQencryptPasswordConn(), pqEndcopy2(), pqEndcopy3(), PQexecFinish(), PQexecStart(), pqGetErrorNotice2(), pqGetErrorNotice3(), pqInternalNotice(), PQmakeEmptyPGresult(), pqRowProcessor(), PQsetClientEncoding(), pqSetenvPoll(), prepare_common(), prepare_foreign_modify(), processExtensionTables(), ProcessResult(), PSQLexecWatch(), receiveFileChunks(), ReceiveXlogStream(), reindex_all_databases(), RetrieveWalSegSize(), run_permutation(), run_simple_query(), RunIdentifySystem(), sendCommand(), SendQuery(), set_frozenxids(), sql_exec(), start_lo_xact(), store_returning_result(), storeQueryResult(), StreamLogicalLog(), try_complete_step(), tryExecuteStatement(), vacuum_all_databases(), vacuum_one_database(), and vacuumlo().

672 {
673  PGresult_data *block;
674  int i;
675 
676  if (!res)
677  return;
678 
679  for (i = 0; i < res->nEvents; i++)
680  {
681  /* only send DESTROY to successfully-initialized event procs */
682  if (res->events[i].resultInitialized)
683  {
685 
686  evt.result = res;
687  (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
688  res->events[i].passThrough);
689  }
690  free(res->events[i].name);
691  }
692 
693  if (res->events)
694  free(res->events);
695 
696  /* Free all the subsidiary blocks */
697  while ((block = res->curBlock) != NULL)
698  {
699  res->curBlock = block->next;
700  free(block);
701  }
702 
703  /* Free the top-level tuple pointer array */
704  if (res->tuples)
705  free(res->tuples);
706 
707  /* zero out the pointer fields to catch programming errors */
708  res->attDescs = NULL;
709  res->tuples = NULL;
710  res->paramDescs = NULL;
711  res->errFields = NULL;
712  res->events = NULL;
713  res->nEvents = 0;
714  /* res->curBlock was zeroed out earlier */
715 
716  /* Free the PGresult structure itself */
717  free(res);
718 }
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 726 of file fe-exec.c.

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

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

727 {
728  if (conn->result)
729  PQclear(conn->result);
730  conn->result = NULL;
731  if (conn->next_result)
732  PQclear(conn->next_result);
733  conn->next_result = NULL;
734 }
PGresult * result
Definition: libpq-int.h:450
PGresult * next_result
Definition: libpq-int.h:451
void PQclear(PGresult *res)
Definition: fe-exec.c:671

◆ PQcmdStatus()

char* PQcmdStatus ( PGresult res)

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

References pg_result::cmdStatus.

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

2996 {
2997  if (!res)
2998  return NULL;
2999  return res->cmdStatus;
3000 }
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178

◆ PQcmdTuples()

char* PQcmdTuples ( PGresult res)

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

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

Referenced by ecpg_process_output(), execute_dml_stmt(), postgresExecForeignDelete(), postgresExecForeignInsert(), postgresExecForeignUpdate(), and SetResultVariables().

3066 {
3067  char *p,
3068  *c;
3069 
3070  if (!res)
3071  return "";
3072 
3073  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3074  {
3075  p = res->cmdStatus + 7;
3076  /* INSERT: skip oid and space */
3077  while (*p && *p != ' ')
3078  p++;
3079  if (*p == 0)
3080  goto interpret_error; /* no space? */
3081  p++;
3082  }
3083  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3084  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3085  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3086  p = res->cmdStatus + 7;
3087  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
3088  p = res->cmdStatus + 6;
3089  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3090  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3091  p = res->cmdStatus + 5;
3092  else
3093  return "";
3094 
3095  /* check that we have an integer (at least one digit, nothing else) */
3096  for (c = p; *c; c++)
3097  {
3098  if (!isdigit((unsigned char) *c))
3099  goto interpret_error;
3100  }
3101  if (c == p)
3102  goto interpret_error;
3103 
3104  return p;
3105 
3106 interpret_error:
3108  "could not interpret result from server: %s",
3109  res->cmdStatus);
3110  return "";
3111 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
char * c
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:822
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178

◆ PQconsumeInput()

int PQconsumeInput ( PGconn conn)

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

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

Referenced by CopyStreamReceive(), dblink_get_notify(), dblink_is_busy(), doCustom(), GetIdleSlot(), libpqrcv_PQexec(), libpqrcv_receive(), main(), pgfdw_get_cleanup_result(), pgfdw_get_result(), PQconnectPoll(), StreamLogicalLog(), and try_complete_step().

1683 {
1684  if (!conn)
1685  return 0;
1686 
1687  /*
1688  * for non-blocking connections try to flush the send-queue, otherwise we
1689  * may never get a response for something that may not have already been
1690  * sent because it's in our write buffer!
1691  */
1692  if (pqIsnonblocking(conn))
1693  {
1694  if (pqFlush(conn) < 0)
1695  return 0;
1696  }
1697 
1698  /*
1699  * Load more data, if available. We do this no matter what state we are
1700  * in, since we are probably getting called because the application wants
1701  * to get rid of a read-select condition. Note that we will NOT block
1702  * waiting for more input.
1703  */
1704  if (pqReadData(conn) < 0)
1705  return 0;
1706 
1707  /* Parsing of the data waits till later. */
1708  return 1;
1709 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:961
#define pqIsnonblocking(conn)
Definition: libpq-int.h:679
int pqReadData(PGconn *conn)
Definition: fe-misc.c:629

◆ PQcopyResult()

PGresult* PQcopyResult ( const PGresult src,
int  flags 
)

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

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

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

2134 {
2135  if (!PQexecStart(conn))
2136  return NULL;
2137  if (!PQsendDescribe(conn, 'P', portal))
2138  return NULL;
2139  return PQexecFinish(conn);
2140 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2178
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2053
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1979

◆ PQdescribePrepared()

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

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

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

Referenced by DescribeQuery(), and ECPGdescribe().

2115 {
2116  if (!PQexecStart(conn))
2117  return NULL;
2118  if (!PQsendDescribe(conn, 'S', stmt))
2119  return NULL;
2120  return PQexecFinish(conn);
2121 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2178
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2053
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1979

◆ PQendcopy()

int PQendcopy ( PGconn conn)

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

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

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

2574 {
2575  if (!conn)
2576  return 0;
2577 
2578  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2579  return pqEndcopy3(conn);
2580  else
2581  return pqEndcopy2(conn);
2582 }
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
int pqEndcopy3(PGconn *conn)
ProtocolVersion pversion
Definition: libpq-int.h:404
int pqEndcopy2(PGconn *conn)

◆ PQescapeBytea()

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

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

References PQescapeByteaInternal(), and static_std_strings.

3682 {
3683  return PQescapeByteaInternal(NULL, from, from_length, to_length,
3685  false /* can't use hex */ );
3686 }
static bool static_std_strings
Definition: fe-exec.c:51
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:3572

◆ PQescapeByteaConn()

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

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

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

3672 {
3673  if (!conn)
3674  return NULL;
3675  return PQescapeByteaInternal(conn, from, from_length, to_length,
3676  conn->std_strings,
3677  (conn->sversion >= 90000));
3678 }
int sversion
Definition: libpq-int.h:405
bool std_strings
Definition: libpq-int.h:423
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:3572

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

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

Referenced by PQescapeBytea(), and PQescapeByteaConn().

3575 {
3576  const unsigned char *vp;
3577  unsigned char *rp;
3578  unsigned char *result;
3579  size_t i;
3580  size_t len;
3581  size_t bslash_len = (std_strings ? 1 : 2);
3582 
3583  /*
3584  * empty string has 1 char ('\0')
3585  */
3586  len = 1;
3587 
3588  if (use_hex)
3589  {
3590  len += bslash_len + 1 + 2 * from_length;
3591  }
3592  else
3593  {
3594  vp = from;
3595  for (i = from_length; i > 0; i--, vp++)
3596  {
3597  if (*vp < 0x20 || *vp > 0x7e)
3598  len += bslash_len + 3;
3599  else if (*vp == '\'')
3600  len += 2;
3601  else if (*vp == '\\')
3602  len += bslash_len + bslash_len;
3603  else
3604  len++;
3605  }
3606  }
3607 
3608  *to_length = len;
3609  rp = result = (unsigned char *) malloc(len);
3610  if (rp == NULL)
3611  {
3612  if (conn)
3614  libpq_gettext("out of memory\n"));
3615  return NULL;
3616  }
3617 
3618  if (use_hex)
3619  {
3620  if (!std_strings)
3621  *rp++ = '\\';
3622  *rp++ = '\\';
3623  *rp++ = 'x';
3624  }
3625 
3626  vp = from;
3627  for (i = from_length; i > 0; i--, vp++)
3628  {
3629  unsigned char c = *vp;
3630 
3631  if (use_hex)
3632  {
3633  *rp++ = hextbl[(c >> 4) & 0xF];
3634  *rp++ = hextbl[c & 0xF];
3635  }
3636  else if (c < 0x20 || c > 0x7e)
3637  {
3638  if (!std_strings)
3639  *rp++ = '\\';
3640  *rp++ = '\\';
3641  *rp++ = (c >> 6) + '0';
3642  *rp++ = ((c >> 3) & 07) + '0';
3643  *rp++ = (c & 07) + '0';
3644  }
3645  else if (c == '\'')
3646  {
3647  *rp++ = '\'';
3648  *rp++ = '\'';
3649  }
3650  else if (c == '\\')
3651  {
3652  if (!std_strings)
3653  {
3654  *rp++ = '\\';
3655  *rp++ = '\\';
3656  }
3657  *rp++ = '\\';
3658  *rp++ = '\\';
3659  }
3660  else
3661  *rp++ = c;
3662  }
3663  *rp = '\0';
3664 
3665  return result;
3666 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
#define malloc(a)
Definition: header.h:50
char * c
PQExpBufferData errorMessage
Definition: libpq-int.h:493
static const char hextbl[]
Definition: fe-exec.c:3531
int i
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ PQescapeIdentifier()

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

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

References PQescapeInternal().

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

3526 {
3527  return PQescapeInternal(conn, str, len, true);
3528 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:3398

◆ PQescapeInternal()

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

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

3399 {
3400  const char *s;
3401  char *result;
3402  char *rp;
3403  int num_quotes = 0; /* single or double, depending on as_ident */
3404  int num_backslashes = 0;
3405  int input_len;
3406  int result_size;
3407  char quote_char = as_ident ? '"' : '\'';
3408 
3409  /* We must have a connection, else fail immediately. */
3410  if (!conn)
3411  return NULL;
3412 
3413  /* Scan the string for characters that must be escaped. */
3414  for (s = str; (s - str) < len && *s != '\0'; ++s)
3415  {
3416  if (*s == quote_char)
3417  ++num_quotes;
3418  else if (*s == '\\')
3419  ++num_backslashes;
3420  else if (IS_HIGHBIT_SET(*s))
3421  {
3422  int charlen;
3423 
3424  /* Slow path for possible multibyte characters */
3425  charlen = pg_encoding_mblen(conn->client_encoding, s);
3426 
3427  /* Multibyte character overruns allowable length. */
3428  if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
3429  {
3431  libpq_gettext("incomplete multibyte character\n"));
3432  return NULL;
3433  }
3434 
3435  /* Adjust s, bearing in mind that for loop will increment it. */
3436  s += charlen - 1;
3437  }
3438  }
3439 
3440  /* Allocate output buffer. */
3441  input_len = s - str;
3442  result_size = input_len + num_quotes + 3; /* two quotes, plus a NUL */
3443  if (!as_ident && num_backslashes > 0)
3444  result_size += num_backslashes + 2;
3445  result = rp = (char *) malloc(result_size);
3446  if (rp == NULL)
3447  {
3449  libpq_gettext("out of memory\n"));
3450  return NULL;
3451  }
3452 
3453  /*
3454  * If we are escaping a literal that contains backslashes, we use the
3455  * escape string syntax so that the result is correct under either value
3456  * of standard_conforming_strings. We also emit a leading space in this
3457  * case, to guard against the possibility that the result might be
3458  * interpolated immediately following an identifier.
3459  */
3460  if (!as_ident && num_backslashes > 0)
3461  {
3462  *rp++ = ' ';
3463  *rp++ = 'E';
3464  }
3465 
3466  /* Opening quote. */
3467  *rp++ = quote_char;
3468 
3469  /*
3470  * Use fast path if possible.
3471  *
3472  * We've already verified that the input string is well-formed in the
3473  * current encoding. If it contains no quotes and, in the case of
3474  * literal-escaping, no backslashes, then we can just copy it directly to
3475  * the output buffer, adding the necessary quotes.
3476  *
3477  * If not, we must rescan the input and process each character
3478  * individually.
3479  */
3480  if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
3481  {
3482  memcpy(rp, str, input_len);
3483  rp += input_len;
3484  }
3485  else
3486  {
3487  for (s = str; s - str < input_len; ++s)
3488  {
3489  if (*s == quote_char || (!as_ident && *s == '\\'))
3490  {
3491  *rp++ = *s;
3492  *rp++ = *s;
3493  }
3494  else if (!IS_HIGHBIT_SET(*s))
3495  *rp++ = *s;
3496  else
3497  {
3498  int i = pg_encoding_mblen(conn->client_encoding, s);
3499 
3500  while (1)
3501  {
3502  *rp++ = *s;
3503  if (--i == 0)
3504  break;
3505  ++s; /* for loop will provide the final increment */
3506  }
3507  }
3508  }
3509  }
3510 
3511  /* Closing quote and terminating NUL. */
3512  *rp++ = quote_char;
3513  *rp = '\0';
3514 
3515  return result;
3516 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
#define malloc(a)
Definition: header.h:50
#define IS_HIGHBIT_SET(ch)
Definition: c.h:939
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1785
PQExpBufferData errorMessage
Definition: libpq-int.h:493
int i
int client_encoding
Definition: libpq-int.h:422
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ PQescapeLiteral()

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

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

References PQescapeInternal().

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

3520 {
3521  return PQescapeInternal(conn, str, len, false);
3522 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:3398

◆ PQescapeString()

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

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

References PQescapeStringInternal(), static_client_encoding, and static_std_strings.

Referenced by get_comma_elts(), and quote_postgres().

3384 {
3385  return PQescapeStringInternal(NULL, to, from, length, NULL,
3388 }
static bool static_std_strings
Definition: fe-exec.c:51
int length(const List *list)
Definition: list.c:1271
static int static_client_encoding
Definition: fe-exec.c:50
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:3290

◆ PQescapeStringConn()

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

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

3368 {
3369  if (!conn)
3370  {
3371  /* force empty-string result */
3372  *to = '\0';
3373  if (error)
3374  *error = 1;
3375  return 0;
3376  }
3377  return PQescapeStringInternal(conn, to, from, length, error,
3378  conn->client_encoding,
3379  conn->std_strings);
3380 }
int length(const List *list)
Definition: list.c:1271
static void error(void)
Definition: sql-dyntest.c:147
bool std_strings
Definition: libpq-int.h:423
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:3290
int client_encoding
Definition: libpq-int.h:422

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

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

Referenced by PQescapeString(), and PQescapeStringConn().

3294 {
3295  const char *source = from;
3296  char *target = to;
3297  size_t remaining = length;
3298 
3299  if (error)
3300  *error = 0;
3301 
3302  while (remaining > 0 && *source != '\0')
3303  {
3304  char c = *source;
3305  int len;
3306  int i;
3307 
3308  /* Fast path for plain ASCII */
3309  if (!IS_HIGHBIT_SET(c))
3310  {
3311  /* Apply quoting if needed */
3312  if (SQL_STR_DOUBLE(c, !std_strings))
3313  *target++ = c;
3314  /* Copy the character */
3315  *target++ = c;
3316  source++;
3317  remaining--;
3318  continue;
3319  }
3320 
3321  /* Slow path for possible multibyte characters */
3322  len = pg_encoding_mblen(encoding, source);
3323 
3324  /* Copy the character */
3325  for (i = 0; i < len; i++)
3326  {
3327  if (remaining == 0 || *source == '\0')
3328  break;
3329  *target++ = *source++;
3330  remaining--;
3331  }
3332 
3333  /*
3334  * If we hit premature end of string (ie, incomplete multibyte
3335  * character), try to pad out to the correct length with spaces. We
3336  * may not be able to pad completely, but we will always be able to
3337  * insert at least one pad space (since we'd not have quoted a
3338  * multibyte character). This should be enough to make a string that
3339  * the server will error out on.
3340  */
3341  if (i < len)
3342  {
3343  if (error)
3344  *error = 1;
3345  if (conn)
3347  libpq_gettext("incomplete multibyte character\n"));
3348  for (; i < len; i++)
3349  {
3350  if (((size_t) (target - to)) / 2 >= length)
3351  break;
3352  *target++ = ' ';
3353  }
3354  break;
3355  }
3356  }
3357 
3358  /* Write the terminating NUL character. */
3359  *target = '\0';
3360 
3361  return target - to;
3362 }
int remaining
Definition: informix.c:692
int length(const List *list)
Definition: list.c:1271
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
static void error(void)
Definition: sql-dyntest.c:147
#define IS_HIGHBIT_SET(ch)
Definition: c.h:939
char * c
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1785
PQExpBufferData errorMessage
Definition: libpq-int.h:493
static char * encoding
Definition: initdb.c:123
int i
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:947
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ PQexec()

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

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

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

Referenced by _doSetSessionAuth(), _doSetWithOids(), _selectOutputSchema(), _selectTablespace(), check_loadable_libraries(), 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(), initGenerateData(), libpq_executeFileMap(), libpqConnect(), libpqProcessFileList(), lo_initialize(), lockTableForWorker(), lookup_object_oid(), main(), pgfdw_xact_callback(), PQencryptPasswordConn(), PQsetClientEncoding(), PSQLexec(), PSQLexecWatch(), ReceiveXlogStream(), RetrieveWalSegSize(), run_permutation(), run_simple_query(), RunIdentifySystem(), SendQuery(), sql_exec(), StreamLogicalLog(), tryExecuteStatement(), and vacuumlo().

1898 {
1899  if (!PQexecStart(conn))
1900  return NULL;
1901  if (!PQsendQuery(conn, query))
1902  return NULL;
1903  return PQexecFinish(conn);
1904 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1183
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2053
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1979

◆ PQexecFinish()

static PGresult * PQexecFinish ( PGconn conn)
static

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

2054 {
2055  PGresult *result;
2056  PGresult *lastResult;
2057 
2058  /*
2059  * For backwards compatibility, return the last result if there are more
2060  * than one --- but merge error messages if we get more than one error
2061  * result.
2062  *
2063  * We have to stop if we see copy in/out/both, however. We will resume
2064  * parsing after application performs the data transfer.
2065  *
2066  * Also stop if the connection is lost (else we'll loop infinitely).
2067  */
2068  lastResult = NULL;
2069  while ((result = PQgetResult(conn)) != NULL)
2070  {
2071  if (lastResult)
2072  {
2073  if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
2074  result->resultStatus == PGRES_FATAL_ERROR)
2075  {
2076  pqCatenateResultError(lastResult, result->errMsg);
2077  PQclear(result);
2078  result = lastResult;
2079 
2080  /*
2081  * Make sure PQerrorMessage agrees with concatenated result
2082  */
2084  appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
2085  }
2086  else
2087  PQclear(lastResult);
2088  }
2089  lastResult = result;
2090  if (result->resultStatus == PGRES_COPY_IN ||
2091  result->resultStatus == PGRES_COPY_OUT ||
2092  result->resultStatus == PGRES_COPY_BOTH ||
2093  conn->status == CONNECTION_BAD)
2094  break;
2095  }
2096 
2097  return lastResult;
2098 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
char * errMsg
Definition: libpq-int.h:196
PQExpBufferData errorMessage
Definition: libpq-int.h:493
void PQclear(PGresult *res)
Definition: fe-exec.c:671
ConnStatusType status
Definition: libpq-int.h:379
void pqCatenateResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:652
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
ExecStatusType resultStatus
Definition: libpq-int.h:177
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1753

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

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

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

1919 {
1920  if (!PQexecStart(conn))
1921  return NULL;
1922  if (!PQsendQueryParams(conn, command,
1923  nParams, paramTypes, paramValues, paramLengths,
1924  paramFormats, resultFormat))
1925  return NULL;
1926  return PQexecFinish(conn);
1927 }
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:1234
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2053
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1979

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

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

Referenced by ecpg_execute(), and try_complete_step().

1965 {
1966  if (!PQexecStart(conn))
1967  return NULL;
1968  if (!PQsendQueryPrepared(conn, stmtName,
1969  nParams, paramValues, paramLengths,
1970  paramFormats, resultFormat))
1971  return NULL;
1972  return PQexecFinish(conn);
1973 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2053
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:1376
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1979

◆ PQexecStart()

static bool PQexecStart ( PGconn conn)
static

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

1980 {
1981  PGresult *result;
1982 
1983  if (!conn)
1984  return false;
1985 
1986  /*
1987  * Silently discard any prior query result that application didn't eat.
1988  * This is probably poor design, but it's here for backward compatibility.
1989  */
1990  while ((result = PQgetResult(conn)) != NULL)
1991  {
1992  ExecStatusType resultStatus = result->resultStatus;
1993 
1994  PQclear(result); /* only need its status */
1995  if (resultStatus == PGRES_COPY_IN)
1996  {
1997  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1998  {
1999  /* In protocol 3, we can get out of a COPY IN state */
2000  if (PQputCopyEnd(conn,
2001  libpq_gettext("COPY terminated by new PQexec")) < 0)
2002  return false;
2003  /* keep waiting to swallow the copy's failure message */
2004  }
2005  else
2006  {
2007  /* In older protocols we have to punt */
2009  libpq_gettext("COPY IN state must be terminated first\n"));
2010  return false;
2011  }
2012  }
2013  else if (resultStatus == PGRES_COPY_OUT)
2014  {
2015  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2016  {
2017  /*
2018  * In protocol 3, we can get out of a COPY OUT state: we just
2019  * switch back to BUSY and allow the remaining COPY data to be
2020  * dropped on the floor.
2021  */
2022  conn->asyncStatus = PGASYNC_BUSY;
2023  /* keep waiting to swallow the copy's completion message */
2024  }
2025  else
2026  {
2027  /* In older protocols we have to punt */
2029  libpq_gettext("COPY OUT state must be terminated first\n"));
2030  return false;
2031  }
2032  }
2033  else if (resultStatus == PGRES_COPY_BOTH)
2034  {
2035  /* We don't allow PQexec during COPY BOTH */
2037  libpq_gettext("PQexec not allowed during COPY BOTH\n"));
2038  return false;
2039  }
2040  /* check for loss of connection, too */
2041  if (conn->status == CONNECTION_BAD)
2042  return false;
2043  }
2044 
2045  /* OK to send a command */
2046  return true;
2047 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2339
ExecStatusType
Definition: libpq-fe.h:82
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:380
PQExpBufferData errorMessage
Definition: libpq-int.h:493
void PQclear(PGresult *res)
Definition: fe-exec.c:671
ProtocolVersion pversion
Definition: libpq-int.h:404
ConnStatusType status
Definition: libpq-int.h:379
ExecStatusType resultStatus
Definition: libpq-int.h:177
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1753
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ PQfformat()

int PQfformat ( const PGresult res,
int  field_num 
)

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

2952 {
2953  if (!check_field_number(res, field_num))
2954  return 0;
2955  if (res->attDescs)
2956  return res->attDescs[field_num].format;
2957  else
2958  return 0;
2959 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2753

◆ PQflush()

int PQflush ( PGconn conn)

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

References pqFlush().

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

3239 {
3240  return pqFlush(conn);
3241 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:961

◆ PQfmod()

int PQfmod ( const PGresult res,
int  field_num 
)

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

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

Referenced by DescribeQuery(), and ECPGget_desc().

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

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

2614 {
2615  *result_len = 0;
2616 
2617  if (!conn)
2618  return NULL;
2619 
2620  /* clear the error string */
2622 
2623  if (conn->sock == PGINVALID_SOCKET || conn->asyncStatus != PGASYNC_IDLE ||
2624  conn->result != NULL)
2625  {
2627  libpq_gettext("connection in wrong state\n"));
2628  return NULL;
2629  }
2630 
2631  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2632  return pqFunctionCall3(conn, fnid,
2633  result_buf, result_len,
2634  result_is_int,
2635  args, nargs);
2636  else
2637  return pqFunctionCall2(conn, fnid,
2638  result_buf, result_len,
2639  result_is_int,
2640  args, nargs);
2641 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
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:450
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:380
pgsocket sock
Definition: libpq-int.h:400
#define PGINVALID_SOCKET
Definition: port.h:33
PQExpBufferData errorMessage
Definition: libpq-int.h:493
ProtocolVersion pversion
Definition: libpq-int.h:404
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ PQfname()

char* PQfname ( const PGresult res,
int  field_num 
)

Definition at line 2810 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(), sql_exec(), sqlda_compat_empty_size(), and StoreQueryTuple().

2811 {
2812  if (!check_field_number(res, field_num))
2813  return NULL;
2814  if (res->attDescs)
2815  return res->attDescs[field_num].name;
2816  else
2817  return NULL;
2818 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2753
char * name
Definition: libpq-fe.h:237

◆ PQfnumber()

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

Definition at line 2832 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_isn_and_int8_passing_mismatch(), check_for_jsonb_9_4_usage(), check_for_reg_data_type_usage(), check_proper_datallowconn(), collectComments(), collectSecLabels(), 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_3_check_for_line_data_type_usage(), old_9_6_check_for_unknown_data_type_usage(), old_9_6_invalidate_hash_indexes(), processExtensionTables(), set_frozenxids(), and show_binary_results().

2833 {
2834  char *field_case;
2835  bool in_quotes;
2836  bool all_lower = true;
2837  const char *iptr;
2838  char *optr;
2839  int i;
2840 
2841  if (!res)
2842  return -1;
2843 
2844  /*
2845  * Note: it is correct to reject a zero-length input string; the proper
2846  * input to match a zero-length field name would be "".
2847  */
2848  if (field_name == NULL ||
2849  field_name[0] == '\0' ||
2850  res->attDescs == NULL)
2851  return -1;
2852 
2853  /*
2854  * Check if we can avoid the strdup() and related work because the
2855  * passed-in string wouldn't be changed before we do the check anyway.
2856  */
2857  for (iptr = field_name; *iptr; iptr++)
2858  {
2859  char c = *iptr;
2860 
2861  if (c == '"' || c != pg_tolower((unsigned char) c))
2862  {
2863  all_lower = false;
2864  break;
2865  }
2866  }
2867 
2868  if (all_lower)
2869  for (i = 0; i < res->numAttributes; i++)
2870  if (strcmp(field_name, res->attDescs[i].name) == 0)
2871  return i;
2872 
2873  /* Fall through to the normal check if that didn't work out. */
2874 
2875  /*
2876  * Note: this code will not reject partially quoted strings, eg
2877  * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
2878  * condition.
2879  */
2880  field_case = strdup(field_name);
2881  if (field_case == NULL)
2882  return -1; /* grotty */
2883 
2884  in_quotes = false;
2885  optr = field_case;
2886  for (iptr = field_case; *iptr; iptr++)
2887  {
2888  char c = *iptr;
2889 
2890  if (in_quotes)
2891  {
2892  if (c == '"')
2893  {
2894  if (iptr[1] == '"')
2895  {
2896  /* doubled quotes become a single quote */
2897  *optr++ = '"';
2898  iptr++;
2899  }
2900  else
2901  in_quotes = false;
2902  }
2903  else
2904  *optr++ = c;
2905  }
2906  else if (c == '"')
2907  in_quotes = true;
2908  else
2909  {
2910  c = pg_tolower((unsigned char) c);
2911  *optr++ = c;
2912  }
2913  }
2914  *optr = '\0';
2915 
2916  for (i = 0; i < res->numAttributes; i++)
2917  {
2918  if (strcmp(field_case, res->attDescs[i].name) == 0)
2919  {
2920  free(field_case);
2921  return i;
2922  }
2923  }
2924  free(field_case);
2925  return -1;
2926 }
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:237

◆ PQfreemem()

◆ PQfreeNotify()

void PQfreeNotify ( PGnotify notify)

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

References PQfreemem().

Referenced by PQfreemem().

3269 {
3270  PQfreemem(notify);
3271 }
void PQfreemem(void *ptr)
Definition: fe-exec.c:3251

◆ PQfsize()

int PQfsize ( const PGresult res,
int  field_num 
)

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

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

Referenced by ecpg_build_compat_sqlda(), and ECPGget_desc().

2974 {
2975  if (!check_field_number(res, field_num))
2976  return 0;
2977  if (res->attDescs)
2978  return res->attDescs[field_num].typlen;
2979  else
2980  return 0;
2981 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2753

◆ PQftable()

Oid PQftable ( const PGresult res,
int  field_num 
)

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

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

2930 {
2931  if (!check_field_number(res, field_num))
2932  return InvalidOid;
2933  if (res->attDescs)
2934  return res->attDescs[field_num].tableid;
2935  else
2936  return InvalidOid;
2937 }
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:2753

◆ PQftablecol()

int PQftablecol ( const PGresult res,
int  field_num 
)

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

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

2941 {
2942  if (!check_field_number(res, field_num))
2943  return 0;
2944  if (res->attDescs)
2945  return res->attDescs[field_num].columnid;
2946  else
2947  return 0;
2948 }
int columnid
Definition: libpq-fe.h:239
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2753

◆ PQftype()

Oid PQftype ( const PGresult res,
int  field_num 
)

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

2963 {
2964  if (!check_field_number(res, field_num))
2965  return InvalidOid;
2966  if (res->attDescs)
2967  return res->attDescs[field_num].typid;
2968  else
2969  return InvalidOid;
2970 }
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:2753

◆ PQgetCopyData()

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

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

2429 {
2430  *buffer = NULL; /* for all failure cases */
2431  if (!conn)
2432  return -2;
2433  if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2434  conn->asyncStatus != PGASYNC_COPY_BOTH)
2435  {
2437  libpq_gettext("no COPY in progress\n"));
2438  return -2;
2439  }
2440  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2441  return pqGetCopyData3(conn, buffer, async);
2442  else
2443  return pqGetCopyData2(conn, buffer, async);
2444 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:380
int pqGetCopyData3(PGconn *conn, char **buffer, int async)
PQExpBufferData errorMessage
Definition: libpq-int.h:493
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
ProtocolVersion pversion
Definition: libpq-int.h:404
int pqGetCopyData2(PGconn *conn, char **buffer, int async)
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ PQgetisnull()

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

Definition at line 3143 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(), dumpCreateDB(), 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(), 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(), and storeRow().

3144 {
3145  if (!check_tuple_field_number(res, tup_num, field_num))
3146  return 1; /* pretend it is null */
3147  if (res->tuples[tup_num][field_num].len == NULL_LEN)
3148  return 1;
3149  else
3150  return 0;
3151 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:2768
#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 3129 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().

3130 {
3131  if (!check_tuple_field_number(res, tup_num, field_num))
3132  return 0;
3133  if (res->tuples[tup_num][field_num].len != NULL_LEN)
3134  return res->tuples[tup_num][field_num].len;
3135  else
3136  return 0;
3137 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:2768
#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 2470 of file fe-exec.c.

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

2471 {
2472  if (!s || maxlen <= 0)
2473  return EOF;
2474  *s = '\0';
2475  /* maxlen must be at least 3 to hold the \. terminator! */
2476  if (maxlen < 3)
2477  return EOF;
2478 
2479  if (!conn)
2480  return EOF;
2481 
2482  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2483  return pqGetline3(conn, s, maxlen);
2484  else
2485  return pqGetline2(conn, s, maxlen);
2486 }
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:404

◆ PQgetlineAsync()

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

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

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

Referenced by pqGetline3().

2521 {
2522  if (!conn)
2523  return -1;
2524 
2525  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2526  return pqGetlineAsync3(conn, buffer, bufsize);
2527  else
2528  return pqGetlineAsync2(conn, buffer, bufsize);
2529 }
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)
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
ProtocolVersion pversion
Definition: libpq-int.h:404

◆ PQgetResult()

PGresult* PQgetResult ( PGconn conn)

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

References pg_conn::asyncStatus, conn, PGEventResultCreate::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(), pqSetResultError(), pqWait(), printfPQExpBuffer(), PGEvent::proc, PGEventResultCreate::result, PGEvent::resultInitialized, and pg_result::resultStatus.

Referenced by BaseBackup(), dblink_record_internal(), discard_response(), doCustom(), dumpTableData_copy(), ecpg_process_output(), EndDBCopyMode(), GetQueryResult(), handleCopyIn(), handleCopyOut(), HandleEndOfCopyStream(), libpq_executeFileMap(), libpqrcv_endstreaming(), libpqrcv_PQexec(), libpqrcv_receive(), materializeQueryResult(), pgfdw_get_cleanup_result(), pgfdw_get_result(), PQconnectPoll(), pqEndcopy2(), pqEndcopy3(), PQexecFinish(), PQexecStart(), pqSetenvPoll(), ProcessResult(), ReceiveAndUnpackTarFile(), receiveFileChunks(), ReceiveTarFile(), ReceiveXlogStream(), storeQueryResult(), StreamLogicalLog(), and try_complete_step().

1754 {
1755  PGresult *res;
1756 
1757  if (!conn)
1758  return NULL;
1759 
1760  /* Parse any available data, if our state permits. */
1761  parseInput(conn);
1762 
1763  /* If not ready to return something, block until we are. */
1764  while (conn->asyncStatus == PGASYNC_BUSY)
1765  {
1766  int flushResult;
1767 
1768  /*
1769  * If data remains unsent, send it. Else we might be waiting for the
1770  * result of a command the backend hasn't even got yet.
1771  */
1772  while ((flushResult = pqFlush(conn)) > 0)
1773  {
1774  if (pqWait(false, true, conn))
1775  {
1776  flushResult = -1;
1777  break;
1778  }
1779  }
1780 
1781  /* Wait for some more data, and load it. */
1782  if (flushResult ||
1783  pqWait(true, false, conn) ||
1784  pqReadData(conn) < 0)
1785  {
1786  /*
1787  * conn->errorMessage has been set by pqWait or pqReadData. We
1788  * want to append it to any already-received error message.
1789  */
1790  pqSaveErrorResult(conn);
1791  conn->asyncStatus = PGASYNC_IDLE;
1792  return pqPrepareAsyncResult(conn);
1793  }
1794 
1795  /* Parse it. */
1796  parseInput(conn);
1797  }
1798 
1799  /* Return the appropriate thing. */
1800  switch (conn->asyncStatus)
1801  {
1802  case PGASYNC_IDLE:
1803  res = NULL; /* query is complete */
1804  break;
1805  case PGASYNC_READY:
1806  res = pqPrepareAsyncResult(conn);
1807  /* Set the state back to BUSY, allowing parsing to proceed. */
1808  conn->asyncStatus = PGASYNC_BUSY;
1809  break;
1810  case PGASYNC_COPY_IN:
1811  res = getCopyResult(conn, PGRES_COPY_IN);
1812  break;
1813  case PGASYNC_COPY_OUT:
1814  res = getCopyResult(conn, PGRES_COPY_OUT);
1815  break;
1816  case PGASYNC_COPY_BOTH:
1817  res = getCopyResult(conn, PGRES_COPY_BOTH);
1818  break;
1819  default:
1821  libpq_gettext("unexpected asyncStatus: %d\n"),
1822  (int) conn->asyncStatus);
1824  break;
1825  }
1826 
1827  if (res)
1828  {
1829  int i;
1830 
1831  for (i = 0; i < res->nEvents; i++)
1832  {
1833  PGEventResultCreate evt;
1834 
1835  evt.conn = conn;
1836  evt.result = res;
1837  if (!res->events[i].proc(PGEVT_RESULTCREATE, &evt,
1838  res->events[i].passThrough))
1839  {
1841  libpq_gettext("PGEventProc \"%s\" failed during PGEVT_RESULTCREATE event\n"),
1842  res->events[i].name);
1843  pqSetResultError(res, conn->errorMessage.data);
1845  break;
1846  }
1847  res->events[i].resultInitialized = true;
1848  }
1849  }
1850 
1851  return res;
1852 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:961
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
bool resultInitialized
Definition: libpq-int.h:164
int nEvents
Definition: libpq-int.h:188
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:777
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:380
PGconn * conn
Definition: streamutil.c:46
int pqReadData(PGconn *conn)
Definition: fe-misc.c:629
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:984
static PGresult * getCopyResult(PGconn *conn, ExecStatusType copytype)
Definition: fe-exec.c:1859
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:142
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1718
PQExpBufferData errorMessage
Definition: libpq-int.h:493
void pqSetResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:637
PGEventProc proc
Definition: libpq-int.h:160
int i
void * passThrough
Definition: libpq-int.h:162
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:749
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:685

◆ PQgetvalue()

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

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

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

Referenced by _check_database_version(), add_tablespace_footer(), 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_isn_and_int8_passing_mismatch(), check_for_jsonb_9_4_usage(), check_for_reg_data_type_usage(), 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(), dumpCreateDB(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpDbRoleConfig(), dumpDomain(), dumpEnumType(), dumpForeignServer(), dumpFunc(), dumpGroups(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSequence(), dumpSequenceData(), 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_schema_name_patterns(), expand_table_name_patterns(), findLastBuiltinOid_V71(), get_create_object_cmd(), get_db_infos(), get_language_name(), get_loadable_libraries(), 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(), 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_3_check_for_line_data_type_usage(), old_9_6_check_for_unknown_data_type_usage(), old_9_6_invalidate_hash_indexes(), postgresAnalyzeForeignTable(), postgresImportForeignSchema(), PQconnectPoll(), PQdisplayTuples(), PQencryptPasswordConn(), PQprintTuples(), pqSetenvPoll(), printCrosstab(), printQuery(), printResultSet(), PrintResultsInCrosstab(), processExtensionTables(), ReadEndOfStreamingResult(), ReceiveAndUnpackTarFile(), receiveFileChunks(), ReceiveTarFile(), ReceiveXlogStream(), reindex_all_databases(), 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().

3119 {
3120  if (!check_tuple_field_number(res, tup_num, field_num))
3121  return NULL;
3122  return res->tuples[tup_num][field_num].value;
3123 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:2768
PGresAttValue ** tuples
Definition: libpq-int.h:172
char * value
Definition: libpq-int.h:138

◆ pqHandleSendFailure()

void pqHandleSendFailure ( PGconn conn)

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

References parseInput(), and pqReadData().

Referenced by pqFunctionCall2(), pqFunctionCall3(), PQsendDescribe(), PQsendPrepare(), PQsendQuery(), and PQsendQueryGuts().

1634 {
1635  /*
1636  * Accept and parse any available input data, ignoring I/O errors. Note
1637  * that if pqReadData decides the backend has closed the channel, it will
1638  * close our side of the socket --- that's just what we want here.
1639  */
1640  while (pqReadData(conn) > 0)
1641  parseInput(conn);
1642 
1643  /*
1644  * Be sure to parse available input messages even if we read no data.
1645  * (Note: calling parseInput within the above loop isn't really necessary,
1646  * but it prevents buffer bloat if there's a lot of data available.)
1647  */
1648  parseInput(conn);
1649 }
int pqReadData(PGconn *conn)
Definition: fe-misc.c:629
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1718

◆ pqInternalNotice()

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

Definition at line 822 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(), and vsnprintf().

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

823 {
824  char msgBuf[1024];
825  va_list args;
826  PGresult *res;
827 
828  if (hooks->noticeRec == NULL)
829  return; /* nobody home to receive notice? */
830 
831  /* Format the message */
832  va_start(args, fmt);
833  vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
834  va_end(args);
835  msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
836 
837  /* Make a PGresult to pass to the notice receiver */
839  if (!res)
840  return;
841  res->noticeHooks = *hooks;
842 
843  /*
844  * Set up fields of notice.
845  */
849  /* XXX should provide a SQLSTATE too? */
850 
851  /*
852  * Result text is always just the primary message + newline. If we can't
853  * allocate it, don't bother invoking the receiver.
854  */
855  res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, false);
856  if (res->errMsg)
857  {
858  sprintf(res->errMsg, "%s\n", msgBuf);
859 
860  /*
861  * Pass to receiver, then free it.
862  */
863  res->noticeHooks.noticeRec(res->noticeHooks.noticeRecArg, res);
864  }
865  PQclear(res);
866 }
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:58
int int vsnprintf(char *str, size_t count, const char *fmt, va_list args)
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:142
void pqSaveMessageField(PGresult *res, char code, const char *value)
Definition: fe-exec.c:942
#define PG_DIAG_SEVERITY_NONLOCALIZED
Definition: postgres_ext.h:56
void PQclear(PGresult *res)
Definition: fe-exec.c:671
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:527
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ PQisBusy()

int PQisBusy ( PGconn conn)

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

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

Referenced by dblink_is_busy(), doCustom(), GetIdleSlot(), libpqrcv_PQexec(), pgfdw_get_cleanup_result(), pgfdw_get_result(), PQconnectPoll(), pqEndcopy2(), pqEndcopy3(), pqSetenvPoll(), and try_complete_step().

1733 {
1734  if (!conn)
1735  return false;
1736 
1737  /* Parse any available data, if our state permits. */
1738  parseInput(conn);
1739 
1740  /* PQgetResult will return immediately in all states except BUSY. */
1741  return conn->asyncStatus == PGASYNC_BUSY;
1742 }
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:380
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1718

◆ PQisnonblocking()

int PQisnonblocking ( const PGconn conn)

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

References pqIsnonblocking.

3220 {
3221  return pqIsnonblocking(conn);
3222 }
#define pqIsnonblocking(conn)
Definition: libpq-int.h:679

◆ PQisthreadsafe()

int PQisthreadsafe ( void  )

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

3227 {
3228 #ifdef ENABLE_THREAD_SAFETY
3229  return true;
3230 #else
3231  return false;
3232 #endif
3233 }

◆ PQmakeEmptyPGresult()

PGresult* PQmakeEmptyPGresult ( PGconn conn,
ExecStatusType  status 
)

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

143 {
144  PGresult *result;
145 
146  result = (PGresult *) malloc(sizeof(PGresult));
147  if (!result)
148  return NULL;
149 
150  result->ntups = 0;
151  result->numAttributes = 0;
152  result->attDescs = NULL;
153  result->tuples = NULL;
154  result->tupArrSize = 0;
155  result->numParameters = 0;
156  result->paramDescs = NULL;
157  result->resultStatus = status;
158  result->cmdStatus[0] = '\0';
159  result->binary = 0;
160  result->events = NULL;
161  result->nEvents = 0;
162  result->errMsg = NULL;
163  result->errFields = NULL;
164  result->errQuery = NULL;
165  result->null_field[0] = '\0';
166  result->curBlock = NULL;
167  result->curOffset = 0;
168  result->spaceLeft = 0;
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  if (!result->events)
198  {
199  PQclear(result);
200  return NULL;
201  }
202  result->nEvents = conn->nEvents;
203  }
204  }
205  else
206  {
207  /* defaults... */
208  result->noticeHooks.noticeRec = NULL;
209  result->noticeHooks.noticeRecArg = NULL;
210  result->noticeHooks.noticeProc = NULL;
211  result->noticeHooks.noticeProcArg = NULL;
212  result->client_encoding = PG_SQL_ASCII;
213  }
214 
215  return result;
216 }
PGMessageField * errFields
Definition: libpq-int.h:197
static PGEvent * dupEvents(PGEvent *events, int count)
Definition: fe-exec.c:384
PGEvent * events
Definition: libpq-int.h:374
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
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
PGNoticeHooks noticeHooks
Definition: libpq-int.h:371
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:493
void pqSetResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:637
void PQclear(PGresult *res)
Definition: fe-exec.c:671
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:375
int client_encoding
Definition: libpq-int.h:422
PGEvent * events
Definition: libpq-int.h:187
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
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 2244 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(), and PrintNotifications().

2245 {
2246  PGnotify *event;
2247 
2248  if (!conn)
2249  return NULL;
2250 
2251  /* Parse any available data to see if we can extract NOTIFY messages. */
2252  parseInput(conn);
2253 
2254  event = conn->notifyHead;
2255  if (event)
2256  {
2257  conn->notifyHead = event->next;
2258  if (!conn->notifyHead)
2259  conn->notifyTail = NULL;
2260  event->next = NULL; /* don't let app see the internal state */
2261  }
2262  return event;
2263 }
PGnotify * notifyHead
Definition: libpq-int.h:391
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1718
struct pgNotify * next
Definition: libpq-fe.h:167
PGnotify * notifyTail
Definition: libpq-int.h:392

◆ PQnparams()

int PQnparams ( const PGresult res)

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

References pg_result::numParameters.

3158 {
3159  if (!res)
3160  return 0;
3161  return res->numParameters;
3162 }
int numParameters
Definition: libpq-int.h:175

◆ PQntuples()

int PQntuples ( const PGresult res)

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

References pg_result::ntups.

Referenced by add_tablespace_footer(), BaseBackup(), buildMatViewRefreshDependencies(), 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_is_install_user(), check_proper_datallowconn(), cluster_all_databases(), collectComments(), collectSecLabels(), CreateReplicationSlot(), createViewAsClause(), describeOneTableDetails(), describePublications(), describeRoles(), describeTableDetails(), dropDBs(), DropReplicationSlot(), dropRoles(), dropTablespaces(), dumpBlobs(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpCreateDB(), dumpDatabaseConfig(), dumpDatabases(), dumpDbRoleConfig(), 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(), ExecuteSqlQueryForSingleRow(), expand_schema_name_patterns(), expand_table_name_patterns(), fetch_more_data(), get_create_object_cmd(), get_db_infos(), get_loadable_libraries(), 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(), 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_3_check_for_line_data_type_usage(), old_9_6_check_for_unknown_data_type_usage(), old_9_6_invalidate_hash_indexes(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresExecForeignDelete(), postgresExecForeignInsert(), postgresExecForeignUpdate(), postgresImportForeignSchema(), PQconnectPoll(), PQdisplayTuples(), PQencryptPasswordConn(), PQprint(), PQprintTuples(), pqSetenvPoll(), printCrosstab(), printQuery(), printResultSet(), PrintResultsInCrosstab(), processExtensionTables(), ReadEndOfStreamingResult(), receiveFileChunks(), ReceiveXlogStream(), reindex_all_databases(), 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().

2725 {
2726  if (!res)
2727  return 0;
2728  return res->ntups;
2729 }
int ntups
Definition: libpq-int.h:169

◆ PQoidStatus()

char* PQoidStatus ( const PGresult res)

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

References buf, and pg_result::cmdStatus.

3009 {
3010  /*
3011  * This must be enough to hold the result. Don't laugh, this is better
3012  * than what this function used to do.
3013  */
3014  static char buf[24];
3015 
3016  size_t len;
3017 
3018  if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
3019  return "";
3020 
3021  len = strspn(res->cmdStatus + 7, "0123456789");
3022  if (len > sizeof(buf) - 1)
3023  len = sizeof(buf) - 1;
3024  memcpy(buf, res->cmdStatus + 7, len);
3025  buf[len] = '\0';
3026 
3027  return buf;
3028 }
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 3036 of file fe-exec.c.

References pg_result::cmdStatus, and InvalidOid.

Referenced by ecpg_process_output(), and PrintQueryStatus().

3037 {
3038  char *endptr = NULL;
3039  unsigned long result;
3040 
3041  if (!res ||
3042  strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
3043  res->cmdStatus[7] < '0' ||
3044  res->cmdStatus[7] > '9')
3045  return InvalidOid;
3046 
3047  result = strtoul(res->cmdStatus + 7, &endptr, 10);
3048 
3049  if (!endptr || (*endptr != ' ' && *endptr != '\0'))
3050  return InvalidOid;
3051  else
3052  return (Oid) result;
3053 }
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 3168 of file fe-exec.c.

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

3169 {
3170  if (!check_param_number(res, param_num))
3171  return InvalidOid;
3172  if (res->paramDescs)
3173  return res->paramDescs[param_num].typid;
3174  else
3175  return InvalidOid;
3176 }
static int check_param_number(const PGresult *res, int param_num)
Definition: fe-exec.c:2791
#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 1941 of file fe-exec.c.

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

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

1944 {
1945  if (!PQexecStart(conn))
1946  return NULL;
1947  if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
1948  return NULL;
1949  return PQexecFinish(conn);
1950 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2053
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1979
int PQsendPrepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:1279

◆ pqPrepareAsyncResult()

PGresult* pqPrepareAsyncResult ( PGconn conn)

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

778 {
779  PGresult *res;
780 
781  /*
782  * conn->result is the PGresult to return. If it is NULL (which probably
783  * shouldn't happen) we assume there is an appropriate error message in
784  * conn->errorMessage.
785  */
786  res = conn->result;
787  if (!res)
789  else
790  {
791  /*
792  * Make sure PQerrorMessage agrees with result; it could be different
793  * if we have concatenated messages.
794  */
797  PQresultErrorMessage(res));
798  }
799 
800  /*
801  * Replace conn->result with next_result, if any. In the normal case
802  * there isn't a next result and we're just dropping ownership of the
803  * current result. In single-row mode this restores the situation to what
804  * it was before we created the current single-row result.
805  */
806  conn->result = conn->next_result;
807  conn->next_result = NULL;
808 
809  return res;
810 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
PGresult * result
Definition: libpq-int.h:450
PGresult * next_result
Definition: libpq-int.h:451
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:142
PQExpBufferData errorMessage
Definition: libpq-int.h:493
char * PQresultErrorMessage(const PGresult *res)
Definition: fe-exec.c:2663
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145

◆ PQputCopyData()

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

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

2273 {
2274  if (!conn)
2275  return -1;
2276  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2277  conn->asyncStatus != PGASYNC_COPY_BOTH)
2278  {
2280  libpq_gettext("no COPY in progress\n"));
2281  return -1;
2282  }
2283 
2284  /*
2285  * Process any NOTICE or NOTIFY messages that might be pending in the
2286  * input buffer. Since the server might generate many notices during the
2287  * COPY, we want to clean those out reasonably promptly to prevent
2288  * indefinite expansion of the input buffer. (Note: the actual read of
2289  * input data into the input buffer happens down inside pqSendSome, but
2290  * it's not authorized to get rid of the data again.)
2291  */
2292  parseInput(conn);
2293 
2294  if (nbytes > 0)
2295  {
2296  /*
2297  * Try to flush any previously sent data in preference to growing the
2298  * output buffer. If we can't enlarge the buffer enough to hold the
2299  * data, return 0 in the nonblock case, else hard error. (For
2300  * simplicity, always assume 5 bytes of overhead even in protocol 2.0
2301  * case.)
2302  */
2303  if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2304  {
2305  if (pqFlush(conn) < 0)
2306  return -1;
2307  if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2308  conn))
2309  return pqIsnonblocking(conn) ? 0 : -1;
2310  }
2311  /* Send the data (too simple to delegate to fe-protocol files) */
2312  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2313  {
2314  if (pqPutMsgStart('d', false, conn) < 0 ||
2315  pqPutnchar(buffer, nbytes, conn) < 0 ||
2316  pqPutMsgEnd(conn) < 0)
2317  return -1;
2318  }
2319  else
2320  {
2321  if (pqPutMsgStart(0, false, conn) < 0 ||
2322  pqPutnchar(buffer, nbytes, conn) < 0 ||
2323  pqPutMsgEnd(conn) < 0)
2324  return -1;
2325  }
2326  }
2327  return 1;
2328 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:961
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:344
#define pqIsnonblocking(conn)
Definition: libpq-int.h:679
int outCount
Definition: libpq-int.h:438
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:519
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:380
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1718
PQExpBufferData errorMessage
Definition: libpq-int.h:493
int outBufSize
Definition: libpq-int.h:437
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:246
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
ProtocolVersion pversion
Definition: libpq-int.h:404
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:587
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ PQputCopyEnd()

int PQputCopyEnd ( PGconn conn,
const char *  errormsg 
)

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

2340 {
2341  if (!conn)
2342  return -1;
2343  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2344  conn->asyncStatus != PGASYNC_COPY_BOTH)
2345  {
2347  libpq_gettext("no COPY in progress\n"));
2348  return -1;
2349  }
2350 
2351  /*
2352  * Send the COPY END indicator. This is simple enough that we don't
2353  * bother delegating it to the fe-protocol files.
2354  */
2355  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2356  {
2357  if (errormsg)
2358  {
2359  /* Send COPY FAIL */
2360  if (pqPutMsgStart('f', false, conn) < 0 ||
2361  pqPuts(errormsg, conn) < 0 ||
2362  pqPutMsgEnd(conn) < 0)
2363  return -1;
2364  }
2365  else
2366  {
2367  /* Send COPY DONE */
2368  if (pqPutMsgStart('c', false, conn) < 0 ||
2369  pqPutMsgEnd(conn) < 0)
2370  return -1;
2371  }
2372 
2373  /*
2374  * If we sent the COPY command in extended-query mode, we must issue a
2375  * Sync as well.
2376  */
2377  if (conn->queryclass != PGQUERY_SIMPLE)
2378  {
2379  if (pqPutMsgStart('S', false, conn) < 0 ||
2380  pqPutMsgEnd(conn) < 0)
2381  return -1;
2382  }
2383  }
2384  else
2385  {
2386  if (errormsg)
2387  {
2388  /* Oops, no way to do this in 2.0 */
2390  libpq_gettext("function requires at least protocol version 3.0\n"));
2391  return -1;
2392  }
2393  else
2394  {
2395  /* Send old-style end-of-data marker */
2396  if (pqPutMsgStart(0, false, conn) < 0 ||
2397  pqPutnchar("\\.\n", 3, conn) < 0 ||
2398  pqPutMsgEnd(conn) < 0)
2399  return -1;
2400  }
2401  }
2402 
2403  /* Return to active duty */
2404  if (conn->asyncStatus == PGASYNC_COPY_BOTH)
2405  conn->asyncStatus = PGASYNC_COPY_OUT;
2406  else
2407  conn->asyncStatus = PGASYNC_BUSY;
2409 
2410  /* Try to flush data */
2411  if (pqFlush(conn) < 0)
2412  return -1;
2413 
2414  return 1;
2415 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:961
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
PGQueryClass queryclass
Definition: libpq-int.h:382
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:519
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:380
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:179
PQExpBufferData errorMessage
Definition: libpq-int.h:493
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:246
ProtocolVersion pversion
Definition: libpq-int.h:404
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:587
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ PQputline()

int PQputline ( PGconn conn,
const char *  s 
)

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

References PQputnbytes().

Referenced by initGenerateData().

2541 {
2542  return PQputnbytes(conn, s, strlen(s));
2543 }
int PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2550

◆ PQputnbytes()

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

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

References PQputCopyData().

Referenced by PQputline().

2551 {
2552  if (PQputCopyData(conn, buffer, nbytes) > 0)
2553  return 0;
2554  else
2555  return EOF;
2556 }
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2272
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214

◆ PQresStatus()

char* PQresStatus ( ExecStatusType  status)

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

References libpq_gettext, pgresStatus, and status().

Referenced by try_complete_step().

2656 {
2657  if ((unsigned int) status >= sizeof pgresStatus / sizeof pgresStatus[0])
2658  return libpq_gettext("invalid ExecStatusType code");
2659  return pgresStatus[status];
2660 }
char *const pgresStatus[]
Definition: fe-exec.c:33
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ PQresultAlloc()

void* PQresultAlloc ( PGresult res,
size_t  nBytes 
)

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

References pqResultAlloc().

Referenced by PQsetResultAttrs().

512 {
513  return pqResultAlloc(res, nBytes, true);
514 }
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:527

◆ pqResultAlloc()

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

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

References pg_result::curBlock, pg_result::curOffset, malloc, 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().

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

◆ PQresultErrorField()

char* PQresultErrorField ( const PGresult res,
int  fieldcode 
)

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

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

Referenced by CreateReplicationSlot(), dblink_res_error(), ecpg_raise_backend(), ECPGnoticeReceiver(), GetQueryResult(), main(), minimal_error_message(), pgfdw_report_error(), pgpassfileWarning(), pqBuildErrorMessage3(), PQconnectPoll(), SetResultVariables(), and try_complete_step().

2710 {
2711  PGMessageField *pfield;
2712 
2713  if (!res)
2714  return NULL;
2715  for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
2716  {
2717  if (pfield->code == fieldcode)
2718  return pfield->contents;
2719  }
2720  return NULL;
2721 }
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)

◆ PQresultStatus()

ExecStatusType PQresultStatus ( const PGresult res)

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

References PGRES_FATAL_ERROR, and pg_result::resultStatus.

Referenced by _doSetSessionAuth(), _doSetWithOids(), _selectOutputSchema(), _selectTablespace(), AcceptResult(), BaseBackup(), check_loadable_libraries(), ClearOrSaveResult(), close_cursor(), create_cursor(), CreateReplicationSlot(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_record_internal(), DescribeQuery(), do_sql_command(), doCustom(), DropReplicationSlot(), dumpTableData_copy(), ecpg_check_PQresult(), ecpg_is_type_an_array(), ecpg_process_output(), EndDBCopyMode(), ExecQueryUsingCursor(), execute_dml_stmt(), executeCommand(), executeMaintenanceCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlQuery(), ExecuteSqlStatement(), executeStatement(), fetch_more_data(), get_create_object_cmd(), get_remote_estimate(), GetQueryResult(), handleCopyIn(), handleCopyOut(), HandleEndOfCopyStream(), initGenerateData(), 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(), materializeQueryResult(), materializeResult(), pgfdw_exec_cleanup_query(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresEndForeignModify(), postgresExecForeignDelete(), postgresExecForeignInsert(), postgresExecForeignUpdate(), postgresImportForeignSchema(), postgresReScanForeignScan(), PQconnectPoll(), PQencryptPasswordConn(), pqSetenvPoll(), prepare_foreign_modify(), PrintQueryResults(), PrintResultsInCrosstab(), ProcessResult(), PSQLexecWatch(), ReceiveAndUnpackTarFile(), receiveFileChunks(), ReceiveTarFile(), ReceiveXlogStream(), RetrieveWalSegSize(), run_permutation(), run_simple_query(), RunIdentifySystem(), sendCommand(), SendQuery(), sql_exec(), storeQueryResult(), StreamLogicalLog(), try_complete_step(), tryExecuteStatement(), and vacuumlo().

2648 {
2649  if (!res)
2650  return PGRES_FATAL_ERROR;
2651  return res->resultStatus;
2652 }
ExecStatusType resultStatus
Definition: libpq-int.h:177

◆ pqResultStrdup()

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

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

References pqResultAlloc().

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

624 {
625  char *space = (char *) pqResultAlloc(res, strlen(str) + 1, false);
626 
627  if (space)
628  strcpy(space, str);
629  return space;
630 }
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:527

◆ PQresultVerboseErrorMessage()

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

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

2674 {
2675  PQExpBufferData workBuf;
2676 
2677  /*
2678  * Because the caller is expected to free the result string, we must
2679  * strdup any constant result. We use plain strdup and document that
2680  * callers should expect NULL if out-of-memory.
2681  */
2682  if (!res ||
2683  (res->resultStatus != PGRES_FATAL_ERROR &&
2685  return strdup(libpq_gettext("PGresult is not an error result\n"));
2686 
2687  initPQExpBuffer(&workBuf);
2688 
2689  /*
2690  * Currently, we pass this off to fe-protocol3.c in all cases; it will
2691  * behave reasonably sanely with an error reported by fe-protocol2.c as
2692  * well. If necessary, we could record the protocol version in PGresults
2693  * so as to be able to invoke a version-specific message formatter, but
2694  * for now there's no need.
2695  */
2696  pqBuildErrorMessage3(&workBuf, res, verbosity, show_context);
2697 
2698  /* If insufficient memory to format the message, fail cleanly */
2699  if (PQExpBufferDataBroken(workBuf))
2700  {
2701  termPQExpBuffer(&workBuf);
2702  return strdup(libpq_gettext("out of memory\n"));
2703  }
2704 
2705  return workBuf.data;
2706 }
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
Definition: fe-protocol3.c:981
ExecStatusType resultStatus
Definition: libpq-int.h:177
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ pqRowProcessor()

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

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

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

◆ pqSaveErrorResult()

void pqSaveErrorResult ( PGconn conn)

Definition at line 749 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(), and pqParseInput3().

750 {
751  /*
752  * If no old async result, just let PQmakeEmptyPGresult make one. Likewise
753  * if old result is not an error message.
754  */
755  if (conn->result == NULL ||
757  conn->result->errMsg == NULL)
758  {
759  pqClearAsyncResult(conn);
761  }
762  else
763  {
764  /* Else, concatenate error message to existing async result. */
766  }
767 }
char * errMsg
Definition: libpq-int.h:196
PGresult * result
Definition: libpq-int.h:450
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:142
PQExpBufferData errorMessage
Definition: libpq-int.h:493
void pqCatenateResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:652
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:726
ExecStatusType resultStatus
Definition: libpq-int.h:177

◆ pqSaveMessageField()

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

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

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

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

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

◆ pqSaveParameterStatus()

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

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

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

964 {
965  pgParameterStatus *pstatus;
966  pgParameterStatus *prev;
967 
968  if (conn->Pfdebug)
969  fprintf(conn->Pfdebug, "pqSaveParameterStatus: '%s' = '%s'\n",
970  name, value);
971 
972  /*
973  * Forget any old information about the parameter
974  */
975  for (pstatus = conn->pstatus, prev = NULL;
976  pstatus != NULL;
977  prev = pstatus, pstatus = pstatus->next)
978  {
979  if (strcmp(pstatus->name, name) == 0)
980  {
981  if (prev)
982  prev->next = pstatus->next;
983  else
984  conn->pstatus = pstatus->next;
985  free(pstatus); /* frees name and value strings too */
986  break;
987  }
988  }
989 
990  /*
991  * Store new info as a single malloc block
992  */
993  pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
994  strlen(name) + strlen(value) + 2);
995  if (pstatus)
996  {
997  char *ptr;
998 
999  ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
1000  pstatus->name = ptr;
1001  strcpy(ptr, name);
1002  ptr += strlen(name) + 1;
1003  pstatus->value = ptr;
1004  strcpy(ptr, value);
1005  pstatus->next = conn->pstatus;
1006  conn->pstatus = pstatus;
1007  }
1008 
1009  /*
1010  * Special hacks: remember client_encoding and
1011  * standard_conforming_strings, and convert server version to a numeric
1012  * form. We keep the first two of these in static variables as well, so
1013  * that PQescapeString and PQescapeBytea can behave somewhat sanely (at
1014  * least in single-connection-using programs).
1015  */
1016  if (strcmp(name, "client_encoding") == 0)
1017  {
1019  /* if we don't recognize the encoding name, fall back to SQL_ASCII */
1020  if (conn->client_encoding < 0)
1021  conn->client_encoding = PG_SQL_ASCII;
1023  }
1024  else if (strcmp(name, "standard_conforming_strings") == 0)
1025  {
1026  conn->std_strings = (strcmp(value, "on") == 0);
1028  }
1029  else if (strcmp(name, "server_version") == 0)
1030  {
1031  int cnt;
1032  int vmaj,
1033  vmin,
1034  vrev;
1035 
1036  cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
1037 
1038  if (cnt == 3)
1039  {
1040  /* old style, e.g. 9.6.1 */
1041  conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
1042  }
1043  else if (cnt == 2)
1044  {
1045  if (vmaj >= 10)
1046  {
1047  /* new style, e.g. 10.1 */
1048  conn->sversion = 100 * 100 * vmaj + vmin;
1049  }
1050  else
1051  {
1052  /* old style without minor version, e.g. 9.6devel */
1053  conn->sversion = (100 * vmaj + vmin) * 100;
1054  }
1055  }
1056  else if (cnt == 1)
1057  {
1058  /* new style without minor version, e.g. 10devel */
1059  conn->sversion = 100 * 100 * vmaj;
1060  }
1061  else
1062  conn->sversion = 0; /* unknown */
1063  }
1064 }
static bool static_std_strings
Definition: fe-exec.c:51
int pg_char_to_encoding(const char *name)
Definition: encnames.c:551
FILE * Pfdebug
Definition: libpq-int.h:368
#define malloc(a)
Definition: header.h:50
int sversion
Definition: libpq-int.h:405
struct pgParameterStatus pgParameterStatus
static struct @121 value
static int static_client_encoding
Definition: fe-exec.c:50
pgParameterStatus * pstatus
Definition: libpq-int.h:421
bool std_strings
Definition: libpq-int.h:423
#define free(a)
Definition: header.h:65
struct pgParameterStatus * next
Definition: libpq-int.h:258
const char * name
Definition: encode.c:521
int client_encoding
Definition: libpq-int.h:422

◆ PQsendDescribe()

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

Definition at line 2178 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(), pqHandleSendFailure(), pqPutc(), pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), PQsendQueryStart(), printfPQExpBuffer(), pg_conn::pversion, and pg_conn::queryclass.

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

2179 {
2180  /* Treat null desc_target as empty string */
2181  if (!desc_target)
2182  desc_target = "";
2183 
2184  if (!PQsendQueryStart(conn))
2185  return 0;
2186 
2187  /* This isn't gonna work on a 2.0 server */
2188  if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2189  {
2191  libpq_gettext("function requires at least protocol version 3.0\n"));
2192  return 0;
2193  }
2194 
2195  /* construct the Describe message */
2196  if (pqPutMsgStart('D', false, conn) < 0 ||
2197  pqPutc(desc_type, conn) < 0 ||
2198  pqPuts(desc_target, conn) < 0 ||
2199  pqPutMsgEnd(conn) < 0)
2200  goto sendFailed;
2201 
2202  /* construct the Sync message */
2203  if (pqPutMsgStart('S', false, conn) < 0 ||
2204  pqPutMsgEnd(conn) < 0)
2205  goto sendFailed;
2206 
2207  /* remember we are doing a Describe */
2208  conn->queryclass = PGQUERY_DESCRIBE;
2209 
2210  /* reset last-query string (not relevant now) */
2211  if (conn->last_query)
2212  {
2213  free(conn->last_query);
2214  conn->last_query = NULL;
2215  }
2216 
2217  /*
2218  * Give the data a push. In nonblock mode, don't complain if we're unable
2219  * to send it all; PQgetResult() will do any additional flushing needed.
2220  */
2221  if (pqFlush(conn) < 0)
2222  goto sendFailed;
2223 
2224  /* OK, it's launched! */
2225  conn->asyncStatus = PGASYNC_BUSY;
2226  return 1;
2227 
2228 sendFailed:
2229  pqHandleSendFailure(conn);
2230  return 0;
2231 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:961
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
void pqHandleSendFailure(PGconn *conn)
Definition: fe-exec.c:1633
PGQueryClass queryclass
Definition: libpq-int.h:382
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:519
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:380
int pqPutc(char c, PGconn *conn)
Definition: fe-misc.c:112
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:179
char * last_query
Definition: libpq-int.h:383
static bool PQsendQueryStart(PGconn *conn)
Definition: fe-exec.c:1416
PQExpBufferData errorMessage
Definition: libpq-int.h:493
#define free(a)
Definition: header.h:65
ProtocolVersion pversion
Definition: libpq-int.h:404
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:587
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ PQsendDescribePortal()

int PQsendDescribePortal ( PGconn conn,
const char *  portal 
)

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

References PQsendDescribe().

2164 {
2165  return PQsendDescribe(conn, 'P', portal);
2166 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2178

◆ PQsendDescribePrepared()

int PQsendDescribePrepared ( PGconn conn,
const char *  stmt 
)

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

References PQsendDescribe().

2151 {
2152  return PQsendDescribe(conn, 'S', stmt);
2153 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2178

◆ PQsendPrepare()

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

Definition at line 1279 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(), pqHandleSendFailure(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), PQsendQueryStart(), printfPQExpBuffer(), pg_conn::pversion, and pg_conn::queryclass.

Referenced by PQprepare(), and prepare_foreign_modify().

1282 {
1283  if (!PQsendQueryStart(conn))
1284  return 0;
1285 
1286  /* check the arguments */
1287  if (!stmtName)
1288  {
1290  libpq_gettext("statement name is a null pointer\n"));
1291  return 0;
1292  }
1293  if (!query)
1294  {
1296  libpq_gettext("command string is a null pointer\n"));
1297  return 0;
1298  }
1299  if (nParams < 0 || nParams > 65535)
1300  {
1302  libpq_gettext("number of parameters must be between 0 and 65535\n"));
1303  return 0;
1304  }
1305 
1306  /* This isn't gonna work on a 2.0 server */
1307  if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1308  {
1310  libpq_gettext("function requires at least protocol version 3.0\n"));
1311  return 0;
1312  }
1313 
1314  /* construct the Parse message */
1315  if (pqPutMsgStart('P', false, conn) < 0 ||
1316  pqPuts(stmtName, conn) < 0 ||
1317  pqPuts(query, conn) < 0)
1318  goto sendFailed;
1319 
1320  if (nParams > 0 && paramTypes)
1321  {
1322  int i;
1323 
1324  if (pqPutInt(nParams, 2, conn) < 0)
1325  goto sendFailed;
1326  for (i = 0; i < nParams; i++)
1327  {
1328  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1329  goto sendFailed;
1330  }
1331  }
1332  else
1333  {
1334  if (pqPutInt(0, 2, conn) < 0)
1335  goto sendFailed;
1336  }
1337  if (pqPutMsgEnd(conn) < 0)
1338  goto sendFailed;
1339 
1340  /* construct the Sync message */
1341  if (pqPutMsgStart('S', false, conn) < 0 ||
1342  pqPutMsgEnd(conn) < 0)
1343  goto sendFailed;
1344 
1345  /* remember we are doing just a Parse */
1346  conn->queryclass = PGQUERY_PREPARE;
1347 
1348  /* and remember the query text too, if possible */
1349  /* if insufficient memory, last_query just winds up NULL */
1350  if (conn->last_query)
1351  free(conn->last_query);
1352  conn->last_query = strdup(query);
1353 
1354  /*
1355  * Give the data a push. In nonblock mode, don't complain if we're unable
1356  * to send it all; PQgetResult() will do any additional flushing needed.
1357  */
1358  if (pqFlush(conn) < 0)
1359  goto sendFailed;
1360 
1361  /* OK, it's launched! */
1362  conn->asyncStatus = PGASYNC_BUSY;
1363  return 1;
1364 
1365 sendFailed:
1366  pqHandleSendFailure(conn);
1367  return 0;
1368 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:961
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
void pqHandleSendFailure(PGconn *conn)
Definition: fe-exec.c:1633
PGQueryClass queryclass
Definition: libpq-int.h:382
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:519
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:307
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:380
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:179
char * last_query
Definition: libpq-int.h:383
static bool PQsendQueryStart(PGconn *conn)
Definition: fe-exec.c:1416
PQExpBufferData errorMessage
Definition: libpq-int.h:493
#define free(a)
Definition: header.h:65
ProtocolVersion pversion
Definition: libpq-int.h:404
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:587
int i
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ PQsendQuery()

int PQsendQuery ( PGconn conn,
const char *  query 
)

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

References pg_conn::asyncStatus, pg_conn::errorMessage, free, pg_conn::last_query, libpq_gettext, PGASYNC_BUSY, PGQUERY_SIMPLE, pqFlush(), pqHandleSendFailure(), 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_vacuum_command(), sendCommand(), and storeQueryResult().

1184 {
1185  if (!PQsendQueryStart(conn))
1186  return 0;
1187 
1188  /* check the argument */
1189  if (!query)
1190  {
1192  libpq_gettext("command string is a null pointer\n"));
1193  return 0;
1194  }
1195 
1196  /* construct the outgoing Query message */
1197  if (pqPutMsgStart('Q', false, conn) < 0 ||
1198  pqPuts(query, conn) < 0 ||
1199  pqPutMsgEnd(conn) < 0)
1200  {
1201  pqHandleSendFailure(conn);
1202  return 0;
1203  }
1204 
1205  /* remember we are using simple query protocol */
1206  conn->queryclass = PGQUERY_SIMPLE;
1207 
1208  /* and remember the query text too, if possible */
1209  /* if insufficient memory, last_query just winds up NULL */
1210  if (conn->last_query)
1211  free(conn->last_query);
1212  conn->last_query = strdup(query);
1213 
1214  /*
1215  * Give the data a push. In nonblock mode, don't complain if we're unable
1216  * to send it all; PQgetResult() will do any additional flushing needed.
1217  */
1218  if (pqFlush(conn) < 0)
1219  {
1220  pqHandleSendFailure(conn);
1221  return 0;
1222  }
1223 
1224  /* OK, it's launched! */
1225  conn->asyncStatus = PGASYNC_BUSY;
1226  return 1;
1227 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:961
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
void pqHandleSendFailure(PGconn *conn)
Definition: fe-exec.c:1633
PGQueryClass queryclass
Definition: libpq-int.h:382
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:519
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:380
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:179
char * last_query
Definition: libpq-int.h:383
static bool PQsendQueryStart(PGconn *conn)
Definition: fe-exec.c:1416
PQExpBufferData errorMessage
Definition: libpq-int.h:493
#define free(a)
Definition: header.h:65
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:587
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ 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 1457 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(), pqHandleSendFailure(), pqPutc(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), pqPuts(), printfPQExpBuffer(), pg_conn::pversion, and pg_conn::queryclass.

Referenced by PQsendQueryParams(), and PQsendQueryPrepared().

1466 {
1467  int i;
1468 
1469  /* This isn't gonna work on a 2.0 server */
1470  if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1471  {
1473  libpq_gettext("function requires at least protocol version 3.0\n"));
1474  return 0;
1475  }
1476 
1477  /*
1478  * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync,
1479  * using specified statement name and the unnamed portal.
1480  */
1481 
1482  if (command)
1483  {
1484  /* construct the Parse message */
1485  if (pqPutMsgStart('P', false, conn) < 0 ||
1486  pqPuts(stmtName, conn) < 0 ||
1487  pqPuts(command, conn) < 0)
1488  goto sendFailed;
1489  if (nParams > 0 && paramTypes)
1490  {
1491  if (pqPutInt(nParams, 2, conn) < 0)
1492  goto sendFailed;
1493  for (i = 0; i < nParams; i++)
1494  {
1495  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1496  goto sendFailed;
1497  }
1498  }
1499  else
1500  {
1501  if (pqPutInt(0, 2, conn) < 0)
1502  goto sendFailed;
1503  }
1504  if (pqPutMsgEnd(conn) < 0)
1505  goto sendFailed;
1506  }
1507 
1508  /* Construct the Bind message */
1509  if (pqPutMsgStart('B', false, conn) < 0 ||
1510  pqPuts("", conn) < 0 ||
1511  pqPuts(stmtName, conn) < 0)
1512  goto sendFailed;
1513 
1514  /* Send parameter formats */
1515  if (nParams > 0 && paramFormats)
1516  {
1517  if (pqPutInt(nParams, 2, conn) < 0)
1518  goto sendFailed;
1519  for (i = 0; i < nParams; i++)
1520  {
1521  if (pqPutInt(paramFormats[i], 2, conn) < 0)
1522  goto sendFailed;
1523  }
1524  }
1525  else
1526  {
1527  if (pqPutInt(0, 2, conn) < 0)
1528  goto sendFailed;
1529  }
1530 
1531  if (pqPutInt(nParams, 2, conn) < 0)
1532  goto sendFailed;
1533 
1534  /* Send parameters */
1535  for (i = 0; i < nParams; i++)
1536  {
1537  if (paramValues && paramValues[i])
1538  {
1539  int nbytes;
1540 
1541  if (paramFormats && paramFormats[i] != 0)
1542  {
1543  /* binary parameter */
1544  if (paramLengths)
1545  nbytes = paramLengths[i];
1546  else
1547  {
1549  libpq_gettext("length must be given for binary parameter\n"));
1550  goto sendFailed;
1551  }
1552  }
1553  else
1554  {
1555  /* text parameter, do not use paramLengths */
1556  nbytes = strlen(paramValues[i]);
1557  }
1558  if (pqPutInt(nbytes, 4, conn) < 0 ||
1559  pqPutnchar(paramValues[i], nbytes, conn) < 0)
1560  goto sendFailed;
1561  }
1562  else
1563  {
1564  /* take the param as NULL */
1565  if (pqPutInt(-1, 4, conn) < 0)
1566  goto sendFailed;
1567  }
1568  }
1569  if (pqPutInt(1, 2, conn) < 0 ||
1570  pqPutInt(resultFormat, 2, conn))
1571  goto sendFailed;
1572  if (pqPutMsgEnd(conn) < 0)
1573  goto sendFailed;
1574 
1575  /* construct the Describe Portal message */
1576  if (pqPutMsgStart('D', false, conn) < 0 ||
1577  pqPutc('P', conn) < 0 ||
1578  pqPuts("", conn) < 0 ||
1579  pqPutMsgEnd(conn) < 0)
1580  goto sendFailed;
1581 
1582  /* construct the Execute message */
1583  if (pqPutMsgStart('E', false, conn) < 0 ||
1584  pqPuts("", conn) < 0 ||
1585  pqPutInt(0, 4, conn) < 0 ||
1586  pqPutMsgEnd(conn) < 0)
1587  goto sendFailed;
1588 
1589  /* construct the Sync message */
1590  if (pqPutMsgStart('S', false, conn) < 0 ||
1591  pqPutMsgEnd(conn) < 0)
1592  goto sendFailed;
1593 
1594  /* remember we are using extended query protocol */
1595  conn->queryclass = PGQUERY_EXTENDED;
1596 
1597  /* and remember the query text too, if possible */
1598  /* if insufficient memory, last_query just winds up NULL */
1599  if (conn->last_query)
1600  free(conn->last_query);
1601  if (command)
1602  conn->last_query = strdup(command);
1603  else
1604  conn->last_query = NULL;
1605 
1606  /*
1607  * Give the data a push. In nonblock mode, don't complain if we're unable
1608  * to send it all; PQgetResult() will do any additional flushing needed.
1609  */
1610  if (pqFlush(conn) < 0)
1611  goto sendFailed;
1612 
1613  /* OK, it's launched! */
1614  conn->asyncStatus = PGASYNC_BUSY;
1615  return 1;
1616 
1617 sendFailed:
1618  pqHandleSendFailure(conn);
1619  return 0;
1620 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:961
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
void pqHandleSendFailure(PGconn *conn)
Definition: fe-exec.c:1633
PGQueryClass queryclass
Definition: libpq-int.h:382
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:519
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:307
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:380
int pqPutc(char c, PGconn *conn)
Definition: fe-misc.c:112
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:179
char * last_query
Definition: libpq-int.h:383
PQExpBufferData errorMessage
Definition: libpq-int.h:493
#define free(a)
Definition: header.h:65
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:246
ProtocolVersion pversion
Definition: libpq-int.h:404
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:587
int i
#define libpq_gettext(x)
Definition: libpq-int.h:685

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

1242 {
1243  if (!PQsendQueryStart(conn))
1244  return 0;
1245 
1246  /* check the arguments */
1247  if (!command)
1248  {
1250  libpq_gettext("command string is a null pointer\n"));
1251  return 0;
1252  }
1253  if (nParams < 0 || nParams > 65535)
1254  {
1256  libpq_gettext("number of parameters must be between 0 and 65535\n"));
1257  return 0;
1258  }
1259 
1260  return PQsendQueryGuts(conn,
1261  command,
1262  "", /* use unnamed statement */
1263  nParams,
1264  paramTypes,
1265  paramValues,
1266  paramLengths,
1267  paramFormats,
1268  resultFormat);
1269 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
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:1457
static bool PQsendQueryStart(PGconn *conn)
Definition: fe-exec.c:1416
PQExpBufferData errorMessage
Definition: libpq-int.h:493
#define libpq_gettext(x)
Definition: libpq-int.h:685

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

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

Referenced by postgresExecForeignDelete(), postgresExecForeignInsert(), postgresExecForeignUpdate(), PQexecPrepared(), and sendCommand().

1383 {
1384  if (!PQsendQueryStart(conn))
1385  return 0;
1386 
1387  /* check the arguments */
1388  if (!stmtName)
1389  {
1391  libpq_gettext("statement name is a null pointer\n"));
1392  return 0;
1393  }
1394  if (nParams < 0 || nParams > 65535)
1395  {
1397  libpq_gettext("number of parameters must be between 0 and 65535\n"));
1398  return 0;
1399  }
1400 
1401  return PQsendQueryGuts(conn,
1402  NULL, /* no command to parse */
1403  stmtName,
1404  nParams,
1405  NULL, /* no param types */
1406  paramValues,
1407  paramLengths,
1408  paramFormats,
1409  resultFormat);
1410 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
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:1457
static bool PQsendQueryStart(PGconn *conn)
Definition: fe-exec.c:1416
PQExpBufferData errorMessage
Definition: libpq-int.h:493
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ PQsendQueryStart()

static bool PQsendQueryStart ( PGconn conn)
static

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

1417 {
1418  if (!conn)
1419  return false;
1420 
1421  /* clear the error string */
1423 
1424  /* Don't try to send if we know there's no live connection. */
1425  if (conn->status != CONNECTION_OK)
1426  {
1428  libpq_gettext("no connection to the server\n"));
1429  return false;
1430  }
1431  /* Can't send while already busy, either. */
1432  if (conn->asyncStatus != PGASYNC_IDLE)
1433  {
1435  libpq_gettext("another command is already in progress\n"));
1436  return false;
1437  }
1438 
1439  /* initialize async result-accumulation state */
1440  pqClearAsyncResult(conn);
1441 
1442  /* reset single-row processing mode */
1443  conn->singleRowMode = false;
1444 
1445  /* ready to send command message */
1446  return true;
1447 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
bool singleRowMode
Definition: libpq-int.h:388
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:380
PQExpBufferData errorMessage
Definition: libpq-int.h:493
ConnStatusType status
Definition: libpq-int.h:379
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:726
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ PQsetnonblocking()

int PQsetnonblocking ( PGconn conn,
int  arg 
)

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

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

3187 {
3188  bool barg;
3189 
3190  if (!conn || conn->status == CONNECTION_BAD)
3191  return -1;
3192 
3193  barg = (arg ? true : false);
3194 
3195  /* early out if the socket is already in the state requested */
3196  if (barg == conn->nonblocking)
3197  return 0;
3198 
3199  /*
3200  * to guarantee constancy for flushing/query/result-polling behavior we
3201  * need to flush the send queue at this point in order to guarantee proper
3202  * behavior. this is ok because either they are making a transition _from_
3203  * or _to_ blocking mode, either way we can block them.
3204  */
3205  /* if we are going from blocking to non-blocking flush here */
3206  if (pqFlush(conn))
3207  return -1;
3208 
3209  conn->nonblocking = barg;
3210 
3211  return 0;
3212 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:961
#define true
Definition: c.h:251
ConnStatusType status
Definition: libpq-int.h:379
bool nonblocking
Definition: libpq-int.h:386
void * arg

◆ PQsetResultAttrs()

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

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

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

◆ pqSetResultError()

void pqSetResultError ( PGresult res,
const char *  msg 
)

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

References pg_result::errMsg, and pqResultStrdup().

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

638 {
639  if (!res)
640  return;
641  if (msg && *msg)
642  res->errMsg = pqResultStrdup(res, msg);
643  else
644  res->errMsg = NULL;
645 }
char * errMsg
Definition: libpq-int.h:196
char * pqResultStrdup(PGresult *res, const char *str)
Definition: fe-exec.c:623

◆ PQsetSingleRowMode()

int PQsetSingleRowMode ( PGconn conn)

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

1656 {
1657  /*
1658  * Only allow setting the flag when we have launched a query and not yet
1659  * received any results.
1660  */
1661  if (!conn)
1662  return 0;
1663  if (conn->asyncStatus != PGASYNC_BUSY)
1664  return 0;
1665  if (conn->queryclass != PGQUERY_SIMPLE &&
1666  conn->queryclass != PGQUERY_EXTENDED)
1667  return 0;
1668  if (conn->result)
1669  return 0;
1670 
1671  /* OK, set flag */
1672  conn->singleRowMode = true;
1673  return 1;
1674 }
bool singleRowMode
Definition: libpq-int.h:388
PGQueryClass queryclass
Definition: libpq-int.h:382
PGresult * result
Definition: libpq-int.h:450
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:380

◆ PQsetvalue()

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

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

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

◆ PQunescapeBytea()

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

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

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

Referenced by dumpTrigger().

3707 {
3708  size_t strtextlen,
3709  buflen;
3710  unsigned char *buffer,
3711  *tmpbuf;
3712  size_t i,
3713  j;
3714 
3715  if (strtext == NULL)
3716  return NULL;
3717 
3718  strtextlen = strlen((const char *) strtext);
3719 
3720  if (strtext[0] == '\\' && strtext[1] == 'x')
3721  {
3722  const unsigned char *s;
3723  unsigned char *p;
3724 
3725  buflen = (strtextlen - 2) / 2;
3726  /* Avoid unportable malloc(0) */
3727  buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
3728  if (buffer == NULL)
3729  return NULL;
3730 
3731  s = strtext + 2;
3732  p = buffer;
3733  while (*s)
3734  {
3735  char v1,
3736  v2;
3737 
3738  /*
3739  * Bad input is silently ignored. Note that this includes
3740  * whitespace between hex pairs, which is allowed by byteain.
3741  */
3742  v1 = get_hex(*s++);
3743  if (!*s || v1 == (char) -1)
3744  continue;
3745  v2 = get_hex(*s++);
3746  if (v2 != (char) -1)
3747  *p++ = (v1 << 4) | v2;
3748  }
3749 
3750  buflen = p - buffer;
3751  }
3752  else
3753  {
3754  /*
3755  * Length of input is max length of output, but add one to avoid
3756  * unportable malloc(0) if input is zero-length.
3757  */
3758  buffer = (unsigned char *) malloc(strtextlen + 1);
3759  if (buffer == NULL)
3760  return NULL;
3761 
3762  for (i = j = 0; i < strtextlen;)
3763  {
3764  switch (strtext[i])
3765  {
3766  case '\\':
3767  i++;
3768  if (strtext[i] == '\\')
3769  buffer[j++] = strtext[i++];
3770  else
3771  {
3772  if ((ISFIRSTOCTDIGIT(strtext[i])) &&
3773  (ISOCTDIGIT(strtext[i + 1])) &&
3774  (ISOCTDIGIT(strtext[i + 2])))
3775  {
3776  int byte;
3777 
3778  byte = OCTVAL(strtext[i++]);
3779  byte = (byte << 3) + OCTVAL(strtext[i++]);
3780  byte = (byte << 3) + OCTVAL(strtext[i++]);
3781