PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
fe-exec.c File Reference
#include "postgres_fe.h"
#include <ctype.h>
#include <fcntl.h>
#include "libpq-fe.h"
#include "libpq-int.h"
#include "mb/pg_wchar.h"
#include <unistd.h>
Include dependency graph for fe-exec.c:

Go to the source code of this file.

Macros

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

Functions

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

Variables

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

Macro Definition Documentation

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

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

Referenced by PQunescapeBytea().

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

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

Referenced by PQunescapeBytea().

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

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

Referenced by PQunescapeBytea().

#define PGRESULT_ALIGN_BOUNDARY   MAXIMUM_ALIGNOF /* from configure */

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

Referenced by pqResultAlloc().

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

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

Referenced by pqResultAlloc().

#define PGRESULT_DATA_BLOCKSIZE   2048

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

Referenced by pqResultAlloc().

#define PGRESULT_SEP_ALLOC_THRESHOLD   (PGRESULT_DATA_BLOCKSIZE / 2)

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

Referenced by pqResultAlloc().

Function Documentation

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

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

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

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

2703 {
2704  if (!res)
2705  return FALSE; /* no way to display error message... */
2706  if (field_num < 0 || field_num >= res->numAttributes)
2707  {
2709  "column number %d is out of range 0..%d",
2710  field_num, res->numAttributes - 1);
2711  return FALSE;
2712  }
2713  return TRUE;
2714 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
#define FALSE
Definition: c.h:221
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:801
int numAttributes
Definition: libpq-int.h:170
#define TRUE
Definition: c.h:217
static int check_param_number ( const PGresult res,
int  param_num 
)
static

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

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

Referenced by PQparamtype().

2741 {
2742  if (!res)
2743  return FALSE; /* no way to display error message... */
2744  if (param_num < 0 || param_num >= res->numParameters)
2745  {
2747  "parameter number %d is out of range 0..%d",
2748  param_num, res->numParameters - 1);
2749  return FALSE;
2750  }
2751 
2752  return TRUE;
2753 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
#define FALSE
Definition: c.h:221
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:801
int numParameters
Definition: libpq-int.h:175
#define TRUE
Definition: c.h:217
static int check_tuple_field_number ( const PGresult res,
int  tup_num,
int  field_num 
)
static

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

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

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

2719 {
2720  if (!res)
2721  return FALSE; /* no way to display error message... */
2722  if (tup_num < 0 || tup_num >= res->ntups)
2723  {
2725  "row number %d is out of range 0..%d",
2726  tup_num, res->ntups - 1);
2727  return FALSE;
2728  }
2729  if (field_num < 0 || field_num >= res->numAttributes)
2730  {
2732  "column number %d is out of range 0..%d",
2733  field_num, res->numAttributes - 1);
2734  return FALSE;
2735  }
2736  return TRUE;
2737 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
#define FALSE
Definition: c.h:221
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:801
int numAttributes
Definition: libpq-int.h:170
int ntups
Definition: libpq-int.h:169
#define TRUE
Definition: c.h:217
static PGEvent * dupEvents ( PGEvent events,
int  count 
)
static

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

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

Referenced by PQcopyResult(), and PQmakeEmptyPGresult().

383 {
384  PGEvent *newEvents;
385  int i;
386 
387  if (!events || count <= 0)
388  return NULL;
389 
390  newEvents = (PGEvent *) malloc(count * sizeof(PGEvent));
391  if (!newEvents)
392  return NULL;
393 
394  for (i = 0; i < count; i++)
395  {
396  newEvents[i].proc = events[i].proc;
397  newEvents[i].passThrough = events[i].passThrough;
398  newEvents[i].data = NULL;
399  newEvents[i].resultInitialized = FALSE;
400  newEvents[i].name = strdup(events[i].name);
401  if (!newEvents[i].name)
402  {
403  while (--i >= 0)
404  free(newEvents[i].name);
405  free(newEvents);
406  return NULL;
407  }
408  }
409 
410  return newEvents;
411 }
bool resultInitialized
Definition: libpq-int.h:164
#define malloc(a)
Definition: header.h:50
#define FALSE
Definition: c.h:221
void * data
Definition: libpq-int.h:163
#define free(a)
Definition: header.h:65
#define NULL
Definition: c.h:229
PGEventProc proc
Definition: libpq-int.h:160
const char * name
Definition: encode.c:521
int i
void * passThrough
Definition: libpq-int.h:162
char * name
Definition: libpq-int.h:161
static char get_hex ( char  c)
inlinestatic

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

References hexlookup.

Referenced by PQunescapeBytea().

3495 {
3496  int res = -1;
3497 
3498  if (c > 0 && c < 127)
3499  res = hexlookup[(unsigned char) c];
3500 
3501  return (char) res;
3502 }
static const int8 hexlookup[128]
Definition: fe-exec.c:3482
char * c
static PGresult * getCopyResult ( PGconn conn,
ExecStatusType  copytype 
)
static

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

1809 {
1810  /*
1811  * If the server connection has been lost, don't pretend everything is
1812  * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
1813  * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
1814  * error in the earlier steps in PQgetResult). The text returned in the
1815  * result is whatever is in conn->errorMessage; we hope that was filled
1816  * with something relevant when the lost connection was detected.
1817  */
1818  if (conn->status != CONNECTION_OK)
1819  {
1820  pqSaveErrorResult(conn);
1821  conn->asyncStatus = PGASYNC_IDLE;
1822  return pqPrepareAsyncResult(conn);
1823  }
1824 
1825  /* If we have an async result for the COPY, return that */
1826  if (conn->result && conn->result->resultStatus == copytype)
1827  return pqPrepareAsyncResult(conn);
1828 
1829  /* Otherwise, invent a suitable PGresult */
1830  return PQmakeEmptyPGresult(conn, copytype);
1831 }
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:756
PGresult * result
Definition: libpq-int.h:451
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:140
ConnStatusType status
Definition: libpq-int.h:378
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:728
ExecStatusType resultStatus
Definition: libpq-int.h:177
static void parseInput ( PGconn conn)
static

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

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

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

1668 {
1669  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1670  pqParseInput3(conn);
1671  else
1672  pqParseInput2(conn);
1673 }
void pqParseInput2(PGconn *conn)
Definition: fe-protocol2.c:411
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
ProtocolVersion pversion
Definition: libpq-int.h:404
void pqParseInput3(PGconn *conn)
Definition: fe-protocol3.c:66
static bool pqAddTuple ( PGresult res,
PGresAttValue tup 
)
static

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

References FALSE, malloc, pg_result::ntups, NULL, realloc, TRUE, pg_result::tupArrSize, and pg_result::tuples.

Referenced by pqRowProcessor(), and PQsetvalue().

854 {
855  if (res->ntups >= res->tupArrSize)
856  {
857  /*
858  * Try to grow the array.
859  *
860  * We can use realloc because shallow copying of the structure is
861  * okay. Note that the first time through, res->tuples is NULL. While
862  * ANSI says that realloc() should act like malloc() in that case,
863  * some old C libraries (like SunOS 4.1.x) coredump instead. On
864  * failure realloc is supposed to return NULL without damaging the
865  * existing allocation. Note that the positions beyond res->ntups are
866  * garbage, not necessarily NULL.
867  */
868  int newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
869  PGresAttValue **newTuples;
870 
871  if (res->tuples == NULL)
872  newTuples = (PGresAttValue **)
873  malloc(newSize * sizeof(PGresAttValue *));
874  else
875  newTuples = (PGresAttValue **)
876  realloc(res->tuples, newSize * sizeof(PGresAttValue *));
877  if (!newTuples)
878  return FALSE; /* malloc or realloc failed */
879  res->tupArrSize = newSize;
880  res->tuples = newTuples;
881  }
882  res->tuples[res->ntups] = tup;
883  res->ntups++;
884  return TRUE;
885 }
int tupArrSize
Definition: libpq-int.h:174
PGresAttValue ** tuples
Definition: libpq-int.h:172
#define malloc(a)
Definition: header.h:50
#define FALSE
Definition: c.h:221
int ntups
Definition: libpq-int.h:169
#define NULL
Definition: c.h:229
#define realloc(a, b)
Definition: header.h:60
#define TRUE
Definition: c.h:217
int PQbinaryTuples ( const PGresult res)

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

References pg_result::binary.

Referenced by ProcessResult().

2690 {
2691  if (!res)
2692  return 0;
2693  return res->binary;
2694 }
int binary
Definition: libpq-int.h:179
void pqCatenateResultError ( PGresult res,
const char *  msg 
)

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

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

Referenced by PQexecFinish(), and pqSaveErrorResult().

632 {
633  PQExpBufferData errorBuf;
634 
635  if (!res || !msg)
636  return;
637  initPQExpBuffer(&errorBuf);
638  if (res->errMsg)
639  appendPQExpBufferStr(&errorBuf, res->errMsg);
640  appendPQExpBufferStr(&errorBuf, msg);
641  pqSetResultError(res, errorBuf.data);
642  termPQExpBuffer(&errorBuf);
643 }
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
char * errMsg
Definition: libpq-int.h:196
void pqSetResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:616
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
void PQclear ( PGresult res)

Definition at line 650 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, NULL, pg_result::paramDescs, PGEvent::passThrough, PGEVT_RESULTDESTROY, PGEvent::proc, PGEventResultDestroy::result, PGEvent::resultInitialized, and pg_result::tuples.

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

651 {
652  PGresult_data *block;
653  int i;
654 
655  if (!res)
656  return;
657 
658  for (i = 0; i < res->nEvents; i++)
659  {
660  /* only send DESTROY to successfully-initialized event procs */
661  if (res->events[i].resultInitialized)
662  {
664 
665  evt.result = res;
666  (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
667  res->events[i].passThrough);
668  }
669  free(res->events[i].name);
670  }
671 
672  if (res->events)
673  free(res->events);
674 
675  /* Free all the subsidiary blocks */
676  while ((block = res->curBlock) != NULL)
677  {
678  res->curBlock = block->next;
679  free(block);
680  }
681 
682  /* Free the top-level tuple pointer array */
683  if (res->tuples)
684  free(res->tuples);
685 
686  /* zero out the pointer fields to catch programming errors */
687  res->attDescs = NULL;
688  res->tuples = NULL;
689  res->paramDescs = NULL;
690  res->errFields = NULL;
691  res->events = NULL;
692  res->nEvents = 0;
693  /* res->curBlock was zeroed out earlier */
694 
695  /* Free the PGresult structure itself */
696  free(res);
697 }
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
#define NULL
Definition: c.h:229
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
void pqClearAsyncResult ( PGconn conn)

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

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

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

706 {
707  if (conn->result)
708  PQclear(conn->result);
709  conn->result = NULL;
710  if (conn->next_result)
711  PQclear(conn->next_result);
712  conn->next_result = NULL;
713 }
PGresult * result
Definition: libpq-int.h:451
PGresult * next_result
Definition: libpq-int.h:452
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
char* PQcmdStatus ( PGresult res)

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

References pg_result::cmdStatus, and NULL.

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

2945 {
2946  if (!res)
2947  return NULL;
2948  return res->cmdStatus;
2949 }
#define NULL
Definition: c.h:229
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178
char* PQcmdTuples ( PGresult res)

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

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

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

3015 {
3016  char *p,
3017  *c;
3018 
3019  if (!res)
3020  return "";
3021 
3022  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3023  {
3024  p = res->cmdStatus + 7;
3025  /* INSERT: skip oid and space */
3026  while (*p && *p != ' ')
3027  p++;
3028  if (*p == 0)
3029  goto interpret_error; /* no space? */
3030  p++;
3031  }
3032  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3033  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3034  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3035  p = res->cmdStatus + 7;
3036  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
3037  p = res->cmdStatus + 6;
3038  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3039  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3040  p = res->cmdStatus + 5;
3041  else
3042  return "";
3043 
3044  /* check that we have an integer (at least one digit, nothing else) */
3045  for (c = p; *c; c++)
3046  {
3047  if (!isdigit((unsigned char) *c))
3048  goto interpret_error;
3049  }
3050  if (c == p)
3051  goto interpret_error;
3052 
3053  return p;
3054 
3055 interpret_error:
3057  "could not interpret result from server: %s",
3058  res->cmdStatus);
3059  return "";
3060 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
char * c
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:801
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178
int PQconsumeInput ( PGconn conn)

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

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

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

1632 {
1633  if (!conn)
1634  return 0;
1635 
1636  /*
1637  * for non-blocking connections try to flush the send-queue, otherwise we
1638  * may never get a response for something that may not have already been
1639  * sent because it's in our write buffer!
1640  */
1641  if (pqIsnonblocking(conn))
1642  {
1643  if (pqFlush(conn) < 0)
1644  return 0;
1645  }
1646 
1647  /*
1648  * Load more data, if available. We do this no matter what state we are
1649  * in, since we are probably getting called because the application wants
1650  * to get rid of a read-select condition. Note that we will NOT block
1651  * waiting for more input.
1652  */
1653  if (pqReadData(conn) < 0)
1654  return 0;
1655 
1656  /* Parsing of the data waits till later. */
1657  return 1;
1658 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:963
#define pqIsnonblocking(conn)
Definition: libpq-int.h:677
int pqReadData(PGconn *conn)
Definition: fe-misc.c:631
PGresult* PQcopyResult ( const PGresult src,
int  flags 
)

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

References pg_result::attDescs, pg_result::client_encoding, pg_result::cmdStatus, PGEventResultCopy::dest, dupEvents(), pg_result::events, i, pgresAttValue::len, pg_result::nEvents, pg_result::noticeHooks, pg_result::ntups, NULL, 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, TRUE, pg_result::tuples, and pgresAttValue::value.

Referenced by pqRowProcessor().

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

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

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

2083 {
2084  if (!PQexecStart(conn))
2085  return NULL;
2086  if (!PQsendDescribe(conn, 'P', portal))
2087  return NULL;
2088  return PQexecFinish(conn);
2089 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2127
#define NULL
Definition: c.h:229
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2002
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1928
PGresult* PQdescribePrepared ( PGconn conn,
const char *  stmt 
)

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

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

Referenced by ECPGdescribe().

2064 {
2065  if (!PQexecStart(conn))
2066  return NULL;
2067  if (!PQsendDescribe(conn, 'S', stmt))
2068  return NULL;
2069  return PQexecFinish(conn);
2070 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2127
#define NULL
Definition: c.h:229
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2002
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1928
int PQendcopy ( PGconn conn)

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

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

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

2523 {
2524  if (!conn)
2525  return 0;
2526 
2527  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2528  return pqEndcopy3(conn);
2529  else
2530  return pqEndcopy2(conn);
2531 }
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
int pqEndcopy3(PGconn *conn)
ProtocolVersion pversion
Definition: libpq-int.h:404
int pqEndcopy2(PGconn *conn)
unsigned char* PQescapeBytea ( const unsigned char *  from,
size_t  from_length,
size_t *  to_length 
)

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

References NULL, PQescapeByteaInternal(), and static_std_strings.

3631 {
3632  return PQescapeByteaInternal(NULL, from, from_length, to_length,
3634  false /* can't use hex */ );
3635 }
static bool static_std_strings
Definition: fe-exec.c:50
#define NULL
Definition: c.h:229
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:3521
unsigned char* PQescapeByteaConn ( PGconn conn,
const unsigned char *  from,
size_t  from_length,
size_t *  to_length 
)

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

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

3621 {
3622  if (!conn)
3623  return NULL;
3624  return PQescapeByteaInternal(conn, from, from_length, to_length,
3625  conn->std_strings,
3626  (conn->sversion >= 90000));
3627 }
int sversion
Definition: libpq-int.h:405
bool std_strings
Definition: libpq-int.h:424
#define NULL
Definition: c.h:229
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:3521
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 3521 of file fe-exec.c.

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

Referenced by PQescapeBytea(), and PQescapeByteaConn().

3524 {
3525  const unsigned char *vp;
3526  unsigned char *rp;
3527  unsigned char *result;
3528  size_t i;
3529  size_t len;
3530  size_t bslash_len = (std_strings ? 1 : 2);
3531 
3532  /*
3533  * empty string has 1 char ('\0')
3534  */
3535  len = 1;
3536 
3537  if (use_hex)
3538  {
3539  len += bslash_len + 1 + 2 * from_length;
3540  }
3541  else
3542  {
3543  vp = from;
3544  for (i = from_length; i > 0; i--, vp++)
3545  {
3546  if (*vp < 0x20 || *vp > 0x7e)
3547  len += bslash_len + 3;
3548  else if (*vp == '\'')
3549  len += 2;
3550  else if (*vp == '\\')
3551  len += bslash_len + bslash_len;
3552  else
3553  len++;
3554  }
3555  }
3556 
3557  *to_length = len;
3558  rp = result = (unsigned char *) malloc(len);
3559  if (rp == NULL)
3560  {
3561  if (conn)
3563  libpq_gettext("out of memory\n"));
3564  return NULL;
3565  }
3566 
3567  if (use_hex)
3568  {
3569  if (!std_strings)
3570  *rp++ = '\\';
3571  *rp++ = '\\';
3572  *rp++ = 'x';
3573  }
3574 
3575  vp = from;
3576  for (i = from_length; i > 0; i--, vp++)
3577  {
3578  unsigned char c = *vp;
3579 
3580  if (use_hex)
3581  {
3582  *rp++ = hextbl[(c >> 4) & 0xF];
3583  *rp++ = hextbl[c & 0xF];
3584  }
3585  else if (c < 0x20 || c > 0x7e)
3586  {
3587  if (!std_strings)
3588  *rp++ = '\\';
3589  *rp++ = '\\';
3590  *rp++ = (c >> 6) + '0';
3591  *rp++ = ((c >> 3) & 07) + '0';
3592  *rp++ = (c & 07) + '0';
3593  }
3594  else if (c == '\'')
3595  {
3596  *rp++ = '\'';
3597  *rp++ = '\'';
3598  }
3599  else if (c == '\\')
3600  {
3601  if (!std_strings)
3602  {
3603  *rp++ = '\\';
3604  *rp++ = '\\';
3605  }
3606  *rp++ = '\\';
3607  *rp++ = '\\';
3608  }
3609  else
3610  *rp++ = c;
3611  }
3612  *rp = '\0';
3613 
3614  return result;
3615 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
return result
Definition: formatting.c:1632
#define malloc(a)
Definition: header.h:50
char * c
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define NULL
Definition: c.h:229
static const char hextbl[]
Definition: fe-exec.c:3480
int i
#define libpq_gettext(x)
Definition: libpq-int.h:683
char* PQescapeIdentifier ( PGconn conn,
const char *  str,
size_t  len 
)

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

References PQescapeInternal().

Referenced by init(), psql_get_variable(), stringlist_to_identifierstr(), and vacuumlo().

3475 {
3476  return PQescapeInternal(conn, str, len, true);
3477 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:3347
static char* PQescapeInternal ( PGconn conn,
const char *  str,
size_t  len,
bool  as_ident 
)
static

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

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

Referenced by PQescapeIdentifier(), and PQescapeLiteral().

3348 {
3349  const char *s;
3350  char *result;
3351  char *rp;
3352  int num_quotes = 0; /* single or double, depending on as_ident */
3353  int num_backslashes = 0;
3354  int input_len;
3355  int result_size;
3356  char quote_char = as_ident ? '"' : '\'';
3357 
3358  /* We must have a connection, else fail immediately. */
3359  if (!conn)
3360  return NULL;
3361 
3362  /* Scan the string for characters that must be escaped. */
3363  for (s = str; (s - str) < len && *s != '\0'; ++s)
3364  {
3365  if (*s == quote_char)
3366  ++num_quotes;
3367  else if (*s == '\\')
3368  ++num_backslashes;
3369  else if (IS_HIGHBIT_SET(*s))
3370  {
3371  int charlen;
3372 
3373  /* Slow path for possible multibyte characters */
3374  charlen = pg_encoding_mblen(conn->client_encoding, s);
3375 
3376  /* Multibyte character overruns allowable length. */
3377  if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
3378  {
3380  libpq_gettext("incomplete multibyte character\n"));
3381  return NULL;
3382  }
3383 
3384  /* Adjust s, bearing in mind that for loop will increment it. */
3385  s += charlen - 1;
3386  }
3387  }
3388 
3389  /* Allocate output buffer. */
3390  input_len = s - str;
3391  result_size = input_len + num_quotes + 3; /* two quotes, plus a NUL */
3392  if (!as_ident && num_backslashes > 0)
3393  result_size += num_backslashes + 2;
3394  result = rp = (char *) malloc(result_size);
3395  if (rp == NULL)
3396  {
3398  libpq_gettext("out of memory\n"));
3399  return NULL;
3400  }
3401 
3402  /*
3403  * If we are escaping a literal that contains backslashes, we use the
3404  * escape string syntax so that the result is correct under either value
3405  * of standard_conforming_strings. We also emit a leading space in this
3406  * case, to guard against the possibility that the result might be
3407  * interpolated immediately following an identifier.
3408  */
3409  if (!as_ident && num_backslashes > 0)
3410  {
3411  *rp++ = ' ';
3412  *rp++ = 'E';
3413  }
3414 
3415  /* Opening quote. */
3416  *rp++ = quote_char;
3417 
3418  /*
3419  * Use fast path if possible.
3420  *
3421  * We've already verified that the input string is well-formed in the
3422  * current encoding. If it contains no quotes and, in the case of
3423  * literal-escaping, no backslashes, then we can just copy it directly to
3424  * the output buffer, adding the necessary quotes.
3425  *
3426  * If not, we must rescan the input and process each character
3427  * individually.
3428  */
3429  if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
3430  {
3431  memcpy(rp, str, input_len);
3432  rp += input_len;
3433  }
3434  else
3435  {
3436  for (s = str; s - str < input_len; ++s)
3437  {
3438  if (*s == quote_char || (!as_ident && *s == '\\'))
3439  {
3440  *rp++ = *s;
3441  *rp++ = *s;
3442  }
3443  else if (!IS_HIGHBIT_SET(*s))
3444  *rp++ = *s;
3445  else
3446  {
3447  int i = pg_encoding_mblen(conn->client_encoding, s);
3448 
3449  while (1)
3450  {
3451  *rp++ = *s;
3452  if (--i == 0)
3453  break;
3454  ++s; /* for loop will provide the final increment */
3455  }
3456  }
3457  }
3458  }
3459 
3460  /* Closing quote and terminating NUL. */
3461  *rp++ = quote_char;
3462  *rp = '\0';
3463 
3464  return result;
3465 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
return result
Definition: formatting.c:1632
#define malloc(a)
Definition: header.h:50
#define IS_HIGHBIT_SET(ch)
Definition: c.h:973
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1785
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define NULL
Definition: c.h:229
int i
int client_encoding
Definition: libpq-int.h:423
#define libpq_gettext(x)
Definition: libpq-int.h:683
char* PQescapeLiteral ( PGconn conn,
const char *  str,
size_t  len 
)

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

References PQescapeInternal().

Referenced by libpqrcv_startstreaming(), and psql_get_variable().

3469 {
3470  return PQescapeInternal(conn, str, len, false);
3471 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:3347
size_t PQescapeString ( char *  to,
const char *  from,
size_t  length 
)

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

References NULL, PQescapeStringInternal(), static_client_encoding, and static_std_strings.

Referenced by get_comma_elts(), and quote_postgres().

3333 {
3334  return PQescapeStringInternal(NULL, to, from, length, NULL,
3337 }
static bool static_std_strings
Definition: fe-exec.c:50
int length(const List *list)
Definition: list.c:1271
static int static_client_encoding
Definition: fe-exec.c:49
#define NULL
Definition: c.h:229
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:3239
size_t PQescapeStringConn ( PGconn conn,
char *  to,
const char *  from,
size_t  length,
int *  error 
)

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

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

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

3317 {
3318  if (!conn)
3319  {
3320  /* force empty-string result */
3321  *to = '\0';
3322  if (error)
3323  *error = 1;
3324  return 0;
3325  }
3326  return PQescapeStringInternal(conn, to, from, length, error,
3327  conn->client_encoding,
3328  conn->std_strings);
3329 }
int length(const List *list)
Definition: list.c:1271
static void error(void)
Definition: sql-dyntest.c:147
bool std_strings
Definition: libpq-int.h:424
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:3239
int client_encoding
Definition: libpq-int.h:423
static size_t PQescapeStringInternal ( PGconn conn,
char *  to,
const char *  from,
size_t  length,
int *  error,
int  encoding,
bool  std_strings 
)
static

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

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

Referenced by PQescapeString(), and PQescapeStringConn().

3243 {
3244  const char *source = from;
3245  char *target = to;
3246  size_t remaining = length;
3247 
3248  if (error)
3249  *error = 0;
3250 
3251  while (remaining > 0 && *source != '\0')
3252  {
3253  char c = *source;
3254  int len;
3255  int i;
3256 
3257  /* Fast path for plain ASCII */
3258  if (!IS_HIGHBIT_SET(c))
3259  {
3260  /* Apply quoting if needed */
3261  if (SQL_STR_DOUBLE(c, !std_strings))
3262  *target++ = c;
3263  /* Copy the character */
3264  *target++ = c;
3265  source++;
3266  remaining--;
3267  continue;
3268  }
3269 
3270  /* Slow path for possible multibyte characters */
3271  len = pg_encoding_mblen(encoding, source);
3272 
3273  /* Copy the character */
3274  for (i = 0; i < len; i++)
3275  {
3276  if (remaining == 0 || *source == '\0')
3277  break;
3278  *target++ = *source++;
3279  remaining--;
3280  }
3281 
3282  /*
3283  * If we hit premature end of string (ie, incomplete multibyte
3284  * character), try to pad out to the correct length with spaces. We
3285  * may not be able to pad completely, but we will always be able to
3286  * insert at least one pad space (since we'd not have quoted a
3287  * multibyte character). This should be enough to make a string that
3288  * the server will error out on.
3289  */
3290  if (i < len)
3291  {
3292  if (error)
3293  *error = 1;
3294  if (conn)
3296  libpq_gettext("incomplete multibyte character\n"));
3297  for (; i < len; i++)
3298  {
3299  if (((size_t) (target - to)) / 2 >= length)
3300  break;
3301  *target++ = ' ';
3302  }
3303  break;
3304  }
3305  }
3306 
3307  /* Write the terminating NUL character. */
3308  *target = '\0';
3309 
3310  return target - to;
3311 }
int remaining
Definition: informix.c:692
int length(const List *list)
Definition: list.c:1271
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
static void error(void)
Definition: sql-dyntest.c:147
#define IS_HIGHBIT_SET(ch)
Definition: c.h:973
char * c
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1785
PQExpBufferData errorMessage
Definition: libpq-int.h:492
static char * encoding
Definition: initdb.c:122
int i
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:507
#define libpq_gettext(x)
Definition: libpq-int.h:683
PGresult* PQexec ( PGconn conn,
const char *  query 
)

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

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

Referenced by _doSetSessionAuth(), _doSetWithOids(), _selectOutputSchema(), _selectTablespace(), check_loadable_libraries(), CreateReplicationSlot(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), deallocate_one(), do_sql_command(), 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(), init(), libpq_executeFileMap(), libpqConnect(), libpqProcessFileList(), lo_initialize(), lockTableForWorker(), lookup_object_oid(), main(), pgfdw_subxact_callback(), pgfdw_xact_callback(), PQencryptPasswordConn(), PQsetClientEncoding(), PSQLexec(), PSQLexecWatch(), ReceiveXlogStream(), run_permutation(), run_simple_query(), RunIdentifySystem(), SendQuery(), sql_exec(), StreamLogicalLog(), tryExecuteStatement(), and vacuumlo().

1847 {
1848  if (!PQexecStart(conn))
1849  return NULL;
1850  if (!PQsendQuery(conn, query))
1851  return NULL;
1852  return PQexecFinish(conn);
1853 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1132
#define NULL
Definition: c.h:229
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2002
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1928
static PGresult * PQexecFinish ( PGconn conn)
static

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

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

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

2003 {
2004  PGresult *result;
2005  PGresult *lastResult;
2006 
2007  /*
2008  * For backwards compatibility, return the last result if there are more
2009  * than one --- but merge error messages if we get more than one error
2010  * result.
2011  *
2012  * We have to stop if we see copy in/out/both, however. We will resume
2013  * parsing after application performs the data transfer.
2014  *
2015  * Also stop if the connection is lost (else we'll loop infinitely).
2016  */
2017  lastResult = NULL;
2018  while ((result = PQgetResult(conn)) != NULL)
2019  {
2020  if (lastResult)
2021  {
2022  if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
2023  result->resultStatus == PGRES_FATAL_ERROR)
2024  {
2025  pqCatenateResultError(lastResult, result->errMsg);
2026  PQclear(result);
2027  result = lastResult;
2028 
2029  /*
2030  * Make sure PQerrorMessage agrees with concatenated result
2031  */
2033  appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
2034  }
2035  else
2036  PQclear(lastResult);
2037  }
2038  lastResult = result;
2039  if (result->resultStatus == PGRES_COPY_IN ||
2040  result->resultStatus == PGRES_COPY_OUT ||
2041  result->resultStatus == PGRES_COPY_BOTH ||
2042  conn->status == CONNECTION_BAD)
2043  break;
2044  }
2045 
2046  return lastResult;
2047 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
return result
Definition: formatting.c:1632
char * errMsg
Definition: libpq-int.h:196
PQExpBufferData errorMessage
Definition: libpq-int.h:492
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
ConnStatusType status
Definition: libpq-int.h:378
void pqCatenateResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:631
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
ExecStatusType resultStatus
Definition: libpq-int.h:177
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1702
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 1860 of file fe-exec.c.

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

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

1868 {
1869  if (!PQexecStart(conn))
1870  return NULL;
1871  if (!PQsendQueryParams(conn, command,
1872  nParams, paramTypes, paramValues, paramLengths,
1873  paramFormats, resultFormat))
1874  return NULL;
1875  return PQexecFinish(conn);
1876 }
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:1183
#define NULL
Definition: c.h:229
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2002
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1928
PGresult* PQexecPrepared ( PGconn conn,
const char *  stmtName,
int  nParams,
const char *const *  paramValues,
const int *  paramLengths,
const int *  paramFormats,
int  resultFormat 
)

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

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

Referenced by ecpg_execute(), and try_complete_step().

1914 {
1915  if (!PQexecStart(conn))
1916  return NULL;
1917  if (!PQsendQueryPrepared(conn, stmtName,
1918  nParams, paramValues, paramLengths,
1919  paramFormats, resultFormat))
1920  return NULL;
1921  return PQexecFinish(conn);
1922 }
#define NULL
Definition: c.h:229
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2002
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:1325
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1928
static bool PQexecStart ( PGconn conn)
static

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

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

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

1929 {
1930  PGresult *result;
1931 
1932  if (!conn)
1933  return false;
1934 
1935  /*
1936  * Silently discard any prior query result that application didn't eat.
1937  * This is probably poor design, but it's here for backward compatibility.
1938  */
1939  while ((result = PQgetResult(conn)) != NULL)
1940  {
1941  ExecStatusType resultStatus = result->resultStatus;
1942 
1943  PQclear(result); /* only need its status */
1944  if (resultStatus == PGRES_COPY_IN)
1945  {
1946  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1947  {
1948  /* In protocol 3, we can get out of a COPY IN state */
1949  if (PQputCopyEnd(conn,
1950  libpq_gettext("COPY terminated by new PQexec")) < 0)
1951  return false;
1952  /* keep waiting to swallow the copy's failure message */
1953  }
1954  else
1955  {
1956  /* In older protocols we have to punt */
1958  libpq_gettext("COPY IN state must be terminated first\n"));
1959  return false;
1960  }
1961  }
1962  else if (resultStatus == PGRES_COPY_OUT)
1963  {
1964  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1965  {
1966  /*
1967  * In protocol 3, we can get out of a COPY OUT state: we just
1968  * switch back to BUSY and allow the remaining COPY data to be
1969  * dropped on the floor.
1970  */
1971  conn->asyncStatus = PGASYNC_BUSY;
1972  /* keep waiting to swallow the copy's completion message */
1973  }
1974  else
1975  {
1976  /* In older protocols we have to punt */
1978  libpq_gettext("COPY OUT state must be terminated first\n"));
1979  return false;
1980  }
1981  }
1982  else if (resultStatus == PGRES_COPY_BOTH)
1983  {
1984  /* We don't allow PQexec during COPY BOTH */
1986  libpq_gettext("PQexec not allowed during COPY BOTH\n"));
1987  return false;
1988  }
1989  /* check for loss of connection, too */
1990  if (conn->status == CONNECTION_BAD)
1991  return false;
1992  }
1993 
1994  /* OK to send a command */
1995  return true;
1996 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2288
return result
Definition: formatting.c:1632
ExecStatusType
Definition: libpq-fe.h:82
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
PQExpBufferData errorMessage
Definition: libpq-int.h:492
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
ProtocolVersion pversion
Definition: libpq-int.h:404
ConnStatusType status
Definition: libpq-int.h:378
ExecStatusType resultStatus
Definition: libpq-int.h:177
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1702
#define libpq_gettext(x)
Definition: libpq-int.h:683
int PQfformat ( const PGresult res,
int  field_num 
)

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

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

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

2901 {
2902  if (!check_field_number(res, field_num))
2903  return 0;
2904  if (res->attDescs)
2905  return res->attDescs[field_num].format;
2906  else
2907  return 0;
2908 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2702
int PQflush ( PGconn conn)

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

References pqFlush().

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

3188 {
3189  return pqFlush(conn);
3190 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:963
int PQfmod ( const PGresult res,
int  field_num 
)

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

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

Referenced by ECPGget_desc().

2934 {
2935  if (!check_field_number(res, field_num))
2936  return 0;
2937  if (res->attDescs)
2938  return res->attDescs[field_num].atttypmod;
2939  else
2940  return 0;
2941 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
int atttypmod
Definition: libpq-fe.h:243
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2702
PGresult* PQfn ( PGconn conn,
int  fnid,
int *  result_buf,
int *  result_len,
int  result_is_int,
const PQArgBlock args,
int  nargs 
)

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

References pg_conn::asyncStatus, pg_conn::errorMessage, libpq_gettext, NULL, PG_PROTOCOL_MAJOR, PGASYNC_IDLE, PGINVALID_SOCKET, pqFunctionCall2(), pqFunctionCall3(), printfPQExpBuffer(), pg_conn::pversion, resetPQExpBuffer(), pg_conn::result, and pg_conn::sock.

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

2563 {
2564  *result_len = 0;
2565 
2566  if (!conn)
2567  return NULL;
2568 
2569  /* clear the error string */
2571 
2572  if (conn->sock == PGINVALID_SOCKET || conn->asyncStatus != PGASYNC_IDLE ||
2573  conn->result != NULL)
2574  {
2576  libpq_gettext("connection in wrong state\n"));
2577  return NULL;
2578  }
2579 
2580  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2581  return pqFunctionCall3(conn, fnid,
2582  result_buf, result_len,
2583  result_is_int,
2584  args, nargs);
2585  else
2586  return pqFunctionCall2(conn, fnid,
2587  result_buf, result_len,
2588  result_is_int,
2589  args, nargs);
2590 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
PGresult * pqFunctionCall2(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
PGresult * pqFunctionCall3(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGresult * result
Definition: libpq-int.h:451
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
pgsocket sock
Definition: libpq-int.h:400
#define PGINVALID_SOCKET
Definition: port.h:24
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define NULL
Definition: c.h:229
ProtocolVersion pversion
Definition: libpq-int.h:404
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
#define libpq_gettext(x)
Definition: libpq-int.h:683
char* PQfname ( const PGresult res,
int  field_num 
)

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

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

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

2760 {
2761  if (!check_field_number(res, field_num))
2762  return NULL;
2763  if (res->attDescs)
2764  return res->attDescs[field_num].name;
2765  else
2766  return NULL;
2767 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2702
#define NULL
Definition: c.h:229
char * name
Definition: libpq-fe.h:237
int PQfnumber ( const PGresult res,
const char *  field_name 
)

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

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

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

2782 {
2783  char *field_case;
2784  bool in_quotes;
2785  bool all_lower = true;
2786  const char *iptr;
2787  char *optr;
2788  int i;
2789 
2790  if (!res)
2791  return -1;
2792 
2793  /*
2794  * Note: it is correct to reject a zero-length input string; the proper
2795  * input to match a zero-length field name would be "".
2796  */
2797  if (field_name == NULL ||
2798  field_name[0] == '\0' ||
2799  res->attDescs == NULL)
2800  return -1;
2801 
2802  /*
2803  * Check if we can avoid the strdup() and related work because the
2804  * passed-in string wouldn't be changed before we do the check anyway.
2805  */
2806  for (iptr = field_name; *iptr; iptr++)
2807  {
2808  char c = *iptr;
2809 
2810  if (c == '"' || c != pg_tolower((unsigned char) c))
2811  {
2812  all_lower = false;
2813  break;
2814  }
2815  }
2816 
2817  if (all_lower)
2818  for (i = 0; i < res->numAttributes; i++)
2819  if (strcmp(field_name, res->attDescs[i].name) == 0)
2820  return i;
2821 
2822  /* Fall through to the normal check if that didn't work out. */
2823 
2824  /*
2825  * Note: this code will not reject partially quoted strings, eg
2826  * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
2827  * condition.
2828  */
2829  field_case = strdup(field_name);
2830  if (field_case == NULL)
2831  return -1; /* grotty */
2832 
2833  in_quotes = false;
2834  optr = field_case;
2835  for (iptr = field_case; *iptr; iptr++)
2836  {
2837  char c = *iptr;
2838 
2839  if (in_quotes)
2840  {
2841  if (c == '"')
2842  {
2843  if (iptr[1] == '"')
2844  {
2845  /* doubled quotes become a single quote */
2846  *optr++ = '"';
2847  iptr++;
2848  }
2849  else
2850  in_quotes = false;
2851  }
2852  else
2853  *optr++ = c;
2854  }
2855  else if (c == '"')
2856  in_quotes = true;
2857  else
2858  {
2859  c = pg_tolower((unsigned char) c);
2860  *optr++ = c;
2861  }
2862  }
2863  *optr = '\0';
2864 
2865  for (i = 0; i < res->numAttributes; i++)
2866  {
2867  if (strcmp(field_case, res->attDescs[i].name) == 0)
2868  {
2869  free(field_case);
2870  return i;
2871  }
2872  }
2873  free(field_case);
2874  return -1;
2875 }
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
#define NULL
Definition: c.h:229
int i
char * name
Definition: libpq-fe.h:237
void PQfreeNotify ( PGnotify notify)

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

References PQfreemem().

3218 {
3219  PQfreemem(notify);
3220 }
void PQfreemem(void *ptr)
Definition: fe-exec.c:3200
int PQfsize ( const PGresult res,
int  field_num 
)

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

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

Referenced by ecpg_build_compat_sqlda(), and ECPGget_desc().

2923 {
2924  if (!check_field_number(res, field_num))
2925  return 0;
2926  if (res->attDescs)
2927  return res->attDescs[field_num].typlen;
2928  else
2929  return 0;
2930 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2702
Oid PQftable ( const PGresult res,
int  field_num 
)

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

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

2879 {
2880  if (!check_field_number(res, field_num))
2881  return InvalidOid;
2882  if (res->attDescs)
2883  return res->attDescs[field_num].tableid;
2884  else
2885  return InvalidOid;
2886 }
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:2702
int PQftablecol ( const PGresult res,
int  field_num 
)

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

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

2890 {
2891  if (!check_field_number(res, field_num))
2892  return 0;
2893  if (res->attDescs)
2894  return res->attDescs[field_num].columnid;
2895  else
2896  return 0;
2897 }
int columnid
Definition: libpq-fe.h:239
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2702
Oid PQftype ( const PGresult res,
int  field_num 
)

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

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

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

2912 {
2913  if (!check_field_number(res, field_num))
2914  return InvalidOid;
2915  if (res->attDescs)
2916  return res->attDescs[field_num].typid;
2917  else
2918  return InvalidOid;
2919 }
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:2702
int PQgetCopyData ( PGconn conn,
char **  buffer,
int  async 
)

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

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

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

2378 {
2379  *buffer = NULL; /* for all failure cases */
2380  if (!conn)
2381  return -2;
2382  if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2383  conn->asyncStatus != PGASYNC_COPY_BOTH)
2384  {
2386  libpq_gettext("no COPY in progress\n"));
2387  return -2;
2388  }
2389  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2390  return pqGetCopyData3(conn, buffer, async);
2391  else
2392  return pqGetCopyData2(conn, buffer, async);
2393 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
int pqGetCopyData3(PGconn *conn, char **buffer, int async)
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define NULL
Definition: c.h:229
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:211
ProtocolVersion pversion
Definition: libpq-int.h:404
int pqGetCopyData2(PGconn *conn, char **buffer, int async)
#define libpq_gettext(x)
Definition: libpq-int.h:683
int PQgetisnull ( const PGresult res,
int  tup_num,
int  field_num 
)

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

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

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

3093 {
3094  if (!check_tuple_field_number(res, tup_num, field_num))
3095  return 1; /* pretend it is null */
3096  if (res->tuples[tup_num][field_num].len == NULL_LEN)
3097  return 1;
3098  else
3099  return 0;
3100 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:2717
#define NULL_LEN
Definition: libpq-int.h:133
PGresAttValue ** tuples
Definition: libpq-int.h:172
int PQgetlength ( const PGresult res,
int  tup_num,
int  field_num 
)

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

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

Referenced by createViewAsClause(), do_field(), ecpg_get_data(), ecpg_store_result(), ECPGget_desc(), libpqGetFile(), libpqrcv_readtimelinehistoryfile(), PQdisplayTuples(), receiveFileChunks(), and show_binary_results().

3079 {
3080  if (!check_tuple_field_number(res, tup_num, field_num))
3081  return 0;
3082  if (res->tuples[tup_num][field_num].len != NULL_LEN)
3083  return res->tuples[tup_num][field_num].len;
3084  else
3085  return 0;
3086 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:2717
#define NULL_LEN
Definition: libpq-int.h:133
PGresAttValue ** tuples
Definition: libpq-int.h:172
int PQgetline ( PGconn conn,
char *  s,
int  maxlen 
)

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

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

2420 {
2421  if (!s || maxlen <= 0)
2422  return EOF;
2423  *s = '\0';
2424  /* maxlen must be at least 3 to hold the \. terminator! */
2425  if (maxlen < 3)
2426  return EOF;
2427 
2428  if (!conn)
2429  return EOF;
2430 
2431  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2432  return pqGetline3(conn, s, maxlen);
2433  else
2434  return pqGetline2(conn, s, maxlen);
2435 }
int pqGetline3(PGconn *conn, char *s, int maxlen)
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
int pqGetline2(PGconn *conn, char *s, int maxlen)
ProtocolVersion pversion
Definition: libpq-int.h:404
int PQgetlineAsync ( PGconn conn,
char *  buffer,
int  bufsize 
)

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

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

Referenced by pqGetline3().

2470 {
2471  if (!conn)
2472  return -1;
2473 
2474  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2475  return pqGetlineAsync3(conn, buffer, bufsize);
2476  else
2477  return pqGetlineAsync2(conn, buffer, bufsize);
2478 }
int pqGetlineAsync2(PGconn *conn, char *buffer, int bufsize)
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:211
ProtocolVersion pversion
Definition: libpq-int.h:404
PGresult* PQgetResult ( PGconn conn)

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

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

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

1703 {
1704  PGresult *res;
1705 
1706  if (!conn)
1707  return NULL;
1708 
1709  /* Parse any available data, if our state permits. */
1710  parseInput(conn);
1711 
1712  /* If not ready to return something, block until we are. */
1713  while (conn->asyncStatus == PGASYNC_BUSY)
1714  {
1715  int flushResult;
1716 
1717  /*
1718  * If data remains unsent, send it. Else we might be waiting for the
1719  * result of a command the backend hasn't even got yet.
1720  */
1721  while ((flushResult = pqFlush(conn)) > 0)
1722  {
1723  if (pqWait(FALSE, TRUE, conn))
1724  {
1725  flushResult = -1;
1726  break;
1727  }
1728  }
1729 
1730  /* Wait for some more data, and load it. */
1731  if (flushResult ||
1732  pqWait(TRUE, FALSE, conn) ||
1733  pqReadData(conn) < 0)
1734  {
1735  /*
1736  * conn->errorMessage has been set by pqWait or pqReadData. We
1737  * want to append it to any already-received error message.
1738  */
1739  pqSaveErrorResult(conn);
1740  conn->asyncStatus = PGASYNC_IDLE;
1741  return pqPrepareAsyncResult(conn);
1742  }
1743 
1744  /* Parse it. */
1745  parseInput(conn);
1746  }
1747 
1748  /* Return the appropriate thing. */
1749  switch (conn->asyncStatus)
1750  {
1751  case PGASYNC_IDLE:
1752  res = NULL; /* query is complete */
1753  break;
1754  case PGASYNC_READY:
1755  res = pqPrepareAsyncResult(conn);
1756  /* Set the state back to BUSY, allowing parsing to proceed. */
1757  conn->asyncStatus = PGASYNC_BUSY;
1758  break;
1759  case PGASYNC_COPY_IN:
1760  res = getCopyResult(conn, PGRES_COPY_IN);
1761  break;
1762  case PGASYNC_COPY_OUT:
1763  res = getCopyResult(conn, PGRES_COPY_OUT);
1764  break;
1765  case PGASYNC_COPY_BOTH:
1766  res = getCopyResult(conn, PGRES_COPY_BOTH);
1767  break;
1768  default:
1770  libpq_gettext("unexpected asyncStatus: %d\n"),
1771  (int) conn->asyncStatus);
1773  break;
1774  }
1775 
1776  if (res)
1777  {
1778  int i;
1779 
1780  for (i = 0; i < res->nEvents; i++)
1781  {
1782  PGEventResultCreate evt;
1783 
1784  evt.conn = conn;
1785  evt.result = res;
1786  if (!res->events[i].proc(PGEVT_RESULTCREATE, &evt,
1787  res->events[i].passThrough))
1788  {
1790  libpq_gettext("PGEventProc \"%s\" failed during PGEVT_RESULTCREATE event\n"),
1791  res->events[i].name);
1792  pqSetResultError(res, conn->errorMessage.data);
1794  break;
1795  }
1796  res->events[i].resultInitialized = TRUE;
1797  }
1798  }
1799 
1800  return res;
1801 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:963
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
bool resultInitialized
Definition: libpq-int.h:164
int nEvents
Definition: libpq-int.h:188
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:756
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
#define FALSE
Definition: c.h:221
PGconn * conn
Definition: streamutil.c:42
int pqReadData(PGconn *conn)
Definition: fe-misc.c:631
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:986
static PGresult * getCopyResult(PGconn *conn, ExecStatusType copytype)
Definition: fe-exec.c:1808
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:140
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1667
PQExpBufferData errorMessage
Definition: libpq-int.h:492
void pqSetResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:616
#define NULL
Definition: c.h:229
PGEventProc proc
Definition: libpq-int.h:160
int i
void * passThrough
Definition: libpq-int.h:162
#define TRUE
Definition: c.h:217
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:728
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:683
char* PQgetvalue ( const PGresult res,
int  tup_num,
int  field_num 
)

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

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

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

3068 {
3069  if (!check_tuple_field_number(res, tup_num, field_num))
3070  return NULL;
3071  return res->tuples[tup_num][field_num].value;
3072 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:2717
PGresAttValue ** tuples
Definition: libpq-int.h:172
#define NULL
Definition: c.h:229
char * value
Definition: libpq-int.h:138
void pqHandleSendFailure ( PGconn conn)

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

References parseInput(), and pqReadData().

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

1583 {
1584  /*
1585  * Accept and parse any available input data, ignoring I/O errors. Note
1586  * that if pqReadData decides the backend has closed the channel, it will
1587  * close our side of the socket --- that's just what we want here.
1588  */
1589  while (pqReadData(conn) > 0)
1590  parseInput(conn);
1591 
1592  /*
1593  * Be sure to parse available input messages even if we read no data.
1594  * (Note: calling parseInput within the above loop isn't really necessary,
1595  * but it prevents buffer bloat if there's a lot of data available.)
1596  */
1597  parseInput(conn);
1598 }
int pqReadData(PGconn *conn)
Definition: fe-misc.c:631
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1667
void pqInternalNotice ( const PGNoticeHooks hooks,
const char *  fmt,
  ... 
)

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

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

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

802 {
803  char msgBuf[1024];
804  va_list args;
805  PGresult *res;
806 
807  if (hooks->noticeRec == NULL)
808  return; /* nobody home to receive notice? */
809 
810  /* Format the message */
811  va_start(args, fmt);
812  vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
813  va_end(args);
814  msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
815 
816  /* Make a PGresult to pass to the notice receiver */
818  if (!res)
819  return;
820  res->noticeHooks = *hooks;
821 
822  /*
823  * Set up fields of notice.
824  */
828  /* XXX should provide a SQLSTATE too? */
829 
830  /*
831  * Result text is always just the primary message + newline. If we can't
832  * allocate it, don't bother invoking the receiver.
833  */
834  res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, FALSE);
835  if (res->errMsg)
836  {
837  sprintf(res->errMsg, "%s\n", msgBuf);
838 
839  /*
840  * Pass to receiver, then free it.
841  */
842  (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
843  }
844  PQclear(res);
845 }
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:58
int int vsnprintf(char *str, size_t count, const char *fmt, va_list args)
#define FALSE
Definition: c.h:221
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:140
void pqSaveMessageField(PGresult *res, char code, const char *value)
Definition: fe-exec.c:891
#define PG_DIAG_SEVERITY_NONLOCALIZED
Definition: postgres_ext.h:56
void PQclear(PGresult *res)
Definition: fe-exec.c:650
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:506
#define NULL
Definition: c.h:229
#define libpq_gettext(x)
Definition: libpq-int.h:683
int PQisBusy ( PGconn conn)

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

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

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

1682 {
1683  if (!conn)
1684  return FALSE;
1685 
1686  /* Parse any available data, if our state permits. */
1687  parseInput(conn);
1688 
1689  /* PQgetResult will return immediately in all states except BUSY. */
1690  return conn->asyncStatus == PGASYNC_BUSY;
1691 }
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
#define FALSE
Definition: c.h:221
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1667
int PQisnonblocking ( const PGconn conn)

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

References pqIsnonblocking.

3169 {
3170  return pqIsnonblocking(conn);
3171 }
#define pqIsnonblocking(conn)
Definition: libpq-int.h:677
int PQisthreadsafe ( void  )

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

3176 {
3177 #ifdef ENABLE_THREAD_SAFETY
3178  return true;
3179 #else
3180  return false;
3181 #endif
3182 }
PGresult* PQmakeEmptyPGresult ( PGconn conn,
ExecStatusType  status 
)

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

References pg_result::attDescs, pg_result::binary, pg_result::client_encoding, pg_conn::client_encoding, pg_result::cmdStatus, pg_result::curBlock, pg_result::curOffset, PQExpBufferData::data, dupEvents(), pg_result::errFields, pg_result::errMsg, pg_conn::errorMessage, pg_result::errQuery, pg_result::events, pg_conn::events, malloc, pg_result::nEvents, pg_conn::nEvents, pg_result::noticeHooks, pg_conn::noticeHooks, PGNoticeHooks::noticeProc, PGNoticeHooks::noticeProcArg, PGNoticeHooks::noticeRec, PGNoticeHooks::noticeRecArg, pg_result::ntups, NULL, 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(), result, 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().

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

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

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

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

2194 {
2195  PGnotify *event;
2196 
2197  if (!conn)
2198  return NULL;
2199 
2200  /* Parse any available data to see if we can extract NOTIFY messages. */
2201  parseInput(conn);
2202 
2203  event = conn->notifyHead;
2204  if (event)
2205  {
2206  conn->notifyHead = event->next;
2207  if (!conn->notifyHead)
2208  conn->notifyTail = NULL;
2209  event->next = NULL; /* don't let app see the internal state */
2210  }
2211  return event;
2212 }
PGnotify * notifyHead
Definition: libpq-int.h:391
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1667
struct pgNotify * next
Definition: libpq-fe.h:167
#define NULL
Definition: c.h:229
PGnotify * notifyTail
Definition: libpq-int.h:392
int PQnparams ( const PGresult res)

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

References pg_result::numParameters.

3107 {
3108  if (!res)
3109  return 0;
3110  return res->numParameters;
3111 }
int numParameters
Definition: libpq-int.h:175
int PQntuples ( const PGresult res)

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

References pg_result::ntups.

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

2674 {
2675  if (!res)
2676  return 0;
2677  return res->ntups;
2678 }
int ntups
Definition: libpq-int.h:169
char* PQoidStatus ( const PGresult res)

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

References buf, and pg_result::cmdStatus.

2958 {
2959  /*
2960  * This must be enough to hold the result. Don't laugh, this is better
2961  * than what this function used to do.
2962  */
2963  static char buf[24];
2964 
2965  size_t len;
2966 
2967  if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2968  return "";
2969 
2970  len = strspn(res->cmdStatus + 7, "0123456789");
2971  if (len > sizeof(buf) - 1)
2972  len = sizeof(buf) - 1;
2973  memcpy(buf, res->cmdStatus + 7, len);
2974  buf[len] = '\0';
2975 
2976  return buf;
2977 }
static char * buf
Definition: pg_test_fsync.c:66
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178
Oid PQoidValue ( const PGresult res)

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

References pg_result::cmdStatus, InvalidOid, NULL, and result.

Referenced by ecpg_process_output(), and PrintQueryStatus().

2986 {
2987  char *endptr = NULL;
2988  unsigned long result;
2989 
2990  if (!res ||
2991  strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
2992  res->cmdStatus[7] < '0' ||
2993  res->cmdStatus[7] > '9')
2994  return InvalidOid;
2995 
2996  result = strtoul(res->cmdStatus + 7, &endptr, 10);
2997 
2998  if (!endptr || (*endptr != ' ' && *endptr != '\0'))
2999  return InvalidOid;
3000  else
3001  return (Oid) result;
3002 }
return result
Definition: formatting.c:1632
unsigned int Oid
Definition: postgres_ext.h:31
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178
Oid PQparamtype ( const PGresult res,
int  param_num 
)

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

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

3118 {
3119  if (!check_param_number(res, param_num))
3120  return InvalidOid;
3121  if (res->paramDescs)
3122  return res->paramDescs[param_num].typid;
3123  else
3124  return InvalidOid;
3125 }
static int check_param_number(const PGresult *res, int param_num)
Definition: fe-exec.c:2740
#define InvalidOid
Definition: postgres_ext.h:36
PGresParamDesc * paramDescs
Definition: libpq-int.h:176
PGresult* PQprepare ( PGconn conn,
const char *  stmtName,
const char *  query,
int  nParams,
const Oid paramTypes 
)

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

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

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

1893 {
1894  if (!PQexecStart(conn))
1895  return NULL;
1896  if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
1897  return NULL;
1898  return PQexecFinish(conn);
1899 }
#define NULL
Definition: c.h:229
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2002
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1928
int PQsendPrepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:1228
PGresult* pqPrepareAsyncResult ( PGconn conn)

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

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

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

757 {
758  PGresult *res;
759 
760  /*
761  * conn->result is the PGresult to return. If it is NULL (which probably
762  * shouldn't happen) we assume there is an appropriate error message in
763  * conn->errorMessage.
764  */
765  res = conn->result;
766  if (!res)
768  else
769  {
770  /*
771  * Make sure PQerrorMessage agrees with result; it could be different
772  * if we have concatenated messages.
773  */
776  PQresultErrorMessage(res));
777  }
778 
779  /*
780  * Replace conn->result with next_result, if any. In the normal case
781  * there isn't a next result and we're just dropping ownership of the
782  * current result. In single-row mode this restores the situation to what
783  * it was before we created the current single-row result.
784  */
785  conn->result = conn->next_result;
786  conn->next_result = NULL;
787 
788  return res;
789 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
PGresult * result
Definition: libpq-int.h:451
PGresult * next_result
Definition: libpq-int.h:452
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:140
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define NULL
Definition: c.h:229
char * PQresultErrorMessage(const PGresult *res)
Definition: fe-exec.c:2612
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
int PQputCopyData ( PGconn conn,
const char *  buffer,
int  nbytes 
)

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

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

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

2222 {
2223  if (!conn)
2224  return -1;
2225  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2226  conn->asyncStatus != PGASYNC_COPY_BOTH)
2227  {
2229  libpq_gettext("no COPY in progress\n"));
2230  return -1;
2231  }
2232 
2233  /*
2234  * Process any NOTICE or NOTIFY messages that might be pending in the
2235  * input buffer. Since the server might generate many notices during the
2236  * COPY, we want to clean those out reasonably promptly to prevent
2237  * indefinite expansion of the input buffer. (Note: the actual read of
2238  * input data into the input buffer happens down inside pqSendSome, but
2239  * it's not authorized to get rid of the data again.)
2240  */
2241  parseInput(conn);
2242 
2243  if (nbytes > 0)
2244  {
2245  /*
2246  * Try to flush any previously sent data in preference to growing the
2247  * output buffer. If we can't enlarge the buffer enough to hold the
2248  * data, return 0 in the nonblock case, else hard error. (For
2249  * simplicity, always assume 5 bytes of overhead even in protocol 2.0
2250  * case.)
2251  */
2252  if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2253  {
2254  if (pqFlush(conn) < 0)
2255  return -1;
2256  if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2257  conn))
2258  return pqIsnonblocking(conn) ? 0 : -1;
2259  }
2260  /* Send the data (too simple to delegate to fe-protocol files) */
2261  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2262  {
2263  if (pqPutMsgStart('d', false, conn) < 0 ||
2264  pqPutnchar(buffer, nbytes, conn) < 0 ||
2265  pqPutMsgEnd(conn) < 0)
2266  return -1;
2267  }
2268  else
2269  {
2270  if (pqPutMsgStart(0, false, conn) < 0 ||
2271  pqPutnchar(buffer, nbytes, conn) < 0 ||
2272  pqPutMsgEnd(conn) < 0)
2273  return -1;
2274  }
2275  }
2276  return 1;
2277 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:963
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:346
#define pqIsnonblocking(conn)
Definition: libpq-int.h:677
int outCount
Definition: libpq-int.h:439
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:521
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1667
PQExpBufferData errorMessage
Definition: libpq-int.h:492
int outBufSize
Definition: libpq-int.h:438
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:248
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:211
ProtocolVersion pversion
Definition: libpq-int.h:404
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:589
#define libpq_gettext(x)
Definition: libpq-int.h:683
int PQputCopyEnd ( PGconn conn,
const char *  errormsg 
)

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

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

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

2289 {
2290  if (!conn)
2291  return -1;
2292  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2293  conn->asyncStatus != PGASYNC_COPY_BOTH)
2294  {
2296  libpq_gettext("no COPY in progress\n"));
2297  return -1;
2298  }
2299 
2300  /*
2301  * Send the COPY END indicator. This is simple enough that we don't
2302  * bother delegating it to the fe-protocol files.
2303  */
2304  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2305  {
2306  if (errormsg)
2307  {
2308  /* Send COPY FAIL */
2309  if (pqPutMsgStart('f', false, conn) < 0 ||
2310  pqPuts(errormsg, conn) < 0 ||
2311  pqPutMsgEnd(conn) < 0)
2312  return -1;
2313  }
2314  else
2315  {
2316  /* Send COPY DONE */
2317  if (pqPutMsgStart('c', false, conn) < 0 ||
2318  pqPutMsgEnd(conn) < 0)
2319  return -1;
2320  }
2321 
2322  /*
2323  * If we sent the COPY command in extended-query mode, we must issue a
2324  * Sync as well.
2325  */
2326  if (conn->queryclass != PGQUERY_SIMPLE)
2327  {
2328  if (pqPutMsgStart('S', false, conn) < 0 ||
2329  pqPutMsgEnd(conn) < 0)
2330  return -1;
2331  }
2332  }
2333  else
2334  {
2335  if (errormsg)
2336  {
2337  /* Oops, no way to do this in 2.0 */
2339  libpq_gettext("function requires at least protocol version 3.0\n"));
2340  return -1;
2341  }
2342  else
2343  {
2344  /* Send old-style end-of-data marker */
2345  if (pqPutMsgStart(0, false, conn) < 0 ||
2346  pqPutnchar("\\.\n", 3, conn) < 0 ||
2347  pqPutMsgEnd(conn) < 0)
2348  return -1;
2349  }
2350  }
2351 
2352  /* Return to active duty */
2353  if (conn->asyncStatus == PGASYNC_COPY_BOTH)
2354  conn->asyncStatus = PGASYNC_COPY_OUT;
2355  else
2356  conn->asyncStatus = PGASYNC_BUSY;
2358 
2359  /* Try to flush data */
2360  if (pqFlush(conn) < 0)
2361  return -1;
2362 
2363  return 1;
2364 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:963
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
PGQueryClass queryclass
Definition: libpq-int.h:381
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:521
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:181
PQExpBufferData errorMessage
Definition: libpq-int.h:492
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:248
ProtocolVersion pversion
Definition: libpq-int.h:404
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:589
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
#define libpq_gettext(x)
Definition: libpq-int.h:683
int PQputline ( PGconn conn,
const char *  s 
)

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

References PQputnbytes().

Referenced by init().

2490 {
2491  return PQputnbytes(conn, s, strlen(s));
2492 }
int PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2499
int PQputnbytes ( PGconn conn,
const char *  buffer,
int  nbytes 
)

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

References PQputCopyData().

Referenced by PQputline().

2500 {
2501  if (PQputCopyData(conn, buffer, nbytes) > 0)
2502  return 0;
2503  else
2504  return EOF;
2505 }
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2221
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:211
char* PQresStatus ( ExecStatusType  status)

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

References libpq_gettext, pgresStatus, and status().

Referenced by try_complete_step().

2605 {
2606  if ((unsigned int) status >= sizeof pgresStatus / sizeof pgresStatus[0])
2607  return libpq_gettext("invalid ExecStatusType code");
2608  return pgresStatus[status];
2609 }
char *const pgresStatus[]
Definition: fe-exec.c:32
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:224
#define libpq_gettext(x)
Definition: libpq-int.h:683
void* PQresultAlloc ( PGresult res,
size_t  nBytes 
)

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

References pqResultAlloc(), and TRUE.

Referenced by PQsetResultAttrs().

491 {
492  return pqResultAlloc(res, nBytes, TRUE);
493 }
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:506
#define TRUE
Definition: c.h:217
void* pqResultAlloc ( PGresult res,
size_t  nBytes,
bool  isBinary 
)

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

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

507 {
508  char *space;
509  PGresult_data *block;
510 
511  if (!res)
512  return NULL;
513 
514  if (nBytes <= 0)
515  return res->null_field;
516 
517  /*
518  * If alignment is needed, round up the current position to an alignment
519  * boundary.
520  */
521  if (isBinary)
522  {
523  int offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
524 
525  if (offset)
526  {
527  res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
528  res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
529  }
530  }
531 
532  /* If there's enough space in the current block, no problem. */
533  if (nBytes <= (size_t) res->spaceLeft)
534  {
535  space = res->curBlock->space + res->curOffset;
536  res->curOffset += nBytes;
537  res->spaceLeft -= nBytes;
538  return space;
539  }
540 
541  /*
542  * If the requested object is very large, give it its own block; this
543  * avoids wasting what might be most of the current block to start a new
544  * block. (We'd have to special-case requests bigger than the block size
545  * anyway.) The object is always given binary alignment in this case.
546  */
547  if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
548  {
549  block = (PGresult_data *) malloc(nBytes + PGRESULT_BLOCK_OVERHEAD);
550  if (!block)
551  return NULL;
552  space = block->space + PGRESULT_BLOCK_OVERHEAD;
553  if (res->curBlock)
554  {
555  /*
556  * Tuck special block below the active block, so that we don't
557  * have to waste the free space in the active block.
558  */
559  block->next = res->curBlock->next;
560  res->curBlock->next = block;
561  }
562  else
563  {
564  /* Must set up the new block as the first active block. */
565  block->next = NULL;
566  res->curBlock = block;
567  res->spaceLeft = 0; /* be sure it's marked full */
568  }
569  return space;
570  }
571 
572  /* Otherwise, start a new block. */
574  if (!block)
575  return NULL;
576  block->next = res->curBlock;
577  res->curBlock = block;
578  if (isBinary)
579  {
580  /* object needs full alignment */
583  }
584  else
585  {
586  /* we can cram it right after the overhead pointer */
587  res->curOffset = sizeof(PGresult_data);
589  }
590 
591  space = block->space + res->curOffset;
592  res->curOffset += nBytes;
593  res->spaceLeft -= nBytes;
594  return space;
595 }
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:128
int curOffset
Definition: libpq-int.h:209
#define PGRESULT_BLOCK_OVERHEAD
Definition: fe-exec.c:129
PGresult_data * curBlock
Definition: libpq-int.h:208
#define PGRESULT_SEP_ALLOC_THRESHOLD
Definition: fe-exec.c:130
#define NULL
Definition: c.h:229
#define PGRESULT_DATA_BLOCKSIZE
Definition: fe-exec.c:127
char* PQresultErrorField ( const PGresult res,
int  fieldcode 
)

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

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

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

2659 {
2660  PGMessageField *pfield;
2661 
2662  if (!res)
2663  return NULL;
2664  for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
2665  {
2666  if (pfield->code == fieldcode)
2667  return pfield->contents;
2668  }
2669  return NULL;
2670 }
PGMessageField * errFields
Definition: libpq-int.h:197
struct pgMessageField * next
Definition: libpq-int.h:144
#define NULL
Definition: c.h:229
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:146
char* PQresultErrorMessage ( const PGresult res)
ExecStatusType PQresultStatus ( const PGresult res)

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

References PGRES_FATAL_ERROR, and pg_result::resultStatus.

Referenced by _doSetSessionAuth(), _doSetWithOids(), _selectOutputSchema(), _selectTablespace(), AcceptResult(), BaseBackup(), check_loadable_libraries(), ClearOrSaveResult(), close_cursor(), create_cursor(), CreateReplicationSlot(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_record_internal(), do_sql_command(), doCustom(), DropReplicationSlot(), dumpTableData_copy(), ecpg_check_PQresult(), ecpg_is_type_an_array(), ecpg_process_output(), EndDBCopyMode(), ExecQueryUsingCursor(), execute_dml_stmt(), executeCommand(), executeMaintenanceCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlQuery(), ExecuteSqlStatement(), executeStatement(), fetch_more_data(), get_create_object_cmd(), get_remote_estimate(), GetQueryResult(), handleCopyIn(), handleCopyOut(), HandleEndOfCopyStream(), init(), libpq_executeFileMap(), libpqConnect(), libpqGetFile(), libpqProcessFileList(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_exec(), libpqrcv_identify_system(), libpqrcv_PQexec(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_startstreaming(), lo_close(), lo_creat(), lo_create(), lo_lseek(), lo_lseek64(), lo_open(), lo_read(), lo_tell(), lo_tell64(), lo_truncate(), lo_truncate64(), lo_unlink(), lo_write(), lockTableForWorker(), lookup_object_oid(), main(), materializeQueryResult(), materializeResult(), pgfdw_subxact_callback(), pgfdw_xact_callback(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresEndForeignModify(), postgresExecForeignDelete(), postgresExecForeignInsert(), postgresExecForeignUpdate(), postgresImportForeignSchema(), postgresReScanForeignScan(), PQconnectPoll(), PQencryptPasswordConn(), pqSetenvPoll(), prepare_foreign_modify(), PrintQueryResults(), PrintResultsInCrosstab(), ProcessResult(), PSQLexecWatch(), ReceiveAndUnpackTarFile(), receiveFileChunks(), ReceiveTarFile(), ReceiveXlogStream(), run_permutation(), run_simple_query(), RunIdentifySystem(), sendCommand(), SendQuery(), sql_exec(), storeQueryResult(), StreamLogicalLog(), try_complete_step(), tryExecuteStatement(), and vacuumlo().

2597 {
2598  if (!res)
2599  return PGRES_FATAL_ERROR;
2600  return res->resultStatus;
2601 }
ExecStatusType resultStatus
Definition: libpq-int.h:177
char* pqResultStrdup ( PGresult res,
const char *  str 
)

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

References FALSE, and pqResultAlloc().

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

603 {
604  char *space = (char *) pqResultAlloc(res, strlen(str) + 1, FALSE);
605 
606  if (space)
607  strcpy(space, str);
608  return space;
609 }
#define FALSE
Definition: c.h:221
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:506
char* PQresultVerboseErrorMessage ( const PGresult res,
PGVerbosity  verbosity,
PGContextVisibility  show_context 
)

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

2623 {
2624  PQExpBufferData workBuf;
2625 
2626  /*
2627  * Because the caller is expected to free the result string, we must
2628  * strdup any constant result. We use plain strdup and document that
2629  * callers should expect NULL if out-of-memory.
2630  */
2631  if (!res ||
2632  (res->resultStatus != PGRES_FATAL_ERROR &&
2634  return strdup(libpq_gettext("PGresult is not an error result\n"));
2635 
2636  initPQExpBuffer(&workBuf);
2637 
2638  /*
2639  * Currently, we pass this off to fe-protocol3.c in all cases; it will
2640  * behave reasonably sanely with an error reported by fe-protocol2.c as
2641  * well. If necessary, we could record the protocol version in PGresults
2642  * so as to be able to invoke a version-specific message formatter, but
2643  * for now there's no need.
2644  */
2645  pqBuildErrorMessage3(&workBuf, res, verbosity, show_context);
2646 
2647  /* If insufficient memory to format the message, fail cleanly */
2648  if (PQExpBufferDataBroken(workBuf))
2649  {
2650  termPQExpBuffer(&workBuf);
2651  return strdup(libpq_gettext("out of memory\n"));
2652  }
2653 
2654  return workBuf.data;
2655 }
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
Definition: fe-protocol3.c:982
ExecStatusType resultStatus
Definition: libpq-int.h:177
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
#define libpq_gettext(x)
Definition: libpq-int.h:683
int pqRowProcessor ( PGconn conn,
const char **  errmsgp 
)

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

References pg_conn::asyncStatus, pg_result::attDescs, pgresAttDesc::format, i, pgresAttValue::len, pgDataValue::len, pg_conn::next_result, NULL, 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, TRUE, val, pgresAttValue::value, and value.

Referenced by getAnotherTuple().

1031 {
1032  PGresult *res = conn->result;
1033  int nfields = res->numAttributes;
1034  const PGdataValue *columns = conn->rowBuf;
1035  PGresAttValue *tup;
1036  int i;
1037 
1038  /*
1039  * In single-row mode, make a new PGresult that will hold just this one
1040  * row; the original conn->result is left unchanged so that it can be used
1041  * again as the template for future rows.
1042  */
1043  if (conn->singleRowMode)
1044  {
1045  /* Copy everything that should be in the result at this point */
1046  res = PQcopyResult(res,
1049  if (!res)
1050  return 0;
1051  }
1052 
1053  /*
1054  * Basically we just allocate space in the PGresult for each field and
1055  * copy the data over.
1056  *
1057  * Note: on malloc failure, we return 0 leaving *errmsgp still NULL, which
1058  * caller will take to mean "out of memory". This is preferable to trying
1059  * to set up such a message here, because evidently there's not enough
1060  * memory for gettext() to do anything.
1061  */
1062  tup = (PGresAttValue *)
1063  pqResultAlloc(res, nfields * sizeof(PGresAttValue), TRUE);
1064  if (tup == NULL)
1065  goto fail;
1066 
1067  for (i = 0; i < nfields; i++)
1068  {
1069  int clen = columns[i].len;
1070 
1071  if (clen < 0)
1072  {
1073  /* null field */
1074  tup[i].len = NULL_LEN;
1075  tup[i].value = res->null_field;
1076  }
1077  else
1078  {
1079  bool isbinary = (res->attDescs[i].format != 0);
1080  char *val;
1081 
1082  val = (char *) pqResultAlloc(res, clen + 1, isbinary);
1083  if (val == NULL)
1084  goto fail;
1085 
1086  /* copy and zero-terminate the data (even if it's binary) */
1087  memcpy(val, columns[i].value, clen);
1088  val[clen] = '\0';
1089 
1090  tup[i].len = clen;
1091  tup[i].value = val;
1092  }
1093  }
1094 
1095  /* And add the tuple to the PGresult's tuple array */
1096  if (!pqAddTuple(res, tup))
1097  goto fail;
1098 
1099  /*
1100  * Success. In single-row mode, make the result available to the client
1101  * immediately.
1102  */
1103  if (conn->singleRowMode)
1104  {
1105  /* Change result status to special single-row value */
1107  /* Stash old result for re-use later */
1108  conn->next_result = conn->result;
1109  conn->result = res;
1110  /* And mark the result ready to return */
1111  conn->asyncStatus = PGASYNC_READY;
1112  }
1113 
1114  return 1;
1115 
1116 fail:
1117  /* release locally allocated PGresult, if we made one */
1118  if (res != conn->result)
1119  PQclear(res);
1120  return 0;
1121 }
bool singleRowMode
Definition: libpq-int.h:387
static bool pqAddTuple(PGresult *res, PGresAttValue *tup)
Definition: fe-exec.c:853
PGresult * PQcopyResult(const PGresult *src, int flags)
Definition: fe-exec.c:291
#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:451
PGresult * next_result
Definition: libpq-int.h:452
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
#define PG_COPYRES_EVENTS
Definition: libpq-fe.h:36
#define PG_COPYRES_NOTICEHOOKS
Definition: libpq-fe.h:37
PGdataValue * rowBuf
Definition: libpq-int.h:447
int numAttributes
Definition: libpq-int.h:170
#define PG_COPYRES_ATTRS
Definition: libpq-fe.h:34
void PQclear(PGresult *res)
Definition: fe-exec.c:650
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:506
#define NULL
Definition: c.h:229
int i
char * value
Definition: libpq-int.h:138
#define TRUE
Definition: c.h:217
static struct @121 value
ExecStatusType resultStatus
Definition: libpq-int.h:177
long val
Definition: informix.c:689
void pqSaveErrorResult ( PGconn conn)

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

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

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

729 {
730  /*
731  * If no old async result, just let PQmakeEmptyPGresult make one. Likewise
732  * if old result is not an error message.
733  */
734  if (conn->result == NULL ||
736  conn->result->errMsg == NULL)
737  {
738  pqClearAsyncResult(conn);
740  }
741  else
742  {
743  /* Else, concatenate error message to existing async result. */
745  }
746 }
char * errMsg
Definition: libpq-int.h:196
PGresult * result
Definition: libpq-int.h:451
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:140
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define NULL
Definition: c.h:229
void pqCatenateResultError(PGresult *res, const char *msg)
Definition: fe-exec.c:631
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:705
ExecStatusType resultStatus
Definition: libpq-int.h:177
void pqSaveMessageField ( PGresult res,
char  code,
const char *  value 
)

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

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

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

892 {
893  PGMessageField *pfield;
894 
895  pfield = (PGMessageField *)
896  pqResultAlloc(res,
897  offsetof(PGMessageField, contents) +
898  strlen(value) + 1,
899  TRUE);
900  if (!pfield)
901  return; /* out of memory? */
902  pfield->code = code;
903  strcpy(pfield->contents, value);
904  pfield->next = res->errFields;
905  res->errFields = pfield;
906 }
PGMessageField * errFields
Definition: libpq-int.h:197
struct pgMessageField * next
Definition: libpq-int.h:144
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:506
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:146
#define TRUE
Definition: c.h:217
static struct @121 value
#define offsetof(type, field)
Definition: c.h:555
void pqSaveParameterStatus ( PGconn conn,
const char *  name,
const char *  value 
)

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

References pg_conn::client_encoding, free, malloc, pgParameterStatus::name, pgParameterStatus::next, NULL, 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().

913 {
914  pgParameterStatus *pstatus;
915  pgParameterStatus *prev;
916 
917  if (conn->Pfdebug)
918  fprintf(conn->Pfdebug, "pqSaveParameterStatus: '%s' = '%s'\n",
919  name, value);
920 
921  /*
922  * Forget any old information about the parameter
923  */
924  for (pstatus = conn->pstatus, prev = NULL;
925  pstatus != NULL;
926  prev = pstatus, pstatus = pstatus->next)
927  {
928  if (strcmp(pstatus->name, name) == 0)
929  {
930  if (prev)
931  prev->next = pstatus->next;
932  else
933  conn->pstatus = pstatus->next;
934  free(pstatus); /* frees name and value strings too */
935  break;
936  }
937  }
938 
939  /*
940  * Store new info as a single malloc block
941  */
942  pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
943  strlen(name) +strlen(value) + 2);
944  if (pstatus)
945  {
946  char *ptr;
947 
948  ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
949  pstatus->name = ptr;
950  strcpy(ptr, name);
951  ptr += strlen(name) + 1;
952  pstatus->value = ptr;
953  strcpy(ptr, value);
954  pstatus->next = conn->pstatus;
955  conn->pstatus = pstatus;
956  }
957 
958  /*
959  * Special hacks: remember client_encoding and
960  * standard_conforming_strings, and convert server version to a numeric
961  * form. We keep the first two of these in static variables as well, so
962  * that PQescapeString and PQescapeBytea can behave somewhat sanely (at
963  * least in single-connection-using programs).
964  */
965  if (strcmp(name, "client_encoding") == 0)
966  {
968  /* if we don't recognize the encoding name, fall back to SQL_ASCII */
969  if (conn->client_encoding < 0)
972  }
973  else if (strcmp(name, "standard_conforming_strings") == 0)
974  {
975  conn->std_strings = (strcmp(value, "on") == 0);
977  }
978  else if (strcmp(name, "server_version") == 0)
979  {
980  int cnt;
981  int vmaj,
982  vmin,
983  vrev;
984 
985  cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
986 
987  if (cnt == 3)
988  {
989  /* old style, e.g. 9.6.1 */
990  conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
991  }
992  else if (cnt == 2)
993  {
994  if (vmaj >= 10)
995  {
996  /* new style, e.g. 10.1 */
997  conn->sversion = 100 * 100 * vmaj + vmin;
998  }
999  else
1000  {
1001  /* old style without minor version, e.g. 9.6devel */
1002  conn->sversion = (100 * vmaj + vmin) * 100;
1003  }
1004  }
1005  else if (cnt == 1)
1006  {
1007  /* new style without minor version, e.g. 10devel */
1008  conn->sversion = 100 * 100 * vmaj;
1009  }
1010  else
1011  conn->sversion = 0; /* unknown */
1012  }
1013 }
static bool static_std_strings
Definition: fe-exec.c:50
int pg_char_to_encoding(const char *name)
Definition: encnames.c:551
FILE * Pfdebug
Definition: libpq-int.h:367
#define malloc(a)
Definition: header.h:50
int sversion
Definition: libpq-int.h:405
struct pgParameterStatus pgParameterStatus
static int static_client_encoding
Definition: fe-exec.c:49
pgParameterStatus * pstatus
Definition: libpq-int.h:422
bool std_strings
Definition: libpq-int.h:424
#define free(a)
Definition: header.h:65
#define NULL
Definition: c.h:229
struct pgParameterStatus * next
Definition: libpq-int.h:258
const char * name
Definition: encode.c:521
int client_encoding
Definition: libpq-int.h:423
static struct @121 value
static int PQsendDescribe ( PGconn conn,
char  desc_type,
const char *  desc_target 
)
static

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

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

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

2128 {
2129  /* Treat null desc_target as empty string */
2130  if (!desc_target)
2131  desc_target = "";
2132 
2133  if (!PQsendQueryStart(conn))
2134  return 0;
2135 
2136  /* This isn't gonna work on a 2.0 server */
2137  if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2138  {
2140  libpq_gettext("function requires at least protocol version 3.0\n"));
2141  return 0;
2142  }
2143 
2144  /* construct the Describe message */
2145  if (pqPutMsgStart('D', false, conn) < 0 ||
2146  pqPutc(desc_type, conn) < 0 ||
2147  pqPuts(desc_target, conn) < 0 ||
2148  pqPutMsgEnd(conn) < 0)
2149  goto sendFailed;
2150 
2151  /* construct the Sync message */
2152  if (pqPutMsgStart('S', false, conn) < 0 ||
2153  pqPutMsgEnd(conn) < 0)
2154  goto sendFailed;
2155 
2156  /* remember we are doing a Describe */
2157  conn->queryclass = PGQUERY_DESCRIBE;
2158 
2159  /* reset last-query string (not relevant now) */
2160  if (conn->last_query)
2161  {
2162  free(conn->last_query);
2163  conn->last_query = NULL;
2164  }
2165 
2166  /*
2167  * Give the data a push. In nonblock mode, don't complain if we're unable
2168  * to send it all; PQgetResult() will do any additional flushing needed.
2169  */
2170  if (pqFlush(conn) < 0)
2171  goto sendFailed;
2172 
2173  /* OK, it's launched! */
2174  conn->asyncStatus = PGASYNC_BUSY;
2175  return 1;
2176 
2177 sendFailed:
2178  pqHandleSendFailure(conn);
2179  return 0;
2180 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:963
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
void pqHandleSendFailure(PGconn *conn)
Definition: fe-exec.c:1582
PGQueryClass queryclass
Definition: libpq-int.h:381
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:521
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
int pqPutc(char c, PGconn *conn)
Definition: fe-misc.c:114
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:181
char * last_query
Definition: libpq-int.h:382
static bool PQsendQueryStart(PGconn *conn)
Definition: fe-exec.c:1365
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define free(a)
Definition: header.h:65
#define NULL
Definition: c.h:229
ProtocolVersion pversion
Definition: libpq-int.h:404
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:589
#define libpq_gettext(x)
Definition: libpq-int.h:683
int PQsendDescribePortal ( PGconn conn,
const char *  portal 
)

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

References PQsendDescribe().

2113 {
2114  return PQsendDescribe(conn, 'P', portal);
2115 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2127
int PQsendDescribePrepared ( PGconn conn,
const char *  stmt 
)

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

References PQsendDescribe().

2100 {
2101  return PQsendDescribe(conn, 'S', stmt);
2102 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2127
int PQsendPrepare ( PGconn conn,
const char *  stmtName,
const char *  query,
int  nParams,
const Oid paramTypes 
)

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

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

Referenced by PQprepare(), and prepare_foreign_modify().

1231 {
1232  if (!PQsendQueryStart(conn))
1233  return 0;
1234 
1235  /* check the arguments */
1236  if (!stmtName)
1237  {
1239  libpq_gettext("statement name is a null pointer\n"));
1240  return 0;
1241  }
1242  if (!query)
1243  {
1245  libpq_gettext("command string is a null pointer\n"));
1246  return 0;
1247  }
1248  if (nParams < 0 || nParams > 65535)
1249  {
1251  libpq_gettext("number of parameters must be between 0 and 65535\n"));
1252  return 0;
1253  }
1254 
1255  /* This isn't gonna work on a 2.0 server */
1256  if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1257  {
1259  libpq_gettext("function requires at least protocol version 3.0\n"));
1260  return 0;
1261  }
1262 
1263  /* construct the Parse message */
1264  if (pqPutMsgStart('P', false, conn) < 0 ||
1265  pqPuts(stmtName, conn) < 0 ||
1266  pqPuts(query, conn) < 0)
1267  goto sendFailed;
1268 
1269  if (nParams > 0 && paramTypes)
1270  {
1271  int i;
1272 
1273  if (pqPutInt(nParams, 2, conn) < 0)
1274  goto sendFailed;
1275  for (i = 0; i < nParams; i++)
1276  {
1277  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1278  goto sendFailed;
1279  }
1280  }
1281  else
1282  {
1283  if (pqPutInt(0, 2, conn) < 0)
1284  goto sendFailed;
1285  }
1286  if (pqPutMsgEnd(conn) < 0)
1287  goto sendFailed;
1288 
1289  /* construct the Sync message */
1290  if (pqPutMsgStart('S', false, conn) < 0 ||
1291  pqPutMsgEnd(conn) < 0)
1292  goto sendFailed;
1293 
1294  /* remember we are doing just a Parse */
1295  conn->queryclass = PGQUERY_PREPARE;
1296 
1297  /* and remember the query text too, if possible */
1298  /* if insufficient memory, last_query just winds up NULL */
1299  if (conn->last_query)
1300  free(conn->last_query);
1301  conn->last_query = strdup(query);
1302 
1303  /*
1304  * Give the data a push. In nonblock mode, don't complain if we're unable
1305  * to send it all; PQgetResult() will do any additional flushing needed.
1306  */
1307  if (pqFlush(conn) < 0)
1308  goto sendFailed;
1309 
1310  /* OK, it's launched! */
1311  conn->asyncStatus = PGASYNC_BUSY;
1312  return 1;
1313 
1314 sendFailed:
1315  pqHandleSendFailure(conn);
1316  return 0;
1317 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:963
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
void pqHandleSendFailure(PGconn *conn)
Definition: fe-exec.c:1582
PGQueryClass queryclass
Definition: libpq-int.h:381
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:521
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:309
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:181
char * last_query
Definition: libpq-int.h:382
static bool PQsendQueryStart(PGconn *conn)
Definition: fe-exec.c:1365
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define free(a)
Definition: header.h:65
ProtocolVersion pversion
Definition: libpq-int.h:404
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:589
int i
#define libpq_gettext(x)
Definition: libpq-int.h:683
int PQsendQuery ( PGconn conn,
const char *  query 
)

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

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

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

1133 {
1134  if (!PQsendQueryStart(conn))
1135  return 0;
1136 
1137  /* check the argument */
1138  if (!query)
1139  {
1141  libpq_gettext("command string is a null pointer\n"));
1142  return 0;
1143  }
1144 
1145  /* construct the outgoing Query message */
1146  if (pqPutMsgStart('Q', false, conn) < 0 ||
1147  pqPuts(query, conn) < 0 ||
1148  pqPutMsgEnd(conn) < 0)
1149  {
1150  pqHandleSendFailure(conn);
1151  return 0;
1152  }
1153 
1154  /* remember we are using simple query protocol */
1155  conn->queryclass = PGQUERY_SIMPLE;
1156 
1157  /* and remember the query text too, if possible */
1158  /* if insufficient memory, last_query just winds up NULL */
1159  if (conn->last_query)
1160  free(conn->last_query);
1161  conn->last_query = strdup(query);
1162 
1163  /*
1164  * Give the data a push. In nonblock mode, don't complain if we're unable
1165  * to send it all; PQgetResult() will do any additional flushing needed.
1166  */
1167  if (pqFlush(conn) < 0)
1168  {
1169  pqHandleSendFailure(conn);
1170  return 0;
1171  }
1172 
1173  /* OK, it's launched! */
1174  conn->asyncStatus = PGASYNC_BUSY;
1175  return 1;
1176 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:963
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
void pqHandleSendFailure(PGconn *conn)
Definition: fe-exec.c:1582
PGQueryClass queryclass
Definition: libpq-int.h:381
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:521
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:181
char * last_query
Definition: libpq-int.h:382
static bool PQsendQueryStart(PGconn *conn)
Definition: fe-exec.c:1365
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define free(a)
Definition: header.h:65
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:589
#define libpq_gettext(x)
Definition: libpq-int.h:683
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 1406 of file fe-exec.c.

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

Referenced by PQsendQueryParams(), and PQsendQueryPrepared().

1415 {
1416  int i;
1417 
1418  /* This isn't gonna work on a 2.0 server */
1419  if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1420  {
1422  libpq_gettext("function requires at least protocol version 3.0\n"));
1423  return 0;
1424  }
1425 
1426  /*
1427  * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync,
1428  * using specified statement name and the unnamed portal.
1429  */
1430 
1431  if (command)
1432  {
1433  /* construct the Parse message */
1434  if (pqPutMsgStart('P', false, conn) < 0 ||
1435  pqPuts(stmtName, conn) < 0 ||
1436  pqPuts(command, conn) < 0)
1437  goto sendFailed;
1438  if (nParams > 0 && paramTypes)
1439  {
1440  if (pqPutInt(nParams, 2, conn) < 0)
1441  goto sendFailed;
1442  for (i = 0; i < nParams; i++)
1443  {
1444  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1445  goto sendFailed;
1446  }
1447  }
1448  else
1449  {
1450  if (pqPutInt(0, 2, conn) < 0)
1451  goto sendFailed;
1452  }
1453  if (pqPutMsgEnd(conn) < 0)
1454  goto sendFailed;
1455  }
1456 
1457  /* Construct the Bind message */
1458  if (pqPutMsgStart('B', false, conn) < 0 ||
1459  pqPuts("", conn) < 0 ||
1460  pqPuts(stmtName, conn) < 0)
1461  goto sendFailed;
1462 
1463  /* Send parameter formats */
1464  if (nParams > 0 && paramFormats)
1465  {
1466  if (pqPutInt(nParams, 2, conn) < 0)
1467  goto sendFailed;
1468  for (i = 0; i < nParams; i++)
1469  {
1470  if (pqPutInt(paramFormats[i], 2, conn) < 0)
1471  goto sendFailed;
1472  }
1473  }
1474  else
1475  {
1476  if (pqPutInt(0, 2, conn) < 0)
1477  goto sendFailed;
1478  }
1479 
1480  if (pqPutInt(nParams, 2, conn) < 0)
1481  goto sendFailed;
1482 
1483  /* Send parameters */
1484  for (i = 0; i < nParams; i++)
1485  {
1486  if (paramValues && paramValues[i])
1487  {
1488  int nbytes;
1489 
1490  if (paramFormats && paramFormats[i] != 0)
1491  {
1492  /* binary parameter */
1493  if (paramLengths)
1494  nbytes = paramLengths[i];
1495  else
1496  {
1498  libpq_gettext("length must be given for binary parameter\n"));
1499  goto sendFailed;
1500  }
1501  }
1502  else
1503  {
1504  /* text parameter, do not use paramLengths */
1505  nbytes = strlen(paramValues[i]);
1506  }
1507  if (pqPutInt(nbytes, 4, conn) < 0 ||
1508  pqPutnchar(paramValues[i], nbytes, conn) < 0)
1509  goto sendFailed;
1510  }
1511  else
1512  {
1513  /* take the param as NULL */
1514  if (pqPutInt(-1, 4, conn) < 0)
1515  goto sendFailed;
1516  }
1517  }
1518  if (pqPutInt(1, 2, conn) < 0 ||
1519  pqPutInt(resultFormat, 2, conn))
1520  goto sendFailed;
1521  if (pqPutMsgEnd(conn) < 0)
1522  goto sendFailed;
1523 
1524  /* construct the Describe Portal message */
1525  if (pqPutMsgStart('D', false, conn) < 0 ||
1526  pqPutc('P', conn) < 0 ||
1527  pqPuts("", conn) < 0 ||
1528  pqPutMsgEnd(conn) < 0)
1529  goto sendFailed;
1530 
1531  /* construct the Execute message */
1532  if (pqPutMsgStart('E', false, conn) < 0 ||
1533  pqPuts("", conn) < 0 ||
1534  pqPutInt(0, 4, conn) < 0 ||
1535  pqPutMsgEnd(conn) < 0)
1536  goto sendFailed;
1537 
1538  /* construct the Sync message */
1539  if (pqPutMsgStart('S', false, conn) < 0 ||
1540  pqPutMsgEnd(conn) < 0)
1541  goto sendFailed;
1542 
1543  /* remember we are using extended query protocol */
1544  conn->queryclass = PGQUERY_EXTENDED;
1545 
1546  /* and remember the query text too, if possible */
1547  /* if insufficient memory, last_query just winds up NULL */
1548  if (conn->last_query)
1549  free(conn->last_query);
1550  if (command)
1551  conn->last_query = strdup(command);
1552  else
1553  conn->last_query = NULL;
1554 
1555  /*
1556  * Give the data a push. In nonblock mode, don't complain if we're unable
1557  * to send it all; PQgetResult() will do any additional flushing needed.
1558  */
1559  if (pqFlush(conn) < 0)
1560  goto sendFailed;
1561 
1562  /* OK, it's launched! */
1563  conn->asyncStatus = PGASYNC_BUSY;
1564  return 1;
1565 
1566 sendFailed:
1567  pqHandleSendFailure(conn);
1568  return 0;
1569 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:963
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
void pqHandleSendFailure(PGconn *conn)
Definition: fe-exec.c:1582
PGQueryClass queryclass
Definition: libpq-int.h:381
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:521
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:309
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
int pqPutc(char c, PGconn *conn)
Definition: fe-misc.c:114
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:181
char * last_query
Definition: libpq-int.h:382
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define free(a)
Definition: header.h:65
#define NULL
Definition: c.h:229
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:248
ProtocolVersion pversion
Definition: libpq-int.h:404
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:589
int i
#define libpq_gettext(x)
Definition: libpq-int.h:683
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 1183 of file fe-exec.c.

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

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

1191 {
1192  if (!PQsendQueryStart(conn))
1193  return 0;
1194 
1195  /* check the arguments */
1196  if (!command)
1197  {
1199  libpq_gettext("command string is a null pointer\n"));
1200  return 0;
1201  }
1202  if (nParams < 0 || nParams > 65535)
1203  {
1205  libpq_gettext("number of parameters must be between 0 and 65535\n"));
1206  return 0;
1207  }
1208 
1209  return PQsendQueryGuts(conn,
1210  command,
1211  "", /* use unnamed statement */
1212  nParams,
1213  paramTypes,
1214  paramValues,
1215  paramLengths,
1216  paramFormats,
1217  resultFormat);
1218 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
static int PQsendQueryGuts(PGconn *conn, const char *command, const char *stmtName, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:1406
static bool PQsendQueryStart(PGconn *conn)
Definition: fe-exec.c:1365
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define libpq_gettext(x)
Definition: libpq-int.h:683
int PQsendQueryPrepared ( PGconn conn,
const char *  stmtName,
int  nParams,
const char *const *  paramValues,
const int *  paramLengths,
const int *  paramFormats,
int  resultFormat 
)

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

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

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

1332 {
1333  if (!PQsendQueryStart(conn))
1334  return 0;
1335 
1336  /* check the arguments */
1337  if (!stmtName)
1338  {
1340  libpq_gettext("statement name is a null pointer\n"));
1341  return 0;
1342  }
1343  if (nParams < 0 || nParams > 65535)
1344  {
1346  libpq_gettext("number of parameters must be between 0 and 65535\n"));
1347  return 0;
1348  }
1349 
1350  return PQsendQueryGuts(conn,
1351  NULL, /* no command to parse */
1352  stmtName,
1353  nParams,
1354  NULL, /* no param types */
1355  paramValues,
1356  paramLengths,
1357  paramFormats,
1358  resultFormat);
1359 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
static int PQsendQueryGuts(PGconn *conn, const char *command, const char *stmtName, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:1406
static bool PQsendQueryStart(PGconn *conn)
Definition: fe-exec.c:1365
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define NULL
Definition: c.h:229
#define libpq_gettext(x)
Definition: libpq-int.h:683
static bool PQsendQueryStart ( PGconn conn)
static

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

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

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

1366 {
1367  if (!conn)
1368  return false;
1369 
1370  /* clear the error string */
1372 
1373  /* Don't try to send if we know there's no live connection. */
1374  if (conn->status != CONNECTION_OK)
1375  {
1377  libpq_gettext("no connection to the server\n"));
1378  return false;
1379  }
1380  /* Can't send while already busy, either. */
1381  if (conn->asyncStatus != PGASYNC_IDLE)
1382  {
1384  libpq_gettext("another command is already in progress\n"));
1385  return false;
1386  }
1387 
1388  /* initialize async result-accumulation state */
1389  pqClearAsyncResult(conn);
1390 
1391  /* reset single-row processing mode */
1392  conn->singleRowMode = false;
1393 
1394  /* ready to send command message */
1395  return true;
1396 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
bool singleRowMode
Definition: libpq-int.h:387
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
PQExpBufferData errorMessage
Definition: libpq-int.h:492
ConnStatusType status
Definition: libpq-int.h:378
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:705
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
#define libpq_gettext(x)
Definition: libpq-int.h:683
int PQsetnonblocking ( PGconn conn,
int  arg 
)

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

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

3136 {
3137  bool barg;
3138 
3139  if (!conn || conn->status == CONNECTION_BAD)
3140  return -1;
3141 
3142  barg = (arg ? TRUE : FALSE);
3143 
3144  /* early out if the socket is already in the state requested */
3145  if (barg == conn->nonblocking)
3146  return 0;
3147 
3148  /*
3149  * to guarantee constancy for flushing/query/result-polling behavior we
3150  * need to flush the send queue at this point in order to guarantee proper
3151  * behavior. this is ok because either they are making a transition _from_
3152  * or _to_ blocking mode, either way we can block them.
3153  */
3154  /* if we are going from blocking to non-blocking flush here */
3155  if (pqFlush(conn))
3156  return -1;
3157 
3158  conn->nonblocking = barg;
3159 
3160  return 0;
3161 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:963
#define FALSE
Definition: c.h:221
ConnStatusType status
Definition: libpq-int.h:378
bool nonblocking
Definition: libpq-int.h:385
void * arg
#define TRUE
Definition: c.h:217
int PQsetResultAttrs ( PGresult res,
int  numAttributes,
PGresAttDesc attDescs 
)

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

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

Referenced by PQcopyResult().

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

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

References pg_result::errMsg, NULL, and pqResultStrdup().

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

617 {
618  if (!res)
619  return;
620  if (msg && *msg)
621  res->errMsg = pqResultStrdup(res, msg);
622  else
623  res->errMsg = NULL;
624 }
char * errMsg
Definition: libpq-int.h:196
#define NULL
Definition: c.h:229
char * pqResultStrdup(PGresult *res, const char *str)
Definition: fe-exec.c:602
int PQsetSingleRowMode ( PGconn conn)

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

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

Referenced by receiveFileChunks(), and storeQueryResult().

1605 {
1606  /*
1607  * Only allow setting the flag when we have launched a query and not yet
1608  * received any results.
1609  */
1610  if (!conn)
1611  return 0;
1612  if (conn->asyncStatus != PGASYNC_BUSY)
1613  return 0;
1614  if (conn->queryclass != PGQUERY_SIMPLE &&
1615  conn->queryclass != PGQUERY_EXTENDED)
1616  return 0;
1617  if (conn->result)
1618  return 0;
1619 
1620  /* OK, set flag */
1621  conn->singleRowMode = true;
1622  return 1;
1623 }
bool singleRowMode
Definition: libpq-int.h:387
PGQueryClass queryclass
Definition: libpq-int.h:381
PGresult * result
Definition: libpq-int.h:451
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
int PQsetvalue ( PGresult res,
int  tup_num,
int  field_num,
char *  value,
int  len 
)

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

References check_field_number(), FALSE, i, pgresAttValue::len, pg_result::ntups, NULL, pg_result::null_field, NULL_LEN, pg_result::numAttributes, pqAddTuple(), pqResultAlloc(), TRUE, pg_result::tuples, and pgresAttValue::value.

Referenced by PQcopyResult().

422 {
423  PGresAttValue *attval;
424 
425  if (!check_field_number(res, field_num))
426  return FALSE;
427 
428  /* Invalid tup_num, must be <= ntups */
429  if (tup_num < 0 || tup_num > res->ntups)
430  return FALSE;
431 
432  /* need to allocate a new tuple? */
433  if (tup_num == res->ntups)
434  {
435  PGresAttValue *tup;
436  int i;
437 
438  tup = (PGresAttValue *)
439  pqResultAlloc(res, res->numAttributes * sizeof(PGresAttValue),
440  TRUE);
441 
442  if (!tup)
443  return FALSE;
444 
445  /* initialize each column to NULL */
446  for (i = 0; i < res->numAttributes; i++)
447  {
448  tup[i].len = NULL_LEN;
449  tup[i].value = res->null_field;
450  }
451 
452  /* add it to the array */
453  if (!pqAddTuple(res, tup))
454  return FALSE;
455  }
456 
457  attval = &res->tuples[tup_num][field_num];
458 
459  /* treat either NULL_LEN or NULL value pointer as a NULL field */
460  if (len == NULL_LEN || value == NULL)
461  {
462  attval->len = NULL_LEN;
463  attval->value = res->null_field;
464  }
465  else if (len <= 0)
466  {
467  attval->len = 0;
468  attval->value = res->null_field;
469  }
470  else
471  {
472  attval->value = (char *) pqResultAlloc(res, len + 1, TRUE);
473  if (!attval->value)
474  return FALSE;
475  attval->len = len;
476  memcpy(attval->value, value, len);
477  attval->value[len] = '\0';
478  }
479 
480  return TRUE;
481 }
static bool pqAddTuple(PGresult *res, PGresAttValue *tup)
Definition: fe-exec.c:853
#define NULL_LEN
Definition: libpq-int.h:133
char null_field[1]
Definition: libpq-int.h:201
PGresAttValue ** tuples
Definition: libpq-int.h:172
#define FALSE
Definition: c.h:221
int numAttributes
Definition: libpq-int.h:170
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2702
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:506
int ntups
Definition: libpq-int.h:169
#define NULL
Definition: c.h:229
int i
char * value
Definition: libpq-int.h:138
#define TRUE
Definition: c.h:217
static struct @121 value
unsigned char* PQunescapeBytea ( const unsigned char *  strtext,
size_t *  retbuflen 
)

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

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

Referenced by dumpTrigger().

3656 {
3657  size_t strtextlen,
3658  buflen;
3659  unsigned char *buffer,
3660  *tmpbuf;
3661  size_t i,
3662  j;
3663 
3664  if (strtext == NULL)
3665  return NULL;
3666 
3667  strtextlen = strlen((const char *) strtext);
3668 
3669  if (strtext[0] == '\\' && strtext[1] == 'x')
3670  {
3671  const unsigned char *s;
3672  unsigned char *p;
3673 
3674  buflen = (strtextlen - 2) / 2;
3675  /* Avoid unportable malloc(0) */
3676  buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
3677  if (buffer == NULL)
3678  return NULL;
3679 
3680  s = strtext + 2;
3681  p = buffer;
3682  while (*s)
3683  {
3684  char v1,
3685  v2;
3686 
3687  /*
3688  * Bad input is silently ignored. Note that this includes
3689  * whitespace between hex pairs, which is allowed by byteain.
3690  */
3691  v1 = get_hex(*s++);
3692  if (!*s || v1 == (char) -1)
3693  continue;
3694  v2 = get_hex(*s++);
3695  if (v2 != (char) -1)
3696  *p++ = (v1 << 4) | v2;
3697  }
3698 
3699  buflen = p - buffer;
3700  }
3701  else