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

Go to the source code of this file.

Macros

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

Functions

static PGEventdupEvents (PGEvent *events, int count, size_t *memSize)
 
static bool pqAddTuple (PGresult *res, PGresAttValue *tup, const char **errmsgp)
 
static int PQsendQueryInternal (PGconn *conn, const char *query, bool newQuery)
 
static bool PQsendQueryStart (PGconn *conn, bool newQuery)
 
static int PQsendQueryGuts (PGconn *conn, const char *command, const char *stmtName, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
static void parseInput (PGconn *conn)
 
static PGresultgetCopyResult (PGconn *conn, ExecStatusType copytype)
 
static bool PQexecStart (PGconn *conn)
 
static PGresultPQexecFinish (PGconn *conn)
 
static int PQsendDescribe (PGconn *conn, char desc_type, const char *desc_target)
 
static int check_field_number (const PGresult *res, int field_num)
 
PGresultPQmakeEmptyPGresult (PGconn *conn, ExecStatusType status)
 
int PQsetResultAttrs (PGresult *res, int numAttributes, PGresAttDesc *attDescs)
 
PGresultPQcopyResult (const PGresult *src, int flags)
 
int PQsetvalue (PGresult *res, int tup_num, int field_num, char *value, int len)
 
void * PQresultAlloc (PGresult *res, size_t nBytes)
 
void * pqResultAlloc (PGresult *res, size_t nBytes, bool isBinary)
 
size_t PQresultMemorySize (const PGresult *res)
 
char * pqResultStrdup (PGresult *res, const char *str)
 
void pqSetResultError (PGresult *res, const char *msg)
 
void PQclear (PGresult *res)
 
void pqClearAsyncResult (PGconn *conn)
 
void pqSaveErrorResult (PGconn *conn)
 
static void pqSaveWriteError (PGconn *conn)
 
PGresultpqPrepareAsyncResult (PGconn *conn)
 
void pqInternalNotice (const PGNoticeHooks *hooks, const char *fmt,...)
 
void pqSaveMessageField (PGresult *res, char code, const char *value)
 
void pqSaveParameterStatus (PGconn *conn, const char *name, const char *value)
 
int pqRowProcessor (PGconn *conn, const char **errmsgp)
 
int PQsendQuery (PGconn *conn, const char *query)
 
int PQsendQueryContinue (PGconn *conn, const char *query)
 
int PQsendQueryParams (PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
int PQsendPrepare (PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
 
int PQsendQueryPrepared (PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
int PQsetSingleRowMode (PGconn *conn)
 
int PQconsumeInput (PGconn *conn)
 
int PQisBusy (PGconn *conn)
 
PGresultPQgetResult (PGconn *conn)
 
PGresultPQexec (PGconn *conn, const char *query)
 
PGresultPQexecParams (PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
PGresultPQprepare (PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
 
PGresultPQexecPrepared (PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
PGresultPQdescribePrepared (PGconn *conn, const char *stmt)
 
PGresultPQdescribePortal (PGconn *conn, const char *portal)
 
int PQsendDescribePrepared (PGconn *conn, const char *stmt)
 
int PQsendDescribePortal (PGconn *conn, const char *portal)
 
PGnotifyPQnotifies (PGconn *conn)
 
int PQputCopyData (PGconn *conn, const char *buffer, int nbytes)
 
int PQputCopyEnd (PGconn *conn, const char *errormsg)
 
int PQgetCopyData (PGconn *conn, char **buffer, int async)
 
int PQgetline (PGconn *conn, char *s, int maxlen)
 
int PQgetlineAsync (PGconn *conn, char *buffer, int bufsize)
 
int PQputline (PGconn *conn, const char *s)
 
int PQputnbytes (PGconn *conn, const char *buffer, int nbytes)
 
int PQendcopy (PGconn *conn)
 
PGresultPQfn (PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
 
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 3705 of file fe-exec.c.

Referenced by PQunescapeBytea().

◆ ISOCTDIGIT

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

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

Referenced by PQunescapeBytea().

◆ OCTVAL

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

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

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

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

Referenced by PQparamtype().

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

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

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

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

◆ dupEvents()

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

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

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

Referenced by PQcopyResult(), and PQmakeEmptyPGresult().

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

◆ get_hex()

static char get_hex ( char  c)
inlinestatic

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

References hexlookup.

Referenced by PQunescapeBytea().

3559 {
3560  int res = -1;
3561 
3562  if (c > 0 && c < 127)
3563  res = hexlookup[(unsigned char) c];
3564 
3565  return (char) res;
3566 }
static const int8 hexlookup[128]
Definition: fe-exec.c:3546
char * c

◆ getCopyResult()

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

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

1870 {
1871  /*
1872  * If the server connection has been lost, don't pretend everything is
1873  * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
1874  * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
1875  * error in the earlier steps in PQgetResult). The text returned in the
1876  * result is whatever is in conn->errorMessage; we hope that was filled
1877  * with something relevant when the lost connection was detected.
1878  */
1879  if (conn->status != CONNECTION_OK)
1880  {
1881  pqSaveErrorResult(conn);
1882  conn->asyncStatus = PGASYNC_IDLE;
1883  return pqPrepareAsyncResult(conn);
1884  }
1885 
1886  /* If we have an async result for the COPY, return that */
1887  if (conn->result && conn->result->resultStatus == copytype)
1888  return pqPrepareAsyncResult(conn);
1889 
1890  /* Otherwise, invent a suitable PGresult */
1891  return PQmakeEmptyPGresult(conn, copytype);
1892 }
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:786
PGresult * result
Definition: libpq-int.h:465
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:389
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:142
ConnStatusType status
Definition: libpq-int.h:388
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:747
ExecStatusType resultStatus
Definition: libpq-int.h:177

◆ parseInput()

static void parseInput ( PGconn conn)
static

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

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

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

1709 {
1710  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1711  pqParseInput3(conn);
1712  else
1713  pqParseInput2(conn);
1714 }
void pqParseInput2(PGconn *conn)
Definition: fe-protocol2.c:405
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:113
ProtocolVersion pversion
Definition: libpq-int.h:414
void pqParseInput3(PGconn *conn)
Definition: fe-protocol3.c:63

◆ pqAddTuple()

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

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

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

Referenced by pqRowProcessor(), and PQsetvalue().

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

◆ PQbinaryTuples()

int PQbinaryTuples ( const PGresult res)

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

References pg_result::binary.

Referenced by ProcessResult().

2745 {
2746  if (!res)
2747  return 0;
2748  return res->binary;
2749 }
int binary
Definition: libpq-int.h:179

◆ PQclear()

void PQclear ( PGresult res)

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

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

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

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

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

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

732 {
733  if (conn->result)
734  PQclear(conn->result);
735  conn->result = NULL;
736  if (conn->next_result)
737  PQclear(conn->next_result);
738  conn->next_result = NULL;
739 }
PGresult * result
Definition: libpq-int.h:465
PGresult * next_result
Definition: libpq-int.h:466
void PQclear(PGresult *res)
Definition: fe-exec.c:676

◆ PQcmdStatus()

char* PQcmdStatus ( PGresult res)

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

References pg_result::cmdStatus.

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

3000 {
3001  if (!res)
3002  return NULL;
3003  return res->cmdStatus;
3004 }
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178

◆ PQcmdTuples()

char* PQcmdTuples ( PGresult res)

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

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

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

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

◆ PQconsumeInput()

int PQconsumeInput ( PGconn conn)

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

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

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

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

◆ PQcopyResult()

PGresult* PQcopyResult ( const PGresult src,
int  flags 
)

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

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

Referenced by pqRowProcessor().

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

◆ 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:2068
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1989

◆ PQendcopy()

int PQendcopy ( PGconn conn)

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

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

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

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

◆ PQescapeBytea()

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

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

References PQescapeByteaInternal(), and static_std_strings.

3698 {
3699  return PQescapeByteaInternal(NULL, from, from_length, to_length,
3701  false /* can't use hex */ );
3702 }
static bool static_std_strings
Definition: fe-exec.c:50
static unsigned char * PQescapeByteaInternal(PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length, bool std_strings, bool use_hex)
Definition: fe-exec.c:3585

◆ PQescapeByteaConn()

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

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

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

3685 {
3686  if (!conn)
3687  return NULL;
3688 
3690 
3691  return PQescapeByteaInternal(conn, from, from_length, to_length,
3692  conn->std_strings,
3693  (conn->sversion >= 90000));
3694 }
int sversion
Definition: libpq-int.h:415
PQExpBufferData errorMessage
Definition: libpq-int.h:530
bool std_strings
Definition: libpq-int.h:438
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
static unsigned char * PQescapeByteaInternal(PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length, bool std_strings, bool use_hex)
Definition: fe-exec.c:3585

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

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

Referenced by PQescapeBytea(), and PQescapeByteaConn().

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

◆ PQescapeIdentifier()

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

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

References PQescapeInternal().

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

3539 {
3540  return PQescapeInternal(conn, str, len, true);
3541 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:3409

◆ PQescapeInternal()

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

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

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

Referenced by PQescapeIdentifier(), and PQescapeLiteral().

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

◆ PQescapeLiteral()

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

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

References PQescapeInternal().

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

3533 {
3534  return PQescapeInternal(conn, str, len, false);
3535 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:3409

◆ PQescapeString()

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

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

References PQescapeStringInternal(), static_client_encoding, and static_std_strings.

Referenced by get_comma_elts(), and quote_postgres().

3395 {
3396  return PQescapeStringInternal(NULL, to, from, length, NULL,
3399 }
static bool static_std_strings
Definition: fe-exec.c:50
static int static_client_encoding
Definition: fe-exec.c:49
static size_t PQescapeStringInternal(PGconn *conn, char *to, const char *from, size_t length, int *error, int encoding, bool std_strings)
Definition: fe-exec.c:3298

◆ PQescapeStringConn()

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

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

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

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

3376 {
3377  if (!conn)
3378  {
3379  /* force empty-string result */
3380  *to = '\0';
3381  if (error)
3382  *error = 1;
3383  return 0;
3384  }
3385 
3387 
3388  return PQescapeStringInternal(conn, to, from, length, error,
3389  conn->client_encoding,
3390  conn->std_strings);
3391 }
static void error(void)
Definition: sql-dyntest.c:147
PQExpBufferData errorMessage
Definition: libpq-int.h:530
bool std_strings
Definition: libpq-int.h:438
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:3298
int client_encoding
Definition: libpq-int.h:437
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148

◆ PQescapeStringInternal()

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

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

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

Referenced by PQescapeString(), and PQescapeStringConn().

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

◆ PQexec()

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

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

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

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

1908 {
1909  if (!PQexecStart(conn))
1910  return NULL;
1911  if (!PQsendQuery(conn, query))
1912  return NULL;
1913  return PQexecFinish(conn);
1914 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1187
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2068
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1989

◆ PQexecFinish()

static PGresult * PQexecFinish ( PGconn conn)
static

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

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

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

2069 {
2070  PGresult *result;
2071  PGresult *lastResult;
2072 
2073  /*
2074  * For backwards compatibility, return the last result if there are more
2075  * than one. (We used to have logic here to concatenate successive error
2076  * messages, but now that happens automatically, since conn->errorMessage
2077  * will continue to accumulate errors throughout this loop.)
2078  *
2079  * We have to stop if we see copy in/out/both, however. We will resume
2080  * parsing after application performs the data transfer.
2081  *
2082  * Also stop if the connection is lost (else we'll loop infinitely).
2083  */
2084  lastResult = NULL;
2085  while ((result = PQgetResult(conn)) != NULL)
2086  {
2087  if (lastResult)
2088  PQclear(lastResult);
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 PQclear(PGresult *res)
Definition: fe-exec.c:676
ConnStatusType status
Definition: libpq-int.h:388
ExecStatusType resultStatus
Definition: libpq-int.h:177
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1746

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

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

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

1929 {
1930  if (!PQexecStart(conn))
1931  return NULL;
1932  if (!PQsendQueryParams(conn, command,
1933  nParams, paramTypes, paramValues, paramLengths,
1934  paramFormats, resultFormat))
1935  return NULL;
1936  return PQexecFinish(conn);
1937 }
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:1250
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2068
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1989

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

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

Referenced by ecpg_execute(), and try_complete_step().

1975 {
1976  if (!PQexecStart(conn))
1977  return NULL;
1978  if (!PQsendQueryPrepared(conn, stmtName,
1979  nParams, paramValues, paramLengths,
1980  paramFormats, resultFormat))
1981  return NULL;
1982  return PQexecFinish(conn);
1983 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2068
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:1392
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1989

◆ PQexecStart()

static bool PQexecStart ( PGconn conn)
static

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

References appendPQExpBufferStr(), 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(), pg_conn::pversion, resetPQExpBuffer(), pg_result::resultStatus, and pg_conn::status.

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

1990 {
1991  PGresult *result;
1992 
1993  if (!conn)
1994  return false;
1995 
1996  /*
1997  * Since this is the beginning of a query cycle, reset the error buffer.
1998  */
2000 
2001  /*
2002  * Silently discard any prior query result that application didn't eat.
2003  * This is probably poor design, but it's here for backward compatibility.
2004  */
2005  while ((result = PQgetResult(conn)) != NULL)
2006  {
2007  ExecStatusType resultStatus = result->resultStatus;
2008 
2009  PQclear(result); /* only need its status */
2010  if (resultStatus == PGRES_COPY_IN)
2011  {
2012  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2013  {
2014  /* In protocol 3, we can get out of a COPY IN state */
2015  if (PQputCopyEnd(conn,
2016  libpq_gettext("COPY terminated by new PQexec")) < 0)
2017  return false;
2018  /* keep waiting to swallow the copy's failure message */
2019  }
2020  else
2021  {
2022  /* In older protocols we have to punt */
2024  libpq_gettext("COPY IN state must be terminated first\n"));
2025  return false;
2026  }
2027  }
2028  else if (resultStatus == PGRES_COPY_OUT)
2029  {
2030  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2031  {
2032  /*
2033  * In protocol 3, we can get out of a COPY OUT state: we just
2034  * switch back to BUSY and allow the remaining COPY data to be
2035  * dropped on the floor.
2036  */
2037  conn->asyncStatus = PGASYNC_BUSY;
2038  /* keep waiting to swallow the copy's completion message */
2039  }
2040  else
2041  {
2042  /* In older protocols we have to punt */
2044  libpq_gettext("COPY OUT state must be terminated first\n"));
2045  return false;
2046  }
2047  }
2048  else if (resultStatus == PGRES_COPY_BOTH)
2049  {
2050  /* We don't allow PQexec during COPY BOTH */
2052  libpq_gettext("PQexec not allowed during COPY BOTH\n"));
2053  return false;
2054  }
2055  /* check for loss of connection, too */
2056  if (conn->status == CONNECTION_BAD)
2057  return false;
2058  }
2059 
2060  /* OK to send a command */
2061  return true;
2062 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2342
ExecStatusType
Definition: libpq-fe.h:84
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:113
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:389
PQExpBufferData errorMessage
Definition: libpq-int.h:530
void PQclear(PGresult *res)
Definition: fe-exec.c:676
ProtocolVersion pversion
Definition: libpq-int.h:414
ConnStatusType status
Definition: libpq-int.h:388
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
ExecStatusType resultStatus
Definition: libpq-int.h:177
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1746
#define libpq_gettext(x)
Definition: libpq-int.h:809

◆ PQfformat()

int PQfformat ( const PGresult res,
int  field_num 
)

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

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

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

2956 {
2957  if (!check_field_number(res, field_num))
2958  return 0;
2959  if (res->attDescs)
2960  return res->attDescs[field_num].format;
2961  else
2962  return 0;
2963 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2757

◆ PQflush()

int PQflush ( PGconn conn)

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

References pqFlush().

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

3247 {
3248  return pqFlush(conn);
3249 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:1012

◆ PQfmod()

int PQfmod ( const PGresult res,
int  field_num 
)

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

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

Referenced by DescribeQuery(), and ECPGget_desc().

2989 {
2990  if (!check_field_number(res, field_num))
2991  return 0;
2992  if (res->attDescs)
2993  return res->attDescs[field_num].atttypmod;
2994  else
2995  return 0;
2996 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
int atttypmod
Definition: libpq-fe.h:246
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2757

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

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

2616 {
2617  *result_len = 0;
2618 
2619  if (!conn)
2620  return NULL;
2621 
2622  /*
2623  * Since this is the beginning of a query cycle, reset the error buffer.
2624  */
2626 
2627  if (conn->sock == PGINVALID_SOCKET || conn->asyncStatus != PGASYNC_IDLE ||
2628  conn->result != NULL)
2629  {
2631  libpq_gettext("connection in wrong state\n"));
2632  return NULL;
2633  }
2634 
2635  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2636  return pqFunctionCall3(conn, fnid,
2637  result_buf, result_len,
2638  result_is_int,
2639  args, nargs);
2640  else
2641  return pqFunctionCall2(conn, fnid,
2642  result_buf, result_len,
2643  result_is_int,
2644  args, nargs);
2645 }
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)
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:113
PGresult * result
Definition: libpq-int.h:465
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:389
pgsocket sock
Definition: libpq-int.h:410
#define PGINVALID_SOCKET
Definition: port.h:33
PQExpBufferData errorMessage
Definition: libpq-int.h:530
ProtocolVersion pversion
Definition: libpq-int.h:414
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
#define libpq_gettext(x)
Definition: libpq-int.h:809

◆ PQfname()

char* PQfname ( const PGresult res,
int  field_num 
)

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

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

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

2815 {
2816  if (!check_field_number(res, field_num))
2817  return NULL;
2818  if (res->attDescs)
2819  return res->attDescs[field_num].name;
2820  else
2821  return NULL;
2822 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2757
char * name
Definition: libpq-fe.h:240

◆ PQfnumber()

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

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

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

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

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

◆ PQfreemem()

◆ PQfreeNotify()

void PQfreeNotify ( PGnotify notify)

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

References PQfreemem().

Referenced by PQfreemem().

3277 {
3278  PQfreemem(notify);
3279 }
void PQfreemem(void *ptr)
Definition: fe-exec.c:3259

◆ PQfsize()

int PQfsize ( const PGresult res,
int  field_num 
)

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

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

Referenced by ecpg_build_compat_sqlda(), and ECPGget_desc().

2978 {
2979  if (!check_field_number(res, field_num))
2980  return 0;
2981  if (res->attDescs)
2982  return res->attDescs[field_num].typlen;
2983  else
2984  return 0;
2985 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2757

◆ PQftable()

Oid PQftable ( const PGresult res,
int  field_num 
)

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

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

2934 {
2935  if (!check_field_number(res, field_num))
2936  return InvalidOid;
2937  if (res->attDescs)
2938  return res->attDescs[field_num].tableid;
2939  else
2940  return InvalidOid;
2941 }
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:2757

◆ PQftablecol()

int PQftablecol ( const PGresult res,
int  field_num 
)

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

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

2945 {
2946  if (!check_field_number(res, field_num))
2947  return 0;
2948  if (res->attDescs)
2949  return res->attDescs[field_num].columnid;
2950  else
2951  return 0;
2952 }
int columnid
Definition: libpq-fe.h:242
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2757

◆ PQftype()

Oid PQftype ( const PGresult res,
int  field_num 
)

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

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

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

2967 {
2968  if (!check_field_number(res, field_num))
2969  return InvalidOid;
2970  if (res->attDescs)
2971  return res->attDescs[field_num].typid;
2972  else
2973  return InvalidOid;
2974 }
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:2757

◆ PQgetCopyData()

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

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

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

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

2431 {
2432  *buffer = NULL; /* for all failure cases */
2433  if (!conn)
2434  return -2;
2435  if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2436  conn->asyncStatus != PGASYNC_COPY_BOTH)
2437  {
2439  libpq_gettext("no COPY in progress\n"));
2440  return -2;
2441  }
2442  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2443  return pqGetCopyData3(conn, buffer, async);
2444  else
2445  return pqGetCopyData2(conn, buffer, async);
2446 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:113
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:389
int pqGetCopyData3(PGconn *conn, char **buffer, int async)
PQExpBufferData errorMessage
Definition: libpq-int.h:530
ProtocolVersion pversion
Definition: libpq-int.h:414
int pqGetCopyData2(PGconn *conn, char **buffer, int async)
#define libpq_gettext(x)
Definition: libpq-int.h:809

◆ PQgetisnull()

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

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

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

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

3148 {
3149  if (!check_tuple_field_number(res, tup_num, field_num))
3150  return 1; /* pretend it is null */
3151  if (res->tuples[tup_num][field_num].len == NULL_LEN)
3152  return 1;
3153  else
3154  return 0;
3155 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:2772
#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 3133 of file fe-exec.c.

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

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

3134 {
3135  if (!check_tuple_field_number(res, tup_num, field_num))
3136  return 0;
3137  if (res->tuples[tup_num][field_num].len != NULL_LEN)
3138  return res->tuples[tup_num][field_num].len;
3139  else
3140  return 0;
3141 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:2772
#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 2472 of file fe-exec.c.

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

2473 {
2474  if (!s || maxlen <= 0)
2475  return EOF;
2476  *s = '\0';
2477  /* maxlen must be at least 3 to hold the \. terminator! */
2478  if (maxlen < 3)
2479  return EOF;
2480 
2481  if (!conn)
2482  return EOF;
2483 
2484  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2485  return pqGetline3(conn, s, maxlen);
2486  else
2487  return pqGetline2(conn, s, maxlen);
2488 }
int pqGetline3(PGconn *conn, char *s, int maxlen)
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:113
int pqGetline2(PGconn *conn, char *s, int maxlen)
ProtocolVersion pversion
Definition: libpq-int.h:414

◆ PQgetlineAsync()

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

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

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

Referenced by pqGetline3().

2523 {
2524  if (!conn)
2525  return -1;
2526 
2527  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2528  return pqGetlineAsync3(conn, buffer, bufsize);
2529  else
2530  return pqGetlineAsync2(conn, buffer, bufsize);
2531 }
int pqGetlineAsync2(PGconn *conn, char *buffer, int bufsize)
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:113
int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)
ProtocolVersion pversion
Definition: libpq-int.h:414

◆ PQgetResult()

PGresult* PQgetResult ( PGconn conn)

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

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

Referenced by BaseBackup(), consumeQueryResult(), dblink_record_internal(), dumpTableData_copy(), ecpg_process_output(), EndDBCopyMode(), handleCopyIn(), handleCopyOut(), HandleEndOfCopyStream(), libpqrcv_PQgetResult(), ParallelSlotsGetIdle(), pgfdw_get_cleanup_result(), pgfdw_get_result(), PQconnectPoll(), pqEndcopy2(), pqEndcopy3(), PQexecFinish(), PQexecStart(), pqSetenvPoll(), process_queued_fetch_requests(), ProcessResult(), readCommandResponse(), ReceiveCopyData(), ReceiveXlogStream(), storeQueryResult(), StreamLogicalLog(), and try_complete_step().

1747 {
1748  PGresult *res;
1749 
1750  if (!conn)
1751  return NULL;
1752 
1753  /* Parse any available data, if our state permits. */
1754  parseInput(conn);
1755 
1756  /* If not ready to return something, block until we are. */
1757  while (conn->asyncStatus == PGASYNC_BUSY)
1758  {
1759  int flushResult;
1760 
1761  /*
1762  * If data remains unsent, send it. Else we might be waiting for the
1763  * result of a command the backend hasn't even got yet.
1764  */
1765  while ((flushResult = pqFlush(conn)) > 0)
1766  {
1767  if (pqWait(false, true, conn))
1768  {
1769  flushResult = -1;
1770  break;
1771  }
1772  }
1773 
1774  /*
1775  * Wait for some more data, and load it. (Note: if the connection has
1776  * been lost, pqWait should return immediately because the socket
1777  * should be read-ready, either with the last server data or with an
1778  * EOF indication. We expect therefore that this won't result in any
1779  * undue delay in reporting a previous write failure.)
1780  */
1781  if (flushResult ||
1782  pqWait(true, false, conn) ||
1783  pqReadData(conn) < 0)
1784  {
1785  /*
1786  * conn->errorMessage has been set by pqWait or pqReadData. We
1787  * want to append it to any already-received error message.
1788  */
1789  pqSaveErrorResult(conn);
1790  conn->asyncStatus = PGASYNC_IDLE;
1791  return pqPrepareAsyncResult(conn);
1792  }
1793 
1794  /* Parse it. */
1795  parseInput(conn);
1796 
1797  /*
1798  * If we had a write error, but nothing above obtained a query result
1799  * or detected a read error, report the write error.
1800  */
1801  if (conn->write_failed && conn->asyncStatus == PGASYNC_BUSY)
1802  {
1803  pqSaveWriteError(conn);
1804  conn->asyncStatus = PGASYNC_IDLE;
1805  return pqPrepareAsyncResult(conn);
1806  }
1807  }
1808 
1809  /* Return the appropriate thing. */
1810  switch (conn->asyncStatus)
1811  {
1812  case PGASYNC_IDLE:
1813  res = NULL; /* query is complete */
1814  break;
1815  case PGASYNC_READY:
1816  res = pqPrepareAsyncResult(conn);
1817  /* Set the state back to BUSY, allowing parsing to proceed. */
1818  conn->asyncStatus = PGASYNC_BUSY;
1819  break;
1820  case PGASYNC_COPY_IN:
1821  res = getCopyResult(conn, PGRES_COPY_IN);
1822  break;
1823  case PGASYNC_COPY_OUT:
1824  res = getCopyResult(conn, PGRES_COPY_OUT);
1825  break;
1826  case PGASYNC_COPY_BOTH:
1827  res = getCopyResult(conn, PGRES_COPY_BOTH);
1828  break;
1829  default:
1831  libpq_gettext("unexpected asyncStatus: %d\n"),
1832  (int) conn->asyncStatus);
1834  break;
1835  }
1836 
1837  if (res)
1838  {
1839  int i;
1840 
1841  for (i = 0; i < res->nEvents; i++)
1842  {
1843  PGEventResultCreate evt;
1844 
1845  evt.conn = conn;
1846  evt.result = res;
1847  if (!res->events[i].proc(PGEVT_RESULTCREATE, &evt,
1848  res->events[i].passThrough))
1849  {
1851  libpq_gettext("PGEventProc \"%s\" failed during PGEVT_RESULTCREATE event\n"),
1852  res->events[i].name);
1853  pqSetResultError(res, conn->errorMessage.data);
1855  break;
1856  }
1857  res->events[i].resultInitialized = true;
1858  }
1859  }
1860 
1861  return res;
1862 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:1012
bool resultInitialized
Definition: libpq-int.h:164
int nEvents
Definition: libpq-int.h:188
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:786
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:389
bool write_failed
Definition: libpq-int.h:420
PGconn * conn
Definition: streamutil.c:54
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
int pqReadData(PGconn *conn)
Definition: fe-misc.c:615
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:1035
static PGresult * getCopyResult(PGconn *conn, ExecStatusType copytype)
Definition: fe-exec.c:1869
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:142
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1708
PQExpBufferData errorMessage
Definition: libpq-int.h:530
void pqSetResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:661
PGEventProc proc
Definition: libpq-int.h:160
static void pqSaveWriteError(PGconn *conn)
Definition: fe-exec.c:759
int i
void * passThrough
Definition: libpq-int.h:162
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:747
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:809

◆ PQgetvalue()

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

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

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

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

3123 {
3124  if (!check_tuple_field_number(res, tup_num, field_num))
3125  return NULL;
3126  return res->tuples[tup_num][field_num].value;
3127 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:2772
PGresAttValue ** tuples
Definition: libpq-int.h:172
char * value
Definition: libpq-int.h:138

◆ pqInternalNotice()

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

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

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

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

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

◆ PQisBusy()

int PQisBusy ( PGconn conn)

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

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

Referenced by advanceConnectionState(), dblink_is_busy(), libpqrcv_PQgetResult(), ParallelSlotsGetIdle(), pgfdw_get_cleanup_result(), pgfdw_get_result(), PQconnectPoll(), pqEndcopy2(), pqEndcopy3(), pqSetenvPoll(), and try_complete_step().

1723 {
1724  if (!conn)
1725  return false;
1726 
1727  /* Parse any available data, if our state permits. */
1728  parseInput(conn);
1729 
1730  /*
1731  * PQgetResult will return immediately in all states except BUSY, or if we
1732  * had a write failure.
1733  */
1734  return conn->asyncStatus == PGASYNC_BUSY || conn->write_failed;
1735 }
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:389
bool write_failed
Definition: libpq-int.h:420
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1708

◆ PQisnonblocking()

int PQisnonblocking ( const PGconn conn)

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

References pqIsnonblocking.

3228 {
3229  return pqIsnonblocking(conn);
3230 }
#define pqIsnonblocking(conn)
Definition: libpq-int.h:803

◆ PQisthreadsafe()

int PQisthreadsafe ( void  )

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

3235 {
3236 #ifdef ENABLE_THREAD_SAFETY
3237  return true;
3238 #else
3239  return false;
3240 #endif
3241 }

◆ 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::memorySize, pg_result::nEvents, pg_conn::nEvents, pg_result::noticeHooks, pg_conn::noticeHooks, PGNoticeHooks::noticeProc, PGNoticeHooks::noticeProcArg, PGNoticeHooks::noticeRec, PGNoticeHooks::noticeRecArg, pg_result::ntups, pg_result::null_field, pg_result::numAttributes, pg_result::numParameters, pg_result::paramDescs, PG_SQL_ASCII, PGRES_COMMAND_OK, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_EMPTY_QUERY, PGRES_SINGLE_TUPLE, PGRES_TUPLES_OK, PQclear(), pqSetResultError(), pg_result::resultStatus, pg_result::spaceLeft, status(), pg_result::tupArrSize, and pg_result::tuples.

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

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  result->memorySize = sizeof(PGresult);
170 
171  if (conn)
172  {
173  /* copy connection data we might need for operations on PGresult */
174  result->noticeHooks = conn->noticeHooks;
175  result->client_encoding = conn->client_encoding;
176 
177  /* consider copying conn's errorMessage */
178  switch (status)
179  {
180  case PGRES_EMPTY_QUERY:
181  case PGRES_COMMAND_OK:
182  case PGRES_TUPLES_OK:
183  case PGRES_COPY_OUT:
184  case PGRES_COPY_IN:
185  case PGRES_COPY_BOTH:
186  case PGRES_SINGLE_TUPLE:
187  /* non-error cases */
188  break;
189  default:
190  pqSetResultError(result, conn->errorMessage.data);
191  break;
192  }
193 
194  /* copy events last; result must be valid if we need to PQclear */
195  if (conn->nEvents > 0)
196  {
197  result->events = dupEvents(conn->events, conn->nEvents,
198  &result->memorySize);
199  if (!result->events)
200  {
201  PQclear(result);
202  return NULL;
203  }
204  result->nEvents = conn->nEvents;
205  }
206  }
207  else
208  {
209  /* defaults... */
210  result->noticeHooks.noticeRec = NULL;
211  result->noticeHooks.noticeRecArg = NULL;
212  result->noticeHooks.noticeProc = NULL;
213  result->noticeHooks.noticeProcArg = NULL;
214  result->client_encoding = PG_SQL_ASCII;
215  }
216 
217  return result;
218 }
size_t memorySize
Definition: libpq-int.h:212
PGMessageField * errFields
Definition: libpq-int.h:197
PGEvent * events
Definition: libpq-int.h:383
int tupArrSize
Definition: libpq-int.h:174
int spaceLeft
Definition: libpq-int.h:210
int nEvents
Definition: libpq-int.h:188
char * errMsg
Definition: libpq-int.h:196
char null_field[1]
Definition: libpq-int.h:201
PGresAttDesc * attDescs
Definition: libpq-int.h:171
PGresAttValue ** tuples
Definition: libpq-int.h:172
#define malloc(a)
Definition: header.h:50
struct pg_result PGresult
Definition: libpq-fe.h:150
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
PGNoticeHooks noticeHooks
Definition: libpq-int.h:380
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:530
void pqSetResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:661
void PQclear(PGresult *res)
Definition: fe-exec.c:676
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:384
int client_encoding
Definition: libpq-int.h:437
static PGEvent * dupEvents(PGEvent *events, int count, size_t *memSize)
Definition: fe-exec.c:388
PGEvent * events
Definition: libpq-int.h:187
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
ExecStatusType resultStatus
Definition: libpq-int.h:177
void * noticeRecArg
Definition: libpq-int.h:153
int client_encoding
Definition: libpq-int.h:189

◆ PQnfields()

◆ PQnotifies()

PGnotify* PQnotifies ( PGconn conn)

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

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

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

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

◆ PQnparams()

int PQnparams ( const PGresult res)

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

References pg_result::numParameters.

3162 {
3163  if (!res)
3164  return 0;
3165  return res->numParameters;
3166 }
int numParameters
Definition: libpq-int.h:175

◆ PQntuples()

int PQntuples ( const PGresult res)

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

References pg_result::ntups.

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

2729 {
2730  if (!res)
2731  return 0;
2732  return res->ntups;
2733 }
int ntups
Definition: libpq-int.h:169

◆ PQoidStatus()

char* PQoidStatus ( const PGresult res)

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

References buf, and pg_result::cmdStatus.

3013 {
3014  /*
3015  * This must be enough to hold the result. Don't laugh, this is better
3016  * than what this function used to do.
3017  */
3018  static char buf[24];
3019 
3020  size_t len;
3021 
3022  if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
3023  return "";
3024 
3025  len = strspn(res->cmdStatus + 7, "0123456789");
3026  if (len > sizeof(buf) - 1)
3027  len = sizeof(buf) - 1;
3028  memcpy(buf, res->cmdStatus + 7, len);
3029  buf[len] = '\0';
3030 
3031  return buf;
3032 }
static char * buf
Definition: pg_test_fsync.c:68
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178

◆ PQoidValue()

Oid PQoidValue ( const PGresult res)

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

References pg_result::cmdStatus, and InvalidOid.

Referenced by ecpg_process_output(), and PrintQueryStatus().

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

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

3173 {
3174  if (!check_param_number(res, param_num))
3175  return InvalidOid;
3176  if (res->paramDescs)
3177  return res->paramDescs[param_num].typid;
3178  else
3179  return InvalidOid;
3180 }
static int check_param_number(const PGresult *res, int param_num)
Definition: fe-exec.c:2795
#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 1951 of file fe-exec.c.

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

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

1954 {
1955  if (!PQexecStart(conn))
1956  return NULL;
1957  if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
1958  return NULL;
1959  return PQexecFinish(conn);
1960 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2068
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1989
int PQsendPrepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:1295

◆ pqPrepareAsyncResult()

PGresult* pqPrepareAsyncResult ( PGconn conn)

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

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

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

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

◆ PQputCopyData()

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

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

References appendPQExpBufferStr(), 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(), and pg_conn::pversion.

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

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

◆ PQputCopyEnd()

int PQputCopyEnd ( PGconn conn,
const char *  errormsg 
)

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

References appendPQExpBufferStr(), 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(), pg_conn::pversion, and pg_conn::queryclass.

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

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

◆ PQputline()

int PQputline ( PGconn conn,
const char *  s 
)

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

References PQputnbytes().

Referenced by initGenerateDataClientSide().

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

◆ PQputnbytes()

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

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

References PQputCopyData().

Referenced by PQputline().

2553 {
2554  if (PQputCopyData(conn, buffer, nbytes) > 0)
2555  return 0;
2556  else
2557  return EOF;
2558 }
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2275

◆ PQresStatus()

char* PQresStatus ( ExecStatusType  status)

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

References libpq_gettext, pgresStatus, and status().

Referenced by try_complete_step().

2660 {
2661  if ((unsigned int) status >= sizeof pgresStatus / sizeof pgresStatus[0])
2662  return libpq_gettext("invalid ExecStatusType code");
2663  return pgresStatus[status];
2664 }
char *const pgresStatus[]
Definition: fe-exec.c:32
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define libpq_gettext(x)
Definition: libpq-int.h:809

◆ PQresultAlloc()

void* PQresultAlloc ( PGresult res,
size_t  nBytes 
)

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

References pqResultAlloc().

Referenced by PQsetResultAttrs().

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

◆ pqResultAlloc()

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

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

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

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

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

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

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

2714 {
2715  PGMessageField *pfield;
2716 
2717  if (!res)
2718  return NULL;
2719  for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
2720  {
2721  if (pfield->code == fieldcode)
2722  return pfield->contents;
2723  }
2724  return NULL;
2725 }
PGMessageField * errFields
Definition: libpq-int.h:197
struct pgMessageField * next
Definition: libpq-int.h:144
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:146

◆ PQresultErrorMessage()

char* PQresultErrorMessage ( const PGresult res)

◆ PQresultMemorySize()

size_t PQresultMemorySize ( const PGresult res)

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

References pg_result::memorySize.

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

◆ PQresultStatus()

ExecStatusType PQresultStatus ( const PGresult res)

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

References PGRES_FATAL_ERROR, and pg_result::resultStatus.

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

2652 {
2653  if (!res)
2654  return PGRES_FATAL_ERROR;
2655  return res->resultStatus;
2656 }
ExecStatusType resultStatus
Definition: libpq-int.h:177

◆ pqResultStrdup()

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

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

References pqResultAlloc().

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

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

◆ PQresultVerboseErrorMessage()

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

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

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

◆ pqRowProcessor()

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

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

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

◆ pqSaveErrorResult()

void pqSaveErrorResult ( PGconn conn)

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

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

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

748 {
749  pqClearAsyncResult(conn);
751 }
PGresult * result
Definition: libpq-int.h:465
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:142
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:731

◆ pqSaveMessageField()

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

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

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

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

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

◆ pqSaveParameterStatus()

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

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

References pg_conn::client_encoding, fprintf, free, malloc, pgParameterStatus::name, pgParameterStatus::next, pg_conn::Pfdebug, pg_char_to_encoding(), PG_SQL_ASCII, pg_conn::pstatus, static_client_encoding, static_std_strings, pg_conn::std_strings, pg_conn::sversion, and pgParameterStatus::value.

Referenced by getParameterStatus(), PQsetClientEncoding(), and pqSetenvPoll().

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

◆ pqSaveWriteError()

static void pqSaveWriteError ( PGconn conn)
static

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

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

Referenced by PQgetResult().

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

◆ PQsendDescribe()

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

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

References appendPQExpBufferStr(), pg_conn::asyncStatus, pg_conn::errorMessage, free, pg_conn::last_query, libpq_gettext, PG_PROTOCOL_MAJOR, PGASYNC_BUSY, PGQUERY_DESCRIBE, pqFlush(), pqPutc(), pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), PQsendQueryStart(), 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, true))
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  /* error message should be set up already */
2230  return 0;
2231 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:1012
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGQueryClass queryclass
Definition: libpq-int.h:391
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:505
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:113
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:389
static bool PQsendQueryStart(PGconn *conn, bool newQuery)
Definition: fe-exec.c:1432
int pqPutc(char c, PGconn *conn)
Definition: fe-misc.c:98
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:165
char * last_query
Definition: libpq-int.h:392
PQExpBufferData errorMessage
Definition: libpq-int.h:530
#define free(a)
Definition: header.h:65
ProtocolVersion pversion
Definition: libpq-int.h:414
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:573
#define libpq_gettext(x)
Definition: libpq-int.h:809

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

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

Referenced by PQprepare(), and prepare_foreign_modify().

1298 {
1299  if (!PQsendQueryStart(conn, true))
1300  return 0;
1301 
1302  /* check the arguments */
1303  if (!stmtName)
1304  {
1306  libpq_gettext("statement name is a null pointer\n"));
1307  return 0;
1308  }
1309  if (!query)
1310  {
1312  libpq_gettext("command string is a null pointer\n"));
1313  return 0;
1314  }
1315  if (nParams < 0 || nParams > 65535)
1316  {
1318  libpq_gettext("number of parameters must be between 0 and 65535\n"));
1319  return 0;
1320  }
1321 
1322  /* This isn't gonna work on a 2.0 server */
1323  if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1324  {
1326  libpq_gettext("function requires at least protocol version 3.0\n"));
1327  return 0;
1328  }
1329 
1330  /* construct the Parse message */
1331  if (pqPutMsgStart('P', false, conn) < 0 ||
1332  pqPuts(stmtName, conn) < 0 ||
1333  pqPuts(query, conn) < 0)
1334  goto sendFailed;
1335 
1336  if (nParams > 0 && paramTypes)
1337  {
1338  int i;
1339 
1340  if (pqPutInt(nParams, 2, conn) < 0)
1341  goto sendFailed;
1342  for (i = 0; i < nParams; i++)
1343  {
1344  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1345  goto sendFailed;
1346  }
1347  }
1348  else
1349  {
1350  if (pqPutInt(0, 2, conn) < 0)
1351  goto sendFailed;
1352  }
1353  if (pqPutMsgEnd(conn) < 0)
1354  goto sendFailed;
1355 
1356  /* construct the Sync message */
1357  if (pqPutMsgStart('S', false, conn) < 0 ||
1358  pqPutMsgEnd(conn) < 0)
1359  goto sendFailed;
1360 
1361  /* remember we are doing just a Parse */
1362  conn->queryclass = PGQUERY_PREPARE;
1363 
1364  /* and remember the query text too, if possible */
1365  /* if insufficient memory, last_query just winds up NULL */
1366  if (conn->last_query)
1367  free(conn->last_query);
1368  conn->last_query = strdup(query);
1369 
1370  /*
1371  * Give the data a push. In nonblock mode, don't complain if we're unable
1372  * to send it all; PQgetResult() will do any additional flushing needed.
1373  */
1374  if (pqFlush(conn) < 0)
1375  goto sendFailed;
1376 
1377  /* OK, it's launched! */
1378  conn->asyncStatus = PGASYNC_BUSY;
1379  return 1;
1380 
1381 sendFailed:
1382  /* error message should be set up already */
1383  return 0;
1384 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:1012
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGQueryClass queryclass
Definition: libpq-int.h:391
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:505
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:113
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:293
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:389
static bool PQsendQueryStart(PGconn *conn, bool newQuery)
Definition: fe-exec.c:1432
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:165
char * last_query
Definition: libpq-int.h:392
PQExpBufferData errorMessage
Definition: libpq-int.h:530
#define free(a)
Definition: header.h:65
ProtocolVersion pversion
Definition: libpq-int.h:414
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:573
int i
#define libpq_gettext(x)
Definition: libpq-int.h:809

◆ PQsendQuery()

int PQsendQuery ( PGconn conn,
const char *  query 
)

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

References PQsendQueryInternal().

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

1188 {
1189  return PQsendQueryInternal(conn, query, true);
1190 }
static int PQsendQueryInternal(PGconn *conn, const char *query, bool newQuery)
Definition: fe-exec.c:1199

◆ PQsendQueryContinue()

int PQsendQueryContinue ( PGconn conn,
const char *  query 
)

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

References PQsendQueryInternal().

Referenced by PQconnectPoll().

1194 {
1195  return PQsendQueryInternal(conn, query, false);
1196 }
static int PQsendQueryInternal(PGconn *conn, const char *query, bool newQuery)
Definition: fe-exec.c:1199

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

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

Referenced by PQsendQueryParams(), and PQsendQueryPrepared().

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

◆ PQsendQueryInternal()

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

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

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

Referenced by PQsendQuery(), and PQsendQueryContinue().

1200 {
1201  if (!PQsendQueryStart(conn, newQuery))
1202  return 0;
1203 
1204  /* check the argument */
1205  if (!query)
1206  {
1208  libpq_gettext("command string is a null pointer\n"));
1209  return 0;
1210  }
1211 
1212  /* construct the outgoing Query message */
1213  if (pqPutMsgStart('Q', false, conn) < 0 ||
1214  pqPuts(query, conn) < 0 ||
1215  pqPutMsgEnd(conn) < 0)
1216  {
1217  /* error message should be set up already */
1218  return 0;
1219  }
1220 
1221  /* remember we are using simple query protocol */
1222  conn->queryclass = PGQUERY_SIMPLE;
1223 
1224  /* and remember the query text too, if possible */
1225  /* if insufficient memory, last_query just winds up NULL */
1226  if (conn->last_query)
1227  free(conn->last_query);
1228  conn->last_query = strdup(query);
1229 
1230  /*
1231  * Give the data a push. In nonblock mode, don't complain if we're unable
1232  * to send it all; PQgetResult() will do any additional flushing needed.
1233  */
1234  if (pqFlush(conn) < 0)
1235  {
1236  /* error message should be set up already */
1237  return 0;
1238  }
1239 
1240  /* OK, it's launched! */
1241  conn->asyncStatus = PGASYNC_BUSY;
1242  return 1;
1243 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:1012
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGQueryClass queryclass
Definition: libpq-int.h:391
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:505
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:389
static bool PQsendQueryStart(PGconn *conn, bool newQuery)
Definition: fe-exec.c:1432
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:165
char * last_query
Definition: libpq-int.h:392
PQExpBufferData errorMessage
Definition: libpq-int.h:530
#define free(a)
Definition: header.h:65
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:573
#define libpq_gettext(x)
Definition: libpq-int.h:809

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

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

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

1258 {
1259  if (!PQsendQueryStart(conn, true))
1260  return 0;
1261 
1262  /* check the arguments */
1263  if (!command)
1264  {
1266  libpq_gettext("command string is a null pointer\n"));
1267  return 0;
1268  }
1269  if (nParams < 0 || nParams > 65535)
1270  {
1272  libpq_gettext("number of parameters must be between 0 and 65535\n"));
1273  return 0;
1274  }
1275 
1276  return PQsendQueryGuts(conn,
1277  command,
1278  "", /* use unnamed statement */
1279  nParams,
1280  paramTypes,
1281  paramValues,
1282  paramLengths,
1283  paramFormats,
1284  resultFormat);
1285 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
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:1476
static bool PQsendQueryStart(PGconn *conn, bool newQuery)
Definition: fe-exec.c:1432
PQExpBufferData errorMessage
Definition: libpq-int.h:530
#define libpq_gettext(x)
Definition: libpq-int.h:809

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

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

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

1399 {
1400  if (!PQsendQueryStart(conn, true))
1401  return 0;
1402 
1403  /* check the arguments */
1404  if (!stmtName)
1405  {
1407  libpq_gettext("statement name is a null pointer\n"));
1408  return 0;
1409  }
1410  if (nParams < 0 || nParams > 65535)
1411  {
1413  libpq_gettext("number of parameters must be between 0 and 65535\n"));
1414  return 0;
1415  }
1416 
1417  return PQsendQueryGuts(conn,
1418  NULL, /* no command to parse */
1419  stmtName,
1420  nParams,
1421  NULL, /* no param types */
1422  paramValues,
1423  paramLengths,
1424  paramFormats,
1425  resultFormat);
1426 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
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:1476
static bool PQsendQueryStart(PGconn *conn, bool newQuery)
Definition: fe-exec.c:1432
PQExpBufferData errorMessage
Definition: libpq-int.h:530
#define libpq_gettext(x)
Definition: libpq-int.h:809

◆ PQsendQueryStart()

static bool PQsendQueryStart ( PGconn conn,
bool  newQuery 
)
static

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

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

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

1433 {
1434  if (!conn)
1435  return false;
1436 
1437  /*
1438  * If this is the beginning of a query cycle, reset the error buffer.
1439  */
1440  if (newQuery)
1442 
1443  /* Don't try to send if we know there's no live connection. */
1444  if (conn->status != CONNECTION_OK)
1445  {
1447  libpq_gettext("no connection to the server\n"));
1448  return false;
1449  }
1450  /* Can't send while already busy, either. */
1451  if (conn->asyncStatus != PGASYNC_IDLE)
1452  {
1454  libpq_gettext("another command is already in progress\n"));
1455  return false;
1456  }
1457 
1458  /* initialize async result-accumulation state */
1459  pqClearAsyncResult(conn);
1460 
1461  /* reset single-row processing mode */
1462  conn->singleRowMode = false;
1463 
1464  /* ready to send command message */
1465  return true;
1466 }
bool singleRowMode
Definition: libpq-int.h:397
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:389
PQExpBufferData errorMessage
Definition: libpq-int.h:530
ConnStatusType status
Definition: libpq-int.h:388
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:731
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
#define libpq_gettext(x)
Definition: libpq-int.h:809

◆ PQsetnonblocking()

int PQsetnonblocking ( PGconn conn,
int  arg 
)

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

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

3191 {
3192  bool barg;
3193 
3194  if (!conn || conn->status == CONNECTION_BAD)
3195  return -1;
3196 
3197  barg = (arg ? true : false);
3198 
3199  /* early out if the socket is already in the state requested */
3200  if (barg == conn->nonblocking)
3201  return 0;
3202 
3203  /*
3204  * to guarantee constancy for flushing/query/result-polling behavior we
3205  * need to flush the send queue at this point in order to guarantee proper
3206  * behavior. this is ok because either they are making a transition _from_
3207  * or _to_ blocking mode, either way we can block them.
3208  *
3209  * Clear errorMessage in case pqFlush adds to it.
3210  */
3212 
3213  /* if we are going from blocking to non-blocking flush here */
3214  if (pqFlush(conn))
3215  return -1;
3216 
3217  conn->nonblocking = barg;
3218 
3219  return 0;
3220 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:1012
#define true
Definition: c.h:383
PQExpBufferData errorMessage
Definition: libpq-int.h:530
ConnStatusType status
Definition: libpq-int.h:388
bool nonblocking
Definition: libpq-int.h:395
void * arg
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148

◆ PQsetResultAttrs()

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

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

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

◆ pqSetResultError()

void pqSetResultError ( PGresult res,
const char *  msg 
)

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

References pg_result::errMsg, and pqResultStrdup().

Referenced by PQgetResult(), and PQmakeEmptyPGresult().

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

◆ PQsetSingleRowMode()

int PQsetSingleRowMode ( PGconn conn)

Definition at line 1645 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 process_queued_fetch_requests(), and storeQueryResult().

1646 {
1647  /*
1648  * Only allow setting the flag when we have launched a query and not yet
1649  * received any results.
1650  */
1651  if (!conn)
1652  return 0;
1653  if (conn->asyncStatus != PGASYNC_BUSY)
1654  return 0;
1655  if (conn->queryclass != PGQUERY_SIMPLE &&
1656  conn->queryclass != PGQUERY_EXTENDED)
1657  return 0;
1658  if (conn->result)
1659  return 0;
1660 
1661  /* OK, set flag */
1662  conn->singleRowMode = true;
1663  return 1;
1664 }
bool singleRowMode
Definition: libpq-int.h:397
PGQueryClass queryclass
Definition: libpq-int.h:391
PGresult * result
Definition: libpq-int.h:465
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:389

◆ PQsetvalue()

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

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

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

◆ PQunescapeBytea()

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

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

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

Referenced by dumpTrigger().

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