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

Go to the source code of this file.

Macros

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

Functions

static PGEventdupEvents (PGEvent *events, int count, size_t *memSize)
 
static bool pqAddTuple (PGresult *res, PGresAttValue *tup, const char **errmsgp)
 
static int PQsendQueryInternal (PGconn *conn, const char *query, bool newQuery)
 
static bool PQsendQueryStart (PGconn *conn, bool newQuery)
 
static int PQsendQueryGuts (PGconn *conn, const char *command, const char *stmtName, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
static void parseInput (PGconn *conn)
 
static PGresultgetCopyResult (PGconn *conn, ExecStatusType copytype)
 
static bool PQexecStart (PGconn *conn)
 
static PGresultPQexecFinish (PGconn *conn)
 
static int PQsendTypedCommand (PGconn *conn, char command, char type, const char *target)
 
static int check_field_number (const PGresult *res, int field_num)
 
static void pqPipelineProcessQueue (PGconn *conn)
 
static int pqPipelineSyncInternal (PGconn *conn, bool immediate_flush)
 
static int pqPipelineFlush (PGconn *conn)
 
PGresultPQmakeEmptyPGresult (PGconn *conn, ExecStatusType status)
 
int PQsetResultAttrs (PGresult *res, int numAttributes, PGresAttDesc *attDescs)
 
PGresultPQcopyResult (const PGresult *src, int flags)
 
int PQsetvalue (PGresult *res, int tup_num, int field_num, char *value, int len)
 
void * PQresultAlloc (PGresult *res, size_t nBytes)
 
void * pqResultAlloc (PGresult *res, size_t nBytes, bool isBinary)
 
size_t PQresultMemorySize (const PGresult *res)
 
char * pqResultStrdup (PGresult *res, const char *str)
 
void pqSetResultError (PGresult *res, PQExpBuffer errorMessage, int offset)
 
void PQclear (PGresult *res)
 
void pqClearAsyncResult (PGconn *conn)
 
void pqSaveErrorResult (PGconn *conn)
 
static void pqSaveWriteError (PGconn *conn)
 
PGresultpqPrepareAsyncResult (PGconn *conn)
 
void pqInternalNotice (const PGNoticeHooks *hooks, const char *fmt,...)
 
void pqSaveMessageField (PGresult *res, char code, const char *value)
 
void pqSaveParameterStatus (PGconn *conn, const char *name, const char *value)
 
int pqRowProcessor (PGconn *conn, const char **errmsgp)
 
static PGcmdQueueEntrypqAllocCmdQueueEntry (PGconn *conn)
 
static void pqAppendCmdQueueEntry (PGconn *conn, PGcmdQueueEntry *entry)
 
static void pqRecycleCmdQueueEntry (PGconn *conn, PGcmdQueueEntry *entry)
 
int PQsendQuery (PGconn *conn, const char *query)
 
int PQsendQueryContinue (PGconn *conn, const char *query)
 
int PQsendQueryParams (PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
int PQsendPrepare (PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
 
int PQsendQueryPrepared (PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
static bool canChangeResultMode (PGconn *conn)
 
int PQsetSingleRowMode (PGconn *conn)
 
int PQsetChunkedRowsMode (PGconn *conn, int chunkSize)
 
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)
 
PGresultPQclosePrepared (PGconn *conn, const char *stmt)
 
PGresultPQclosePortal (PGconn *conn, const char *portal)
 
int PQsendClosePrepared (PGconn *conn, const char *stmt)
 
int PQsendClosePortal (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 *buffer, int length)
 
int PQgetlineAsync (PGconn *conn, char *buffer, int bufsize)
 
int PQputline (PGconn *conn, const char *string)
 
int PQputnbytes (PGconn *conn, const char *buffer, int nbytes)
 
int PQendcopy (PGconn *conn)
 
PGresultPQfn (PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
 
int PQenterPipelineMode (PGconn *conn)
 
int PQexitPipelineMode (PGconn *conn)
 
void pqCommandQueueAdvance (PGconn *conn, bool isReadyForQuery, bool gotSync)
 
int PQpipelineSync (PGconn *conn)
 
int PQsendPipelineSync (PGconn *conn)
 
int PQsendFlushRequest (PGconn *conn)
 
ExecStatusType PQresultStatus (const PGresult *res)
 
char * PQresStatus (ExecStatusType status)
 
char * PQresultErrorMessage (const PGresult *res)
 
char * PQresultVerboseErrorMessage (const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
 
char * PQresultErrorField (const PGresult *res, int fieldcode)
 
int PQntuples (const PGresult *res)
 
int PQnfields (const PGresult *res)
 
int PQbinaryTuples (const PGresult *res)
 
static int check_tuple_field_number (const PGresult *res, int tup_num, int field_num)
 
static int check_param_number (const PGresult *res, int param_num)
 
char * PQfname (const PGresult *res, int field_num)
 
int PQfnumber (const PGresult *res, const char *field_name)
 
Oid PQftable (const PGresult *res, int field_num)
 
int PQftablecol (const PGresult *res, int field_num)
 
int PQfformat (const PGresult *res, int field_num)
 
Oid PQftype (const PGresult *res, int field_num)
 
int PQfsize (const PGresult *res, int field_num)
 
int PQfmod (const PGresult *res, int field_num)
 
char * PQcmdStatus (PGresult *res)
 
char * PQoidStatus (const PGresult *res)
 
Oid PQoidValue (const PGresult *res)
 
char * PQcmdTuples (PGresult *res)
 
char * PQgetvalue (const PGresult *res, int tup_num, int field_num)
 
int PQgetlength (const PGresult *res, int tup_num, int field_num)
 
int PQgetisnull (const PGresult *res, int tup_num, int field_num)
 
int PQnparams (const PGresult *res)
 
Oid PQparamtype (const PGresult *res, int param_num)
 
int PQsetnonblocking (PGconn *conn, int arg)
 
int PQisnonblocking (const PGconn *conn)
 
int PQisthreadsafe (void)
 
int PQflush (PGconn *conn)
 
void PQfreemem (void *ptr)
 
void PQfreeNotify (PGnotify *notify)
 
static size_t PQescapeStringInternal (PGconn *conn, char *to, const char *from, size_t length, int *error, int encoding, bool std_strings)
 
size_t PQescapeStringConn (PGconn *conn, char *to, const char *from, size_t length, int *error)
 
size_t PQescapeString (char *to, const char *from, size_t length)
 
static char * PQescapeInternal (PGconn *conn, const char *str, size_t len, bool as_ident)
 
char * PQescapeLiteral (PGconn *conn, const char *str, size_t len)
 
char * PQescapeIdentifier (PGconn *conn, const char *str, size_t len)
 
static char get_hex (char c)
 
static unsigned char * PQescapeByteaInternal (PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length, bool std_strings, bool use_hex)
 
unsigned char * PQescapeByteaConn (PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length)
 
unsigned char * PQescapeBytea (const unsigned char *from, size_t from_length, size_t *to_length)
 
unsigned char * PQunescapeBytea (const unsigned char *strtext, size_t *retbuflen)
 

Variables

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

Macro Definition Documentation

◆ ISFIRSTOCTDIGIT

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

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

◆ ISOCTDIGIT

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

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

◆ OCTVAL

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

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

◆ PGRESULT_ALIGN_BOUNDARY

#define PGRESULT_ALIGN_BOUNDARY   MAXIMUM_ALIGNOF /* from configure */

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

◆ PGRESULT_BLOCK_OVERHEAD

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

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

◆ PGRESULT_DATA_BLOCKSIZE

#define PGRESULT_DATA_BLOCKSIZE   2048

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

◆ PGRESULT_SEP_ALLOC_THRESHOLD

#define PGRESULT_SEP_ALLOC_THRESHOLD   (PGRESULT_DATA_BLOCKSIZE / 2)

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

Function Documentation

◆ canChangeResultMode()

static bool canChangeResultMode ( PGconn conn)
static

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

1926{
1927 /*
1928 * Only allow changing the mode when we have launched a query and not yet
1929 * received any results.
1930 */
1931 if (!conn)
1932 return false;
1934 return false;
1935 if (!conn->cmd_queue_head ||
1938 return false;
1940 return false;
1941 return true;
1942}
@ PGASYNC_BUSY
Definition: libpq-int.h:224
@ PGQUERY_SIMPLE
Definition: libpq-int.h:328
@ PGQUERY_EXTENDED
Definition: libpq-int.h:329
#define pgHavePendingResult(conn)
Definition: libpq-int.h:916
PGconn * conn
Definition: streamutil.c:52
PGQueryClass queryclass
Definition: libpq-int.h:353
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:465
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:491

References pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, PGASYNC_BUSY, pgHavePendingResult, PGQUERY_EXTENDED, PGQUERY_SIMPLE, and PGcmdQueueEntry::queryclass.

Referenced by PQsetChunkedRowsMode(), and PQsetSingleRowMode().

◆ check_field_number()

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

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

3511{
3512 if (!res)
3513 return false; /* no way to display error message... */
3514 if (field_num < 0 || field_num >= res->numAttributes)
3515 {
3517 "column number %d is out of range 0..%d",
3518 field_num, res->numAttributes - 1);
3519 return false;
3520 }
3521 return true;
3522}
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:938
PGNoticeHooks noticeHooks
Definition: libpq-int.h:191
int numAttributes
Definition: libpq-int.h:175

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

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

◆ check_param_number()

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

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

3549{
3550 if (!res)
3551 return false; /* no way to display error message... */
3552 if (param_num < 0 || param_num >= res->numParameters)
3553 {
3555 "parameter number %d is out of range 0..%d",
3556 param_num, res->numParameters - 1);
3557 return false;
3558 }
3559
3560 return true;
3561}
int numParameters
Definition: libpq-int.h:180

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

Referenced by PQparamtype().

◆ check_tuple_field_number()

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

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

3527{
3528 if (!res)
3529 return false; /* no way to display error message... */
3530 if (tup_num < 0 || tup_num >= res->ntups)
3531 {
3533 "row number %d is out of range 0..%d",
3534 tup_num, res->ntups - 1);
3535 return false;
3536 }
3537 if (field_num < 0 || field_num >= res->numAttributes)
3538 {
3540 "column number %d is out of range 0..%d",
3541 field_num, res->numAttributes - 1);
3542 return false;
3543 }
3544 return true;
3545}
int ntups
Definition: libpq-int.h:174

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

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

◆ dupEvents()

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

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

409{
410 PGEvent *newEvents;
411 size_t msize;
412 int i;
413
414 if (!events || count <= 0)
415 return NULL;
416
417 msize = count * sizeof(PGEvent);
418 newEvents = (PGEvent *) malloc(msize);
419 if (!newEvents)
420 return NULL;
421
422 for (i = 0; i < count; i++)
423 {
424 newEvents[i].proc = events[i].proc;
425 newEvents[i].passThrough = events[i].passThrough;
426 newEvents[i].data = NULL;
427 newEvents[i].resultInitialized = false;
428 newEvents[i].name = strdup(events[i].name);
429 if (!newEvents[i].name)
430 {
431 while (--i >= 0)
432 free(newEvents[i].name);
433 free(newEvents);
434 return NULL;
435 }
436 msize += strlen(events[i].name) + 1;
437 }
438
439 *memSize += msize;
440 return newEvents;
441}
#define free(a)
Definition: header.h:65
#define malloc(a)
Definition: header.h:50
int i
Definition: isn.c:74
struct PGEvent PGEvent
void * passThrough
Definition: libpq-int.h:167
PGEventProc proc
Definition: libpq-int.h:165
const char * name

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

Referenced by PQcopyResult(), and PQmakeEmptyPGresult().

◆ get_hex()

static char get_hex ( char  c)
inlinestatic

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

4390{
4391 int res = -1;
4392
4393 if (c > 0 && c < 127)
4394 res = hexlookup[(unsigned char) c];
4395
4396 return (char) res;
4397}
static const int8 hexlookup[128]
Definition: fe-exec.c:4377
char * c

References hexlookup.

Referenced by PQunescapeBytea().

◆ getCopyResult()

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

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

2225{
2226 /*
2227 * If the server connection has been lost, don't pretend everything is
2228 * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
2229 * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
2230 * error in the earlier steps in PQgetResult). The text returned in the
2231 * result is whatever is in conn->errorMessage; we hope that was filled
2232 * with something relevant when the lost connection was detected.
2233 */
2234 if (conn->status != CONNECTION_OK)
2235 {
2238 return pqPrepareAsyncResult(conn);
2239 }
2240
2241 /* If we have an async result for the COPY, return that */
2242 if (conn->result && conn->result->resultStatus == copytype)
2243 return pqPrepareAsyncResult(conn);
2244
2245 /* Otherwise, invent a suitable PGresult */
2246 return PQmakeEmptyPGresult(conn, copytype);
2247}
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:851
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:803
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:159
@ CONNECTION_OK
Definition: libpq-fe.h:83
@ PGASYNC_IDLE
Definition: libpq-int.h:223
PGresult * result
Definition: libpq-int.h:594
ConnStatusType status
Definition: libpq-int.h:464
ExecStatusType resultStatus
Definition: libpq-int.h:182

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

Referenced by PQgetResult().

◆ parseInput()

static void parseInput ( PGconn conn)
static

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

2021{
2023}
void pqParseInput3(PGconn *conn)
Definition: fe-protocol3.c:66

References conn, and pqParseInput3().

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

◆ pqAddTuple()

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

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

994{
995 if (res->ntups >= res->tupArrSize)
996 {
997 /*
998 * Try to grow the array.
999 *
1000 * We can use realloc because shallow copying of the structure is
1001 * okay. Note that the first time through, res->tuples is NULL. While
1002 * ANSI says that realloc() should act like malloc() in that case,
1003 * some old C libraries (like SunOS 4.1.x) coredump instead. On
1004 * failure realloc is supposed to return NULL without damaging the
1005 * existing allocation. Note that the positions beyond res->ntups are
1006 * garbage, not necessarily NULL.
1007 */
1008 int newSize;
1009 PGresAttValue **newTuples;
1010
1011 /*
1012 * Since we use integers for row numbers, we can't support more than
1013 * INT_MAX rows. Make sure we allow that many, though.
1014 */
1015 if (res->tupArrSize <= INT_MAX / 2)
1016 newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
1017 else if (res->tupArrSize < INT_MAX)
1018 newSize = INT_MAX;
1019 else
1020 {
1021 *errmsgp = libpq_gettext("PGresult cannot support more than INT_MAX tuples");
1022 return false;
1023 }
1024
1025 /*
1026 * Also, on 32-bit platforms we could, in theory, overflow size_t even
1027 * before newSize gets to INT_MAX. (In practice we'd doubtless hit
1028 * OOM long before that, but let's check.)
1029 */
1030#if INT_MAX >= (SIZE_MAX / 2)
1031 if (newSize > SIZE_MAX / sizeof(PGresAttValue *))
1032 {
1033 *errmsgp = libpq_gettext("size_t overflow");
1034 return false;
1035 }
1036#endif
1037
1038 if (res->tuples == NULL)
1039 newTuples = (PGresAttValue **)
1040 malloc(newSize * sizeof(PGresAttValue *));
1041 else
1042 newTuples = (PGresAttValue **)
1043 realloc(res->tuples, newSize * sizeof(PGresAttValue *));
1044 if (!newTuples)
1045 return false; /* malloc or realloc failed */
1046 res->memorySize +=
1047 (newSize - res->tupArrSize) * sizeof(PGresAttValue *);
1048 res->tupArrSize = newSize;
1049 res->tuples = newTuples;
1050 }
1051 res->tuples[res->ntups] = tup;
1052 res->ntups++;
1053 return true;
1054}
#define realloc(a, b)
Definition: header.h:60
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:78
#define libpq_gettext(x)
Definition: libpq-int.h:934
size_t memorySize
Definition: libpq-int.h:217
PGresAttValue ** tuples
Definition: libpq-int.h:177
int tupArrSize
Definition: libpq-int.h:179

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

Referenced by pqRowProcessor(), and PQsetvalue().

◆ pqAllocCmdQueueEntry()

static PGcmdQueueEntry * pqAllocCmdQueueEntry ( PGconn conn)
static

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

1307{
1308 PGcmdQueueEntry *entry;
1309
1310 if (conn->cmd_queue_recycle == NULL)
1311 {
1312 entry = (PGcmdQueueEntry *) malloc(sizeof(PGcmdQueueEntry));
1313 if (entry == NULL)
1314 {
1315 libpq_append_conn_error(conn, "out of memory");
1316 return NULL;
1317 }
1318 }
1319 else
1320 {
1321 entry = conn->cmd_queue_recycle;
1322 conn->cmd_queue_recycle = entry->next;
1323 }
1324 entry->next = NULL;
1325 entry->query = NULL;
1326
1327 return entry;
1328}
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition: fe-misc.c:1381
struct PGcmdQueueEntry * next
Definition: libpq-int.h:355
PGcmdQueueEntry * cmd_queue_recycle
Definition: libpq-int.h:498

References pg_conn::cmd_queue_recycle, conn, libpq_append_conn_error(), malloc, PGcmdQueueEntry::next, and PGcmdQueueEntry::query.

Referenced by pqPipelineSyncInternal(), PQsendPrepare(), PQsendQueryGuts(), PQsendQueryInternal(), and PQsendTypedCommand().

◆ pqAppendCmdQueueEntry()

static void pqAppendCmdQueueEntry ( PGconn conn,
PGcmdQueueEntry entry 
)
static

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

1340{
1341 Assert(entry->next == NULL);
1342
1343 if (conn->cmd_queue_head == NULL)
1344 conn->cmd_queue_head = entry;
1345 else
1346 conn->cmd_queue_tail->next = entry;
1347
1348 conn->cmd_queue_tail = entry;
1349
1350 switch (conn->pipelineStatus)
1351 {
1352 case PQ_PIPELINE_OFF:
1353 case PQ_PIPELINE_ON:
1354
1355 /*
1356 * When not in pipeline aborted state, if there's a result ready
1357 * to be consumed, let it be so (that is, don't change away from
1358 * READY or READY_MORE); otherwise set us busy to wait for
1359 * something to arrive from the server.
1360 */
1363 break;
1364
1366
1367 /*
1368 * In aborted pipeline state, we don't expect anything from the
1369 * server (since we don't send any queries that are queued).
1370 * Therefore, if IDLE then do what PQgetResult would do to let
1371 * itself consume commands from the queue; if we're in any other
1372 * state, we don't have to do anything.
1373 */
1374 if (conn->asyncStatus == PGASYNC_IDLE ||
1377 break;
1378 }
1379}
static void pqPipelineProcessQueue(PGconn *conn)
Definition: fe-exec.c:3180
Assert(PointerIsAligned(start, uint64))
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:186
@ PQ_PIPELINE_ABORTED
Definition: libpq-fe.h:188
@ PQ_PIPELINE_ON
Definition: libpq-fe.h:187
@ PGASYNC_PIPELINE_IDLE
Definition: libpq-int.h:233
PGcmdQueueEntry * cmd_queue_tail
Definition: libpq-int.h:492
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:471

References Assert(), pg_conn::asyncStatus, pg_conn::cmd_queue_head, pg_conn::cmd_queue_tail, conn, PGcmdQueueEntry::next, PGASYNC_BUSY, PGASYNC_IDLE, PGASYNC_PIPELINE_IDLE, pg_conn::pipelineStatus, PQ_PIPELINE_ABORTED, PQ_PIPELINE_OFF, PQ_PIPELINE_ON, and pqPipelineProcessQueue().

Referenced by pqPipelineSyncInternal(), PQsendPrepare(), PQsendQueryGuts(), PQsendQueryInternal(), and PQsendTypedCommand().

◆ PQbinaryTuples()

int PQbinaryTuples ( const PGresult res)

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

3498{
3499 if (!res)
3500 return 0;
3501 return res->binary;
3502}
int binary
Definition: libpq-int.h:184

References pg_result::binary.

Referenced by HandleCopyResult().

◆ PQclear()

void PQclear ( PGresult res)

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

722{
723 PGresult_data *block;
724 int i;
725
726 /* As a convenience, do nothing for a NULL pointer */
727 if (!res)
728 return;
729 /* Also, do nothing if the argument is OOM_result */
730 if ((const PGresult *) res == &OOM_result)
731 return;
732
733 /* Close down any events we may have */
734 for (i = 0; i < res->nEvents; i++)
735 {
736 /* only send DESTROY to successfully-initialized event procs */
737 if (res->events[i].resultInitialized)
738 {
740
741 evt.result = res;
742 (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
743 res->events[i].passThrough);
744 }
745 free(res->events[i].name);
746 }
747
748 free(res->events);
749
750 /* Free all the subsidiary blocks */
751 while ((block = res->curBlock) != NULL)
752 {
753 res->curBlock = block->next;
754 free(block);
755 }
756
757 /* Free the top-level tuple pointer array */
758 free(res->tuples);
759
760 /* zero out the pointer fields to catch programming errors */
761 res->attDescs = NULL;
762 res->tuples = NULL;
763 res->paramDescs = NULL;
764 res->errFields = NULL;
765 res->events = NULL;
766 res->nEvents = 0;
767 /* res->curBlock was zeroed out earlier */
768
769 /* Free the PGresult structure itself */
770 free(res);
771}
static const PGresult OOM_result
Definition: fe-exec.c:49
@ PGEVT_RESULTDESTROY
Definition: libpq-events.h:34
char * name
Definition: libpq-int.h:166
bool resultInitialized
Definition: libpq-int.h:169
int nEvents
Definition: libpq-int.h:193
PGresAttDesc * attDescs
Definition: libpq-int.h:176
PGMessageField * errFields
Definition: libpq-int.h:202
PGresParamDesc * paramDescs
Definition: libpq-int.h:181
PGEvent * events
Definition: libpq-int.h:192
PGresult_data * curBlock
Definition: libpq-int.h:213
PGresult_data * next
Definition: libpq-int.h:110

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

Referenced by _check_database_version(), _doSetSessionAuth(), _printTableAccessMethodNoStorage(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), add_tablespace_footer(), addFooterToPublicationDesc(), advanceConnectionState(), append_depends_on_extension(), appendQualifiedRelation(), BaseBackup(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), buildShSecLabels(), check_and_drop_existing_subscriptions(), check_for_connection_status(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_is_install_user(), check_loadable_libraries(), check_new_cluster_logical_replication_slots(), check_new_cluster_subscription_configuration(), check_old_cluster_subscription_state(), check_prepare_conn(), check_publisher(), check_subscriber(), ClearOrSaveResult(), close_cursor(), cluster_all_databases(), collectBinaryUpgradeClassOids(), collectComments(), collectRoleNames(), collectSecLabels(), collectSequences(), compile_database_list(), compile_relation_list_one_db(), confirm_query_canceled_impl(), connect_database(), ConnectDatabase(), connectDatabase(), connectToServer(), convertTSFunction(), create_cursor(), create_logical_replication_slot(), create_logical_replication_slots(), create_new_objects(), create_publication(), create_subscription(), CreateReplicationSlot(), createViewAsClause(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_res_error(), dblink_res_internalerror(), deallocate_one(), deallocate_query(), describeAccessMethods(), describeAggregates(), describeConfigurationParameters(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describePublications(), DescribeQuery(), describeRoleGrants(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), descriptor_free(), discardAbortedPipelineResults(), discardUntilSync(), do_lo_import(), do_sql_command_end(), drop_existing_subscriptions(), drop_failover_replication_slots(), drop_publication(), drop_replication_slot(), dropDBs(), DropReplicationSlot(), dropRoles(), dropTablespaces(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpCompositeType(), dumpConversion(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpDomain(), dumpEnumType(), dumpForeignServer(), dumpFunc(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRelationStats(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSearchPath(), dumpSequence(), dumpSequenceData(), dumpStatisticsExt(), dumpTable(), dumpTableAttach(), 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(), enable_subscription(), EndDBCopyMode(), exec_command_password(), execute_foreign_modify(), executeCommand(), executeMaintenanceCommand(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlStatement(), executeStatement(), expand_dbname_patterns(), expand_extension_name_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), fail_lo_xact(), fetch_more_data(), finish_lo_xact(), generate_object_name(), get_create_object_cmd(), get_db_infos(), get_language_name(), get_loadable_libraries(), get_next_possible_free_pg_type_oid(), get_parallel_tabidx_list(), get_parallel_tables_list(), get_primary_sysid(), get_remote_estimate(), get_returning_data(), get_subscription_count(), get_synchronized_snapshot(), get_table_relkind(), get_tablespace_paths(), get_template0_info(), getAccessMethods(), getAdditionalACLs(), getAggregates(), getCasts(), getCollations(), GetConnection(), getConstraints(), getConversions(), getCopyStart(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getLOs(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getParamDescriptions(), getPartitioningInfo(), getPolicies(), getProcLangs(), getPublicationNamespaces(), getPublications(), getPublicationTables(), getRowDescriptions(), getRules(), GetSlotInformation(), getSubscriptions(), getSubscriptionTables(), getTableAttrs(), GetTableInfo(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), handleCopyIn(), HandleCopyResult(), HandleEndOfCopyStream(), init_libpq_conn(), initPopulateTable(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_alter_slot(), libpqrcv_connect(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_exec(), libpqrcv_identify_system(), libpqrcv_PQexec(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_startstreaming(), libpqsrv_get_result_last(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtendedStats(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listLargeObjects(), listOneExtensionContents(), listOperatorClasses(), listOperatorFamilies(), listOpFamilyFunctions(), listOpFamilyOperators(), listPartitionedTables(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), lo_close(), lo_creat(), lo_create(), lo_initialize(), lo_lseek(), lo_lseek64(), lo_open(), lo_read(), lo_tell(), lo_tell64(), lo_truncate(), lo_truncate64(), lo_unlink(), lo_write(), lockTableForWorker(), lookup_object_oid(), main(), materializeResult(), objectDescription(), old_9_6_invalidate_hash_indexes(), permissionsList(), pgfdw_cancel_query_end(), pgfdw_exec_cleanup_query_end(), pgfdw_finish_pre_commit_cleanup(), pgfdw_get_cleanup_result(), pgfdw_report_error(), pgfdw_xact_callback(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresEndDirectModify(), postgresGetAnalyzeInfoForForeignTable(), postgresImportForeignSchema(), postgresReScanForeignScan(), pqClearAsyncResult(), PQconnectPoll(), PQcopyResult(), PQencryptPasswordConn(), pqEndcopy3(), PQexecFinish(), PQexecStart(), pqGetErrorNotice3(), pqInternalNotice(), PQmakeEmptyPGresult(), PQsetClientEncoding(), prepare_common(), prepare_foreign_modify(), prepareCommand(), process_query_result(), process_queued_fetch_requests(), process_result(), processExtensionTables(), processQueryResult(), readCommandResponse(), ReceiveCopyData(), ReceiveXlogStream(), reindex_all_databases(), retrieve_objects(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_permutation(), run_simple_command(), run_simple_query(), RunIdentifySystem(), SendQuery(), server_is_in_recovery(), set_frozenxids(), set_locale_and_encoding(), set_replication_progress(), set_restrict_relation_kind(), setup_connection(), setup_publisher(), sql_conn(), sql_exec(), start_lo_xact(), store_returning_result(), storeQueryResult(), StreamLogicalLog(), TableCommandResultHandler(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), try_complete_step(), tryExecuteStatement(), vacuum_all_databases(), vacuumlo(), and wait_for_connection_state().

◆ pqClearAsyncResult()

void pqClearAsyncResult ( PGconn conn)

◆ PQclosePortal()

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

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

2540{
2541 if (!PQexecStart(conn))
2542 return NULL;
2543 if (!PQsendTypedCommand(conn, PqMsg_Close, 'P', portal))
2544 return NULL;
2545 return PQexecFinish(conn);
2546}
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2410
static int PQsendTypedCommand(PGconn *conn, char command, char type, const char *target)
Definition: fe-exec.c:2589
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2344
#define PqMsg_Close
Definition: protocol.h:20

References conn, PQexecFinish(), PQexecStart(), PqMsg_Close, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQclosePrepared()

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

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

2522{
2523 if (!PQexecStart(conn))
2524 return NULL;
2526 return NULL;
2527 return PQexecFinish(conn);
2528}
#define stmt
Definition: indent_codes.h:59

References conn, PQexecFinish(), PQexecStart(), PqMsg_Close, PQsendTypedCommand(), and stmt.

Referenced by test_prepared().

◆ PQcmdStatus()

char * PQcmdStatus ( PGresult res)

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

3753{
3754 if (!res)
3755 return NULL;
3756 return res->cmdStatus;
3757}
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:183

References pg_result::cmdStatus.

Referenced by dblink_exec(), ecpg_process_output(), ExecQueryAndProcessResults(), materializeResult(), PrintQueryStatus(), and test_pipelined_insert().

◆ PQcmdTuples()

char * PQcmdTuples ( PGresult res)

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

3823{
3824 char *p,
3825 *c;
3826
3827 if (!res)
3828 return "";
3829
3830 if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3831 {
3832 p = res->cmdStatus + 7;
3833 /* INSERT: skip oid and space */
3834 while (*p && *p != ' ')
3835 p++;
3836 if (*p == 0)
3837 goto interpret_error; /* no space? */
3838 p++;
3839 }
3840 else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3841 strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3842 strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3843 p = res->cmdStatus + 7;
3844 else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0 ||
3845 strncmp(res->cmdStatus, "MERGE ", 6) == 0)
3846 p = res->cmdStatus + 6;
3847 else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3848 strncmp(res->cmdStatus, "COPY ", 5) == 0)
3849 p = res->cmdStatus + 5;
3850 else
3851 return "";
3852
3853 /* check that we have an integer (at least one digit, nothing else) */
3854 for (c = p; *c; c++)
3855 {
3856 if (!isdigit((unsigned char) *c))
3857 goto interpret_error;
3858 }
3859 if (c == p)
3860 goto interpret_error;
3861
3862 return p;
3863
3864interpret_error:
3866 "could not interpret result from server: %s",
3867 res->cmdStatus);
3868 return "";
3869}

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

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

◆ pqCommandQueueAdvance()

void pqCommandQueueAdvance ( PGconn conn,
bool  isReadyForQuery,
bool  gotSync 
)

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

3143{
3144 PGcmdQueueEntry *prevquery;
3145
3146 if (conn->cmd_queue_head == NULL)
3147 return;
3148
3149 /*
3150 * If processing a query of simple query protocol, we only advance the
3151 * queue when we receive the ReadyForQuery message for it.
3152 */
3153 if (conn->cmd_queue_head->queryclass == PGQUERY_SIMPLE && !isReadyForQuery)
3154 return;
3155
3156 /*
3157 * If we're waiting for a SYNC, don't advance the queue until we get one.
3158 */
3159 if (conn->cmd_queue_head->queryclass == PGQUERY_SYNC && !gotSync)
3160 return;
3161
3162 /* delink element from queue */
3163 prevquery = conn->cmd_queue_head;
3165
3166 /* If the queue is now empty, reset the tail too */
3167 if (conn->cmd_queue_head == NULL)
3168 conn->cmd_queue_tail = NULL;
3169
3170 /* and make the queue element recyclable */
3171 prevquery->next = NULL;
3172 pqRecycleCmdQueueEntry(conn, prevquery);
3173}
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1386
@ PGQUERY_SYNC
Definition: libpq-int.h:332

References pg_conn::cmd_queue_head, pg_conn::cmd_queue_tail, conn, PGcmdQueueEntry::next, PGQUERY_SIMPLE, PGQUERY_SYNC, pqRecycleCmdQueueEntry(), and PGcmdQueueEntry::queryclass.

Referenced by PQgetResult(), and pqParseInput3().

◆ PQconsumeInput()

int PQconsumeInput ( PGconn conn)

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

1985{
1986 if (!conn)
1987 return 0;
1988
1989 /*
1990 * for non-blocking connections try to flush the send-queue, otherwise we
1991 * may never get a response for something that may not have already been
1992 * sent because it's in our write buffer!
1993 */
1994 if (pqIsnonblocking(conn))
1995 {
1996 if (pqFlush(conn) < 0)
1997 return 0;
1998 }
1999
2000 /*
2001 * Load more data, if available. We do this no matter what state we are
2002 * in, since we are probably getting called because the application wants
2003 * to get rid of a read-select condition. Note that we will NOT block
2004 * waiting for more input.
2005 */
2006 if (pqReadData(conn) < 0)
2007 return 0;
2008
2009 /* Parsing of the data waits till later. */
2010 return 1;
2011}
int pqReadData(PGconn *conn)
Definition: fe-misc.c:580
int pqFlush(PGconn *conn)
Definition: fe-misc.c:968
#define pqIsnonblocking(conn)
Definition: libpq-int.h:923

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

Referenced by advanceConnectionState(), confirm_query_canceled_impl(), CopyStreamReceive(), dblink_get_notify(), dblink_is_busy(), do_sql_command_end(), ecpg_process_output(), libpqrcv_PQgetResult(), libpqrcv_receive(), libpqsrv_get_result(), main(), pgfdw_cancel_query_end(), pgfdw_exec_cleanup_query_end(), pgfdw_get_cleanup_result(), postgresForeignAsyncNotify(), PQconnectPoll(), PrintNotifications(), process_slot(), StreamLogicalLog(), test_nosync(), test_pipelined_insert(), test_uniqviol(), try_complete_step(), and wait_on_slots().

◆ PQcopyResult()

PGresult * PQcopyResult ( const PGresult src,
int  flags 
)

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

319{
320 PGresult *dest;
321 int i;
322
323 if (!src)
324 return NULL;
325
327 if (!dest)
328 return NULL;
329
330 /* Always copy these over. Is cmdStatus really useful here? */
331 dest->client_encoding = src->client_encoding;
332 strcpy(dest->cmdStatus, src->cmdStatus);
333
334 /* Wants attrs? */
335 if (flags & (PG_COPYRES_ATTRS | PG_COPYRES_TUPLES))
336 {
338 {
339 PQclear(dest);
340 return NULL;
341 }
342 }
343
344 /* Wants to copy tuples? */
345 if (flags & PG_COPYRES_TUPLES)
346 {
347 int tup,
348 field;
349
350 for (tup = 0; tup < src->ntups; tup++)
351 {
352 for (field = 0; field < src->numAttributes; field++)
353 {
354 if (!PQsetvalue(dest, tup, field,
355 src->tuples[tup][field].value,
356 src->tuples[tup][field].len))
357 {
358 PQclear(dest);
359 return NULL;
360 }
361 }
362 }
363 }
364
365 /* Wants to copy notice hooks? */
366 if (flags & PG_COPYRES_NOTICEHOOKS)
367 dest->noticeHooks = src->noticeHooks;
368
369 /* Wants to copy PGEvents? */
370 if ((flags & PG_COPYRES_EVENTS) && src->nEvents > 0)
371 {
372 dest->events = dupEvents(src->events, src->nEvents,
373 &dest->memorySize);
374 if (!dest->events)
375 {
376 PQclear(dest);
377 return NULL;
378 }
379 dest->nEvents = src->nEvents;
380 }
381
382 /* Okay, trigger PGEVT_RESULTCOPY event */
383 for (i = 0; i < dest->nEvents; i++)
384 {
385 /* We don't fire events that had some previous failure */
386 if (src->events[i].resultInitialized)
387 {
389
390 evt.src = src;
391 evt.dest = dest;
392 if (dest->events[i].proc(PGEVT_RESULTCOPY, &evt,
393 dest->events[i].passThrough))
394 dest->events[i].resultInitialized = true;
395 }
396 }
397
398 return dest;
399}
int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs)
Definition: fe-exec.c:249
static PGEvent * dupEvents(PGEvent *events, int count, size_t *memSize)
Definition: fe-exec.c:408
int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len)
Definition: fe-exec.c:452
@ PGEVT_RESULTCOPY
Definition: libpq-events.h:33
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:127
#define PG_COPYRES_TUPLES
Definition: libpq-fe.h:69
#define PG_COPYRES_ATTRS
Definition: libpq-fe.h:68
#define PG_COPYRES_EVENTS
Definition: libpq-fe.h:70
#define PG_COPYRES_NOTICEHOOKS
Definition: libpq-fe.h:71
const PGresult * src
Definition: libpq-events.h:60
PGresult * dest
Definition: libpq-events.h:61
int client_encoding
Definition: libpq-int.h:194
char * value
Definition: libpq-int.h:143

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

Referenced by pqRowProcessor().

◆ PQdescribePortal()

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

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

2475{
2476 if (!PQexecStart(conn))
2477 return NULL;
2478 if (!PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal))
2479 return NULL;
2480 return PQexecFinish(conn);
2481}
#define PqMsg_Describe
Definition: protocol.h:21

References conn, PQexecFinish(), PQexecStart(), PqMsg_Describe, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQdescribePrepared()

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

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

2456{
2457 if (!PQexecStart(conn))
2458 return NULL;
2460 return NULL;
2461 return PQexecFinish(conn);
2462}

References conn, PQexecFinish(), PQexecStart(), PqMsg_Describe, PQsendTypedCommand(), and stmt.

Referenced by DescribeQuery(), ECPGdescribe(), and test_prepared().

◆ PQendcopy()

int PQendcopy ( PGconn conn)

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

2950{
2951 if (!conn)
2952 return 0;
2953
2954 return pqEndcopy3(conn);
2955}
int pqEndcopy3(PGconn *conn)

References conn, and pqEndcopy3().

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

◆ PQenterPipelineMode()

int PQenterPipelineMode ( PGconn conn)

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

3043{
3044 if (!conn)
3045 return 0;
3046
3047 /* succeed with no action if already in pipeline mode */
3049 return 1;
3050
3052 {
3053 libpq_append_conn_error(conn, "cannot enter pipeline mode, connection not idle");
3054 return 0;
3055 }
3056
3058
3059 return 1;
3060}

References pg_conn::asyncStatus, conn, libpq_append_conn_error(), PGASYNC_IDLE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, and PQ_PIPELINE_ON.

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

◆ PQescapeBytea()

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

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

4529{
4530 return PQescapeByteaInternal(NULL, from, from_length, to_length,
4532 false /* can't use hex */ );
4533}
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:4416
static bool static_std_strings
Definition: fe-exec.c:60

References PQescapeByteaInternal(), and static_std_strings.

◆ PQescapeByteaConn()

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

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

4515{
4516 if (!conn)
4517 return NULL;
4518
4519 if (conn->cmd_queue_head == NULL)
4521
4522 return PQescapeByteaInternal(conn, from, from_length, to_length,
4524 (conn->sversion >= 90000));
4525}
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:907
bool std_strings
Definition: libpq-int.h:554
int sversion
Definition: libpq-int.h:506

References pg_conn::cmd_queue_head, conn, pqClearConnErrorState, PQescapeByteaInternal(), pg_conn::std_strings, and pg_conn::sversion.

◆ PQescapeByteaInternal()

static unsigned char * PQescapeByteaInternal ( PGconn conn,
const unsigned char *  from,
size_t  from_length,
size_t *  to_length,
bool  std_strings,
bool  use_hex 
)
static

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

4419{
4420 const unsigned char *vp;
4421 unsigned char *rp;
4422 unsigned char *result;
4423 size_t i;
4424 size_t len;
4425 size_t bslash_len = (std_strings ? 1 : 2);
4426
4427 /*
4428 * empty string has 1 char ('\0')
4429 */
4430 len = 1;
4431
4432 if (use_hex)
4433 {
4434 len += bslash_len + 1 + 2 * from_length;
4435 }
4436 else
4437 {
4438 vp = from;
4439 for (i = from_length; i > 0; i--, vp++)
4440 {
4441 if (*vp < 0x20 || *vp > 0x7e)
4442 len += bslash_len + 3;
4443 else if (*vp == '\'')
4444 len += 2;
4445 else if (*vp == '\\')
4446 len += bslash_len + bslash_len;
4447 else
4448 len++;
4449 }
4450 }
4451
4452 *to_length = len;
4453 rp = result = (unsigned char *) malloc(len);
4454 if (rp == NULL)
4455 {
4456 if (conn)
4457 libpq_append_conn_error(conn, "out of memory");
4458 return NULL;
4459 }
4460
4461 if (use_hex)
4462 {
4463 if (!std_strings)
4464 *rp++ = '\\';
4465 *rp++ = '\\';
4466 *rp++ = 'x';
4467 }
4468
4469 vp = from;
4470 for (i = from_length; i > 0; i--, vp++)
4471 {
4472 unsigned char c = *vp;
4473
4474 if (use_hex)
4475 {
4476 *rp++ = hextbl[(c >> 4) & 0xF];
4477 *rp++ = hextbl[c & 0xF];
4478 }
4479 else if (c < 0x20 || c > 0x7e)
4480 {
4481 if (!std_strings)
4482 *rp++ = '\\';
4483 *rp++ = '\\';
4484 *rp++ = (c >> 6) + '0';
4485 *rp++ = ((c >> 3) & 07) + '0';
4486 *rp++ = (c & 07) + '0';
4487 }
4488 else if (c == '\'')
4489 {
4490 *rp++ = '\'';
4491 *rp++ = '\'';
4492 }
4493 else if (c == '\\')
4494 {
4495 if (!std_strings)
4496 {
4497 *rp++ = '\\';
4498 *rp++ = '\\';
4499 }
4500 *rp++ = '\\';
4501 *rp++ = '\\';
4502 }
4503 else
4504 *rp++ = c;
4505 }
4506 *rp = '\0';
4507
4508 return result;
4509}
static const char hextbl[]
Definition: fe-exec.c:4375
const void size_t len

References conn, hextbl, i, len, libpq_append_conn_error(), and malloc.

Referenced by PQescapeBytea(), and PQescapeByteaConn().

◆ PQescapeIdentifier()

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

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

4370{
4371 return PQescapeInternal(conn, str, len, true);
4372}
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:4213
const char * str

References conn, len, PQescapeInternal(), and str.

Referenced by create_publication(), create_subscription(), drop_publication(), enable_subscription(), escape_identifier(), initCreatePKeys(), initCreateTables(), main(), PQchangePassword(), psql_get_variable(), stringlist_to_identifierstr(), and vacuumlo().

◆ PQescapeInternal()

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

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

4214{
4215 const char *s;
4216 char *result;
4217 char *rp;
4218 int num_quotes = 0; /* single or double, depending on as_ident */
4219 int num_backslashes = 0;
4220 size_t input_len = strnlen(str, len);
4221 size_t result_size;
4222 char quote_char = as_ident ? '"' : '\'';
4223 bool validated_mb = false;
4224
4225 /* We must have a connection, else fail immediately. */
4226 if (!conn)
4227 return NULL;
4228
4229 if (conn->cmd_queue_head == NULL)
4231
4232 /*
4233 * Scan the string for characters that must be escaped and for invalidly
4234 * encoded data.
4235 */
4236 s = str;
4237 for (size_t remaining = input_len; remaining > 0; remaining--, s++)
4238 {
4239 if (*s == quote_char)
4240 ++num_quotes;
4241 else if (*s == '\\')
4242 ++num_backslashes;
4243 else if (IS_HIGHBIT_SET(*s))
4244 {
4245 int charlen;
4246
4247 /* Slow path for possible multibyte characters */
4248 charlen = pg_encoding_mblen(conn->client_encoding, s);
4249
4250 if (charlen > remaining)
4251 {
4252 /* Multibyte character overruns allowable length. */
4253 libpq_append_conn_error(conn, "incomplete multibyte character");
4254 return NULL;
4255 }
4256
4257 /*
4258 * If we haven't already, check that multibyte characters are
4259 * valid. It's important to verify that as invalid multi-byte
4260 * characters could e.g. be used to "skip" over quote characters,
4261 * e.g. when parsing character-by-character.
4262 *
4263 * We check validity once, for the whole remainder of the string,
4264 * when we first encounter any multi-byte character. Some
4265 * encodings have optimized implementations for longer strings.
4266 */
4267 if (!validated_mb)
4268 {
4270 != remaining)
4271 {
4272 libpq_append_conn_error(conn, "invalid multibyte character");
4273 return NULL;
4274 }
4275 validated_mb = true;
4276 }
4277
4278 /* Adjust s, bearing in mind that for loop will increment it. */
4279 s += charlen - 1;
4280 remaining -= charlen - 1;
4281 }
4282 }
4283
4284 /* Allocate output buffer. */
4285 result_size = input_len + num_quotes + 3; /* two quotes, plus a NUL */
4286 if (!as_ident && num_backslashes > 0)
4287 result_size += num_backslashes + 2;
4288 result = rp = (char *) malloc(result_size);
4289 if (rp == NULL)
4290 {
4291 libpq_append_conn_error(conn, "out of memory");
4292 return NULL;
4293 }
4294
4295 /*
4296 * If we are escaping a literal that contains backslashes, we use the
4297 * escape string syntax so that the result is correct under either value
4298 * of standard_conforming_strings. We also emit a leading space in this
4299 * case, to guard against the possibility that the result might be
4300 * interpolated immediately following an identifier.
4301 */
4302 if (!as_ident && num_backslashes > 0)
4303 {
4304 *rp++ = ' ';
4305 *rp++ = 'E';
4306 }
4307
4308 /* Opening quote. */
4309 *rp++ = quote_char;
4310
4311 /*
4312 * Use fast path if possible.
4313 *
4314 * We've already verified that the input string is well-formed in the
4315 * current encoding. If it contains no quotes and, in the case of
4316 * literal-escaping, no backslashes, then we can just copy it directly to
4317 * the output buffer, adding the necessary quotes.
4318 *
4319 * If not, we must rescan the input and process each character
4320 * individually.
4321 */
4322 if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
4323 {
4324 memcpy(rp, str, input_len);
4325 rp += input_len;
4326 }
4327 else
4328 {
4329 s = str;
4330 for (size_t remaining = input_len; remaining > 0; remaining--, s++)
4331 {
4332 if (*s == quote_char || (!as_ident && *s == '\\'))
4333 {
4334 *rp++ = *s;
4335 *rp++ = *s;
4336 }
4337 else if (!IS_HIGHBIT_SET(*s))
4338 *rp++ = *s;
4339 else
4340 {
4342
4343 while (1)
4344 {
4345 *rp++ = *s;
4346 if (--i == 0)
4347 break;
4348 remaining--;
4349 ++s; /* for loop will provide the final increment */
4350 }
4351 }
4352 }
4353 }
4354
4355 /* Closing quote and terminating NUL. */
4356 *rp++ = quote_char;
4357 *rp = '\0';
4358
4359 return result;
4360}
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1126
int remaining
Definition: informix.c:692
size_t strnlen(const char *str, size_t maxlen)
Definition: strnlen.c:26
int client_encoding
Definition: libpq-int.h:553
int pg_encoding_verifymbstr(int encoding, const char *mbstr, int len)
Definition: wchar.c:2163
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:2116

References pg_conn::client_encoding, pg_conn::cmd_queue_head, conn, i, IS_HIGHBIT_SET, len, libpq_append_conn_error(), malloc, pg_encoding_mblen(), pg_encoding_verifymbstr(), pqClearConnErrorState, remaining, str, and strnlen().

Referenced by PQescapeIdentifier(), and PQescapeLiteral().

◆ PQescapeLiteral()

◆ PQescapeString()

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

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

4199{
4200 return PQescapeStringInternal(NULL, to, from, length, NULL,
4203}
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:4071
static int static_client_encoding
Definition: fe-exec.c:59

References PQescapeStringInternal(), static_client_encoding, and static_std_strings.

Referenced by escape_string(), get_comma_elts(), and quote_postgres().

◆ PQescapeStringConn()

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

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

4179{
4180 if (!conn)
4181 {
4182 /* force empty-string result */
4183 *to = '\0';
4184 if (error)
4185 *error = 1;
4186 return 0;
4187 }
4188
4189 if (conn->cmd_queue_head == NULL)
4191
4192 return PQescapeStringInternal(conn, to, from, length, error,
4194 conn->std_strings);
4195}
static void error(void)
Definition: sql-dyntest.c:147

References pg_conn::client_encoding, pg_conn::cmd_queue_head, conn, error(), pqClearConnErrorState, PQescapeStringInternal(), and pg_conn::std_strings.

Referenced by AppendStringCommandOption(), appendStringLiteralConn(), check_loadable_libraries(), do_lo_import(), and escape_string_conn().

◆ PQescapeStringInternal()

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

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

4075{
4076 const char *source = from;
4077 char *target = to;
4078 size_t remaining = strnlen(from, length);
4079 bool already_complained = false;
4080
4081 if (error)
4082 *error = 0;
4083
4084 while (remaining > 0)
4085 {
4086 char c = *source;
4087 int charlen;
4088 int i;
4089
4090 /* Fast path for plain ASCII */
4091 if (!IS_HIGHBIT_SET(c))
4092 {
4093 /* Apply quoting if needed */
4094 if (SQL_STR_DOUBLE(c, !std_strings))
4095 *target++ = c;
4096 /* Copy the character */
4097 *target++ = c;
4098 source++;
4099 remaining--;
4100 continue;
4101 }
4102
4103 /* Slow path for possible multibyte characters */
4104 charlen = pg_encoding_mblen(encoding, source);
4105
4106 if (remaining < charlen ||
4107 pg_encoding_verifymbchar(encoding, source, charlen) == -1)
4108 {
4109 /*
4110 * Multibyte character is invalid. It's important to verify that
4111 * as invalid multibyte characters could e.g. be used to "skip"
4112 * over quote characters, e.g. when parsing
4113 * character-by-character.
4114 *
4115 * Report an error if possible, and replace the character's first
4116 * byte with an invalid sequence. The invalid sequence ensures
4117 * that the escaped string will trigger an error on the
4118 * server-side, even if we can't directly report an error here.
4119 *
4120 * This isn't *that* crucial when we can report an error to the
4121 * caller; but if we can't or the caller ignores it, the caller
4122 * will use this string unmodified and it needs to be safe for
4123 * parsing.
4124 *
4125 * We know there's enough space for the invalid sequence because
4126 * the "to" buffer needs to be at least 2 * length + 1 long, and
4127 * at worst we're replacing a single input byte with two invalid
4128 * bytes.
4129 *
4130 * It would be a bit faster to verify the whole string the first
4131 * time we encounter a set highbit, but this way we can replace
4132 * just the invalid data, which probably makes it easier for users
4133 * to find the invalidly encoded portion of a larger string.
4134 */
4135 if (error)
4136 *error = 1;
4137 if (conn && !already_complained)
4138 {
4139 if (remaining < charlen)
4140 libpq_append_conn_error(conn, "incomplete multibyte character");
4141 else
4142 libpq_append_conn_error(conn, "invalid multibyte character");
4143 /* Issue a complaint only once per string */
4144 already_complained = true;
4145 }
4146
4148 target += 2;
4149
4150 /*
4151 * Handle the following bytes as if this byte didn't exist. That's
4152 * safer in case the subsequent bytes contain important characters
4153 * for the caller (e.g. '>' in html).
4154 */
4155 source++;
4156 remaining--;
4157 }
4158 else
4159 {
4160 /* Copy the character */
4161 for (i = 0; i < charlen; i++)
4162 {
4163 *target++ = *source++;
4164 remaining--;
4165 }
4166 }
4167 }
4168
4169 /* Write the terminating NUL character. */
4170 *target = '\0';
4171
4172 return target - to;
4173}
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:1134
int32 encoding
Definition: pg_database.h:41
static rewind_source * source
Definition: pg_rewind.c:89
void pg_encoding_set_invalid(int encoding, char *dst)
Definition: wchar.c:2049
int pg_encoding_verifymbchar(int encoding, const char *mbstr, int len)
Definition: wchar.c:2150

References conn, encoding, error(), i, IS_HIGHBIT_SET, libpq_append_conn_error(), pg_encoding_mblen(), pg_encoding_set_invalid(), pg_encoding_verifymbchar(), remaining, source, SQL_STR_DOUBLE, and strnlen().

Referenced by PQescapeString(), and PQescapeStringConn().

◆ PQexec()

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

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

2263{
2264 if (!PQexecStart(conn))
2265 return NULL;
2266 if (!PQsendQuery(conn, query))
2267 return NULL;
2268 return PQexecFinish(conn);
2269}
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1416

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

Referenced by _doSetSessionAuth(), _printTableAccessMethodNoStorage(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), check_and_drop_existing_subscriptions(), check_loadable_libraries(), check_prepare_conn(), check_publisher(), check_subscriber(), connect_database(), create_logical_replication_slot(), create_publication(), create_subscription(), CreateReplicationSlot(), deallocate_one(), DescribeQuery(), drop_existing_subscriptions(), drop_failover_replication_slots(), drop_publication(), drop_replication_slot(), DropReplicationSlot(), ecpg_autostart_transaction(), ecpg_execute(), ecpg_is_type_an_array(), ECPGsetcommit(), ECPGtrans(), enable_subscription(), executeCommand(), executeMaintenanceCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlQuery(), ExecuteSqlStatement(), executeStatement(), generate_object_name(), get_create_object_cmd(), get_primary_sysid(), GetConnection(), GetSlotInformation(), GetTableInfo(), init_libpq_conn(), initPopulateTable(), libpq_traverse_files(), lo_initialize(), lockTableForWorker(), lookup_object_oid(), main(), PQchangePassword(), PQencryptPasswordConn(), PQsetClientEncoding(), PSQLexec(), ReceiveXlogStream(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_permutation(), run_simple_command(), run_simple_query(), RunIdentifySystem(), SendQuery(), server_is_in_recovery(), set_replication_progress(), setup_publisher(), sql_conn(), sql_exec(), StreamLogicalLog(), test_disallowed_in_pipeline(), test_pipeline_abort(), test_prepared(), test_transaction(), test_uniqviol(), tryExecuteStatement(), and vacuumlo().

◆ PQexecFinish()

static PGresult * PQexecFinish ( PGconn conn)
static

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

2411{
2412 PGresult *result;
2413 PGresult *lastResult;
2414
2415 /*
2416 * For backwards compatibility, return the last result if there are more
2417 * than one. (We used to have logic here to concatenate successive error
2418 * messages, but now that happens automatically, since conn->errorMessage
2419 * will continue to accumulate errors throughout this loop.)
2420 *
2421 * We have to stop if we see copy in/out/both, however. We will resume
2422 * parsing after application performs the data transfer.
2423 *
2424 * Also stop if the connection is lost (else we'll loop infinitely).
2425 */
2426 lastResult = NULL;
2427 while ((result = PQgetResult(conn)) != NULL)
2428 {
2429 PQclear(lastResult);
2430 lastResult = result;
2431 if (result->resultStatus == PGRES_COPY_IN ||
2432 result->resultStatus == PGRES_COPY_OUT ||
2433 result->resultStatus == PGRES_COPY_BOTH ||
2435 break;
2436 }
2437
2438 return lastResult;
2439}
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2062
@ CONNECTION_BAD
Definition: libpq-fe.h:84
@ PGRES_COPY_IN
Definition: libpq-fe.h:131
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:136
@ PGRES_COPY_OUT
Definition: libpq-fe.h:130

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

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

◆ PQexecParams()

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

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

2284{
2285 if (!PQexecStart(conn))
2286 return NULL;
2287 if (!PQsendQueryParams(conn, command,
2288 nParams, paramTypes, paramValues, paramLengths,
2289 paramFormats, resultFormat))
2290 return NULL;
2291 return PQexecFinish(conn);
2292}
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:1492

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

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

◆ PQexecPrepared()

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

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

2330{
2331 if (!PQexecStart(conn))
2332 return NULL;
2333 if (!PQsendQueryPrepared(conn, stmtName,
2334 nParams, paramValues, paramLengths,
2335 paramFormats, resultFormat))
2336 return NULL;
2337 return PQexecFinish(conn);
2338}
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:1633

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

Referenced by ecpg_execute(), and try_complete_step().

◆ PQexecStart()

static bool PQexecStart ( PGconn conn)
static

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

2345{
2346 PGresult *result;
2347
2348 if (!conn)
2349 return false;
2350
2351 /*
2352 * Since this is the beginning of a query cycle, reset the error state.
2353 * However, in pipeline mode with something already queued, the error
2354 * buffer belongs to that command and we shouldn't clear it.
2355 */
2356 if (conn->cmd_queue_head == NULL)
2358
2360 {
2361 libpq_append_conn_error(conn, "synchronous command execution functions are not allowed in pipeline mode");
2362 return false;
2363 }
2364
2365 /*
2366 * Silently discard any prior query result that application didn't eat.
2367 * This is probably poor design, but it's here for backward compatibility.
2368 */
2369 while ((result = PQgetResult(conn)) != NULL)
2370 {
2371 ExecStatusType resultStatus = result->resultStatus;
2372
2373 PQclear(result); /* only need its status */
2374 if (resultStatus == PGRES_COPY_IN)
2375 {
2376 /* get out of a COPY IN state */
2377 if (PQputCopyEnd(conn,
2378 libpq_gettext("COPY terminated by new PQexec")) < 0)
2379 return false;
2380 /* keep waiting to swallow the copy's failure message */
2381 }
2382 else if (resultStatus == PGRES_COPY_OUT)
2383 {
2384 /*
2385 * Get out of a COPY OUT state: we just switch back to BUSY and
2386 * allow the remaining COPY data to be dropped on the floor.
2387 */
2389 /* keep waiting to swallow the copy's completion message */
2390 }
2391 else if (resultStatus == PGRES_COPY_BOTH)
2392 {
2393 /* We don't allow PQexec during COPY BOTH */
2394 libpq_append_conn_error(conn, "PQexec not allowed during COPY BOTH");
2395 return false;
2396 }
2397 /* check for loss of connection, too */
2398 if (conn->status == CONNECTION_BAD)
2399 return false;
2400 }
2401
2402 /* OK to send a command */
2403 return true;
2404}
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2749
ExecStatusType
Definition: libpq-fe.h:122

References pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, CONNECTION_BAD, libpq_append_conn_error(), libpq_gettext, PGASYNC_BUSY, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, PQclear(), pqClearConnErrorState, PQgetResult(), PQputCopyEnd(), pg_result::resultStatus, and pg_conn::status.

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

◆ PQexitPipelineMode()

int PQexitPipelineMode ( PGconn conn)

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

3074{
3075 if (!conn)
3076 return 0;
3077
3081 conn->cmd_queue_head == NULL)
3082 return 1;
3083
3084 switch (conn->asyncStatus)
3085 {
3086 case PGASYNC_READY:
3087 case PGASYNC_READY_MORE:
3088 /* there are some uncollected results */
3089 libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
3090 return 0;
3091
3092 case PGASYNC_BUSY:
3093 libpq_append_conn_error(conn, "cannot exit pipeline mode while busy");
3094 return 0;
3095
3096 case PGASYNC_IDLE:
3098 /* OK */
3099 break;
3100
3101 case PGASYNC_COPY_IN:
3102 case PGASYNC_COPY_OUT:
3103 case PGASYNC_COPY_BOTH:
3104 libpq_append_conn_error(conn, "cannot exit pipeline mode while in COPY");
3105 }
3106
3107 /* still work to process */
3108 if (conn->cmd_queue_head != NULL)
3109 {
3110 libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
3111 return 0;
3112 }
3113
3116
3117 /* Flush any pending data in out buffer */
3118 if (pqFlush(conn) < 0)
3119 return 0; /* error message is setup already */
3120 return 1;
3121}
@ PGASYNC_COPY_OUT
Definition: libpq-int.h:231
@ PGASYNC_READY_MORE
Definition: libpq-int.h:227
@ PGASYNC_READY
Definition: libpq-int.h:225
@ PGASYNC_COPY_BOTH
Definition: libpq-int.h:232
@ PGASYNC_COPY_IN
Definition: libpq-int.h:230

References pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, libpq_append_conn_error(), PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_PIPELINE_IDLE, PGASYNC_READY, PGASYNC_READY_MORE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, and pqFlush().

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

◆ PQfformat()

int PQfformat ( const PGresult res,
int  field_num 
)

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

3709{
3710 if (!check_field_number(res, field_num))
3711 return 0;
3712 if (res->attDescs)
3713 return res->attDescs[field_num].format;
3714 else
3715 return 0;
3716}
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3510

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

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

◆ PQflush()

◆ PQfmod()

int PQfmod ( const PGresult res,
int  field_num 
)

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

3742{
3743 if (!check_field_number(res, field_num))
3744 return 0;
3745 if (res->attDescs)
3746 return res->attDescs[field_num].atttypmod;
3747 else
3748 return 0;
3749}
int atttypmod
Definition: libpq-fe.h:312

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

Referenced by DescribeQuery(), and ECPGget_desc().

◆ PQfn()

PGresult * PQfn ( PGconn conn,
int  fnid,
int *  result_buf,
int *  result_len,
int  result_is_int,
const PQArgBlock args,
int  nargs 
)

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

2987{
2988 *result_len = 0;
2989
2990 if (!conn)
2991 return NULL;
2992
2993 /*
2994 * Since this is the beginning of a query cycle, reset the error state.
2995 * However, in pipeline mode with something already queued, the error
2996 * buffer belongs to that command and we shouldn't clear it.
2997 */
2998 if (conn->cmd_queue_head == NULL)
3000
3002 {
3003 libpq_append_conn_error(conn, "%s not allowed in pipeline mode", "PQfn");
3004 return NULL;
3005 }
3006
3009 {
3010 libpq_append_conn_error(conn, "connection in wrong state");
3011 return NULL;
3012 }
3013
3014 return pqFunctionCall3(conn, fnid,
3015 result_buf, result_len,
3016 result_is_int,
3017 args, nargs);
3018}
PGresult * pqFunctionCall3(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
#define PGINVALID_SOCKET
Definition: port.h:31
pgsocket sock
Definition: libpq-int.h:501

References generate_unaccent_rules::args, pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, libpq_append_conn_error(), PGASYNC_IDLE, pgHavePendingResult, PGINVALID_SOCKET, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqClearConnErrorState, pqFunctionCall3(), 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().

◆ PQfname()

char * PQfname ( const PGresult res,
int  field_num 
)

◆ PQfnumber()

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

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

3590{
3591 char *field_case;
3592 bool in_quotes;
3593 bool all_lower = true;
3594 const char *iptr;
3595 char *optr;
3596 int i;
3597
3598 if (!res)
3599 return -1;
3600
3601 /*
3602 * Note: it is correct to reject a zero-length input string; the proper
3603 * input to match a zero-length field name would be "".
3604 */
3605 if (field_name == NULL ||
3606 field_name[0] == '\0' ||
3607 res->attDescs == NULL)
3608 return -1;
3609
3610 /*
3611 * Check if we can avoid the strdup() and related work because the
3612 * passed-in string wouldn't be changed before we do the check anyway.
3613 */
3614 for (iptr = field_name; *iptr; iptr++)
3615 {
3616 char c = *iptr;
3617
3618 if (c == '"' || c != pg_tolower((unsigned char) c))
3619 {
3620 all_lower = false;
3621 break;
3622 }
3623 }
3624
3625 if (all_lower)
3626 for (i = 0; i < res->numAttributes; i++)
3627 if (strcmp(field_name, res->attDescs[i].name) == 0)
3628 return i;
3629
3630 /* Fall through to the normal check if that didn't work out. */
3631
3632 /*
3633 * Note: this code will not reject partially quoted strings, eg
3634 * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
3635 * condition.
3636 */
3637 field_case = strdup(field_name);
3638 if (field_case == NULL)
3639 return -1; /* grotty */
3640
3641 in_quotes = false;
3642 optr = field_case;
3643 for (iptr = field_case; *iptr; iptr++)
3644 {
3645 char c = *iptr;
3646
3647 if (in_quotes)
3648 {
3649 if (c == '"')
3650 {
3651 if (iptr[1] == '"')
3652 {
3653 /* doubled quotes become a single quote */
3654 *optr++ = '"';
3655 iptr++;
3656 }
3657 else
3658 in_quotes = false;
3659 }
3660 else
3661 *optr++ = c;
3662 }
3663 else if (c == '"')
3664 in_quotes = true;
3665 else
3666 {
3667 c = pg_tolower((unsigned char) c);
3668 *optr++ = c;
3669 }
3670 }
3671 *optr = '\0';
3672
3673 for (i = 0; i < res->numAttributes; i++)
3674 {
3675 if (strcmp(field_case, res->attDescs[i].name) == 0)
3676 {
3677 free(field_case);
3678 return i;
3679 }
3680 }
3681 free(field_case);
3682 return -1;
3683}
unsigned char pg_tolower(unsigned char ch)
Definition: pgstrcasecmp.c:122

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

Referenced by append_depends_on_extension(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), check_for_connection_status(), check_for_pg_role_prefix(), collectComments(), collectSecLabels(), describeOneTableDetails(), dropRoles(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpDatabase(), dumpDomain(), dumpEnumType(), dumpFunc(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRelationStats(), dumpRoleMembership(), dumpRoles(), dumpTableSchema(), dumpTSConfig(), dumpUserMappings(), get_db_infos(), get_tablespace_paths(), get_template0_info(), getAccessMethods(), getAggregates(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getIndexes(), getInherits(), getLOs(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPolicies(), getProcLangs(), getPublicationNamespaces(), getPublications(), getPublicationTables(), getRules(), getSubscriptions(), getSubscriptionTables(), getTableAttrs(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), old_9_6_invalidate_hash_indexes(), process_data_type_check(), process_extension_updates(), process_incompat_polymorphics(), process_isn_and_int8_passing_mismatch(), process_old_cluster_logical_slot_infos(), process_old_sub_state_check(), process_rel_infos(), process_user_defined_encoding_conversions(), process_user_defined_postfix_ops(), process_with_oids_check(), processExtensionTables(), set_frozenxids(), and show_binary_results().

◆ PQfreemem()

◆ PQfreeNotify()

void PQfreeNotify ( PGnotify notify)

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

4050{
4051 PQfreemem(notify);
4052}
void PQfreemem(void *ptr)
Definition: fe-exec.c:4032

References PQfreemem().

◆ PQfsize()

int PQfsize ( const PGresult res,
int  field_num 
)

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

3731{
3732 if (!check_field_number(res, field_num))
3733 return 0;
3734 if (res->attDescs)
3735 return res->attDescs[field_num].typlen;
3736 else
3737 return 0;
3738}

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

Referenced by ecpg_build_compat_sqlda(), and ECPGget_desc().

◆ PQftable()

Oid PQftable ( const PGresult res,
int  field_num 
)

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

3687{
3688 if (!check_field_number(res, field_num))
3689 return InvalidOid;
3690 if (res->attDescs)
3691 return res->attDescs[field_num].tableid;
3692 else
3693 return InvalidOid;
3694}
#define InvalidOid
Definition: postgres_ext.h:37

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

◆ PQftablecol()

int PQftablecol ( const PGresult res,
int  field_num 
)

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

3698{
3699 if (!check_field_number(res, field_num))
3700 return 0;
3701 if (res->attDescs)
3702 return res->attDescs[field_num].columnid;
3703 else
3704 return 0;
3705}
int columnid
Definition: libpq-fe.h:308

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

◆ PQftype()

Oid PQftype ( const PGresult res,
int  field_num 
)

◆ PQgetCopyData()

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

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

2817{
2818 *buffer = NULL; /* for all failure cases */
2819 if (!conn)
2820 return -2;
2823 {
2824 libpq_append_conn_error(conn, "no COPY in progress");
2825 return -2;
2826 }
2827 return pqGetCopyData3(conn, buffer, async);
2828}
int pqGetCopyData3(PGconn *conn, char **buffer, int async)

References pg_conn::asyncStatus, conn, libpq_append_conn_error(), PGASYNC_COPY_BOTH, PGASYNC_COPY_OUT, and pqGetCopyData3().

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

◆ PQgetisnull()

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

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

3902{
3903 if (!check_tuple_field_number(res, tup_num, field_num))
3904 return 1; /* pretend it is null */
3905 if (res->tuples[tup_num][field_num].len == NULL_LEN)
3906 return 1;
3907 else
3908 return 0;
3909}
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3525
#define NULL_LEN
Definition: libpq-int.h:138

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

Referenced by addFooterToPublicationDesc(), BaseBackup(), compile_database_list(), compile_relation_list_one_db(), describeOneTableDetails(), determineNotNullFlags(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpDatabase(), dumpDomain(), dumpFunc(), dumpRangeType(), dumpRelationStats(), dumpRoleMembership(), dumpRoles(), dumpTableData_insert(), ecpg_get_data(), ecpg_set_compat_sqlda(), ecpg_set_native_sqlda(), ECPGget_desc(), ExecQueryTuples(), get_template0_info(), getAggregates(), getExtendedStatistics(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getIndexes(), getLOs(), getNamespaces(), getPolicies(), getProcLangs(), getPublicationTables(), GetSlotInformation(), getSubscriptions(), getSubscriptionTables(), getTableAttrs(), GetTableInfo(), getTables(), getTSDictionaries(), getTypes(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_create_slot(), libpqrcv_processTuples(), listTSConfigsVerbose(), listTSParsersVerbose(), make_tuple_from_result_row(), materializeResult(), postgresImportForeignSchema(), printCrosstab(), printQuery(), PrintResultInCrosstab(), process_queued_fetch_requests(), retrieve_objects(), run_simple_query(), RunIdentifySystem(), sqlda_common_total_size(), StoreQueryTuple(), storeRow(), and verify_heap_slot_handler().

◆ PQgetlength()

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

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

3888{
3889 if (!check_tuple_field_number(res, tup_num, field_num))
3890 return 0;
3891 if (res->tuples[tup_num][field_num].len != NULL_LEN)
3892 return res->tuples[tup_num][field_num].len;
3893 else
3894 return 0;
3895}

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

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

◆ PQgetline()

int PQgetline ( PGconn conn,
char *  buffer,
int  length 
)

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

2855{
2856 if (!buffer || length <= 0)
2857 return EOF;
2858 *buffer = '\0';
2859 /* length must be at least 3 to hold the \. terminator! */
2860 if (length < 3)
2861 return EOF;
2862
2863 if (!conn)
2864 return EOF;
2865
2866 return pqGetline3(conn, buffer, length);
2867}
int pqGetline3(PGconn *conn, char *s, int maxlen)

References conn, and pqGetline3().

◆ PQgetlineAsync()

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

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

2902{
2903 if (!conn)
2904 return -1;
2905
2906 return pqGetlineAsync3(conn, buffer, bufsize);
2907}
int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)
#define bufsize
Definition: indent_globs.h:36

References bufsize, conn, and pqGetlineAsync3().

Referenced by pqGetline3().

◆ PQgetResult()

PGresult * PQgetResult ( PGconn conn)

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

2063{
2064 PGresult *res;
2065
2066 if (!conn)
2067 return NULL;
2068
2069 /* Parse any available data, if our state permits. */
2071
2072 /* If not ready to return something, block until we are. */
2073 while (conn->asyncStatus == PGASYNC_BUSY)
2074 {
2075 int flushResult;
2076
2077 /*
2078 * If data remains unsent, send it. Else we might be waiting for the
2079 * result of a command the backend hasn't even got yet.
2080 */
2081 while ((flushResult = pqFlush(conn)) > 0)
2082 {
2083 if (pqWait(false, true, conn))
2084 {
2085 flushResult = -1;
2086 break;
2087 }
2088 }
2089
2090 /*
2091 * Wait for some more data, and load it. (Note: if the connection has
2092 * been lost, pqWait should return immediately because the socket
2093 * should be read-ready, either with the last server data or with an
2094 * EOF indication. We expect therefore that this won't result in any
2095 * undue delay in reporting a previous write failure.)
2096 */
2097 if (flushResult ||
2098 pqWait(true, false, conn) ||
2099 pqReadData(conn) < 0)
2100 {
2101 /* Report the error saved by pqWait or pqReadData */
2104 return pqPrepareAsyncResult(conn);
2105 }
2106
2107 /* Parse it. */
2109
2110 /*
2111 * If we had a write error, but nothing above obtained a query result
2112 * or detected a read error, report the write error.
2113 */
2115 {
2118 return pqPrepareAsyncResult(conn);
2119 }
2120 }
2121
2122 /* Return the appropriate thing. */
2123 switch (conn->asyncStatus)
2124 {
2125 case PGASYNC_IDLE:
2126 res = NULL; /* query is complete */
2127 break;
2130
2131 /*
2132 * We're about to return the NULL that terminates the round of
2133 * results from the current query; prepare to send the results of
2134 * the next query, if any, when we're called next. If there's no
2135 * next element in the command queue, this gets us in IDLE state.
2136 */
2138 res = NULL; /* query is complete */
2139 break;
2140
2141 case PGASYNC_READY:
2143
2144 /*
2145 * Normally pqPrepareAsyncResult will have left conn->result
2146 * empty. Otherwise, "res" must be a not-full PGRES_TUPLES_CHUNK
2147 * result, which we want to return to the caller while staying in
2148 * PGASYNC_READY state. Then the next call here will return the
2149 * empty PGRES_TUPLES_OK result that was restored from
2150 * saved_result, after which we can proceed.
2151 */
2152 if (conn->result)
2153 {
2155 break;
2156 }
2157
2158 /* Advance the queue as appropriate */
2161
2163 {
2164 /*
2165 * We're about to send the results of the current query. Set
2166 * us idle now, and ...
2167 */
2169
2170 /*
2171 * ... in cases when we're sending a pipeline-sync result,
2172 * move queue processing forwards immediately, so that next
2173 * time we're called, we're prepared to return the next result
2174 * received from the server. In all other cases, leave the
2175 * queue state change for next time, so that a terminating
2176 * NULL result is sent.
2177 *
2178 * (In other words: we don't return a NULL after a pipeline
2179 * sync.)
2180 */
2183 }
2184 else
2185 {
2186 /* Set the state back to BUSY, allowing parsing to proceed. */
2188 }
2189 break;
2190 case PGASYNC_READY_MORE:
2192 /* Set the state back to BUSY, allowing parsing to proceed. */
2194 break;
2195 case PGASYNC_COPY_IN:
2197 break;
2198 case PGASYNC_COPY_OUT:
2200 break;
2201 case PGASYNC_COPY_BOTH:
2203 break;
2204 default:
2205 libpq_append_conn_error(conn, "unexpected asyncStatus: %d", (int) conn->asyncStatus);
2207 conn->asyncStatus = PGASYNC_IDLE; /* try to restore valid state */
2209 break;
2210 }
2211
2212 /* Time to fire PGEVT_RESULTCREATE events, if there are any */
2213 if (res && res->nEvents > 0)
2214 (void) PQfireResultCreateEvents(conn, res);
2215
2216 return res;
2217}
static void pqSaveWriteError(PGconn *conn)
Definition: fe-exec.c:820
void pqCommandQueueAdvance(PGconn *conn, bool isReadyForQuery, bool gotSync)
Definition: fe-exec.c:3142
static PGresult * getCopyResult(PGconn *conn, ExecStatusType copytype)
Definition: fe-exec.c:2224
static void parseInput(PGconn *conn)
Definition: fe-exec.c:2020
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:993
int PQfireResultCreateEvents(PGconn *conn, PGresult *res)
Definition: libpq-events.c:185
@ PGRES_TUPLES_CHUNK
Definition: libpq-fe.h:141
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:138
bool write_failed
Definition: libpq-int.h:512

References Assert(), pg_conn::asyncStatus, conn, getCopyResult(), libpq_append_conn_error(), pg_result::nEvents, parseInput(), PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_PIPELINE_IDLE, PGASYNC_READY, PGASYNC_READY_MORE, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_PIPELINE_SYNC, PGRES_TUPLES_CHUNK, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqCommandQueueAdvance(), PQfireResultCreateEvents(), pqFlush(), pqPipelineProcessQueue(), pqPrepareAsyncResult(), pqReadData(), pqSaveErrorResult(), pqSaveWriteError(), pqWait(), pg_conn::result, pg_result::resultStatus, and pg_conn::write_failed.

Referenced by advanceConnectionState(), BaseBackup(), ClearOrSaveAllResults(), confirm_query_canceled_impl(), consumeQueryResult(), discardAbortedPipelineResults(), discardUntilSync(), dumpTableData_copy(), ecpg_process_output(), EndDBCopyMode(), ExecQueryAndProcessResults(), handleCopyIn(), handleCopyOut(), HandleEndOfCopyStream(), libpqrcv_PQgetResult(), libpqsrv_get_result(), pgfdw_finish_pre_commit_cleanup(), pgfdw_get_cleanup_result(), PQconnectPoll(), pqEndcopy3(), PQexecFinish(), PQexecStart(), process_query_result(), process_queued_fetch_requests(), process_result(), readCommandResponse(), ReceiveCopyData(), ReceiveXlogStream(), StreamLogicalLog(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), test_uniqviol(), try_complete_step(), and wait_on_slots().

◆ PQgetvalue()

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

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

3877{
3878 if (!check_tuple_field_number(res, tup_num, field_num))
3879 return NULL;
3880 return res->tuples[tup_num][field_num].value;
3881}

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

Referenced by _check_database_version(), add_tablespace_footer(), addFooterToPublicationDesc(), append_depends_on_extension(), appendQualifiedRelation(), BaseBackup(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), check_and_drop_existing_subscriptions(), check_for_connection_status(), check_for_pg_role_prefix(), check_is_install_user(), check_new_cluster_logical_replication_slots(), check_new_cluster_subscription_configuration(), check_old_cluster_subscription_state(), check_publisher(), check_subscriber(), cluster_all_databases(), collectBinaryUpgradeClassOids(), collectComments(), collectRoleNames(), collectSecLabels(), collectSequences(), compile_database_list(), compile_relation_list_one_db(), convertTSFunction(), create_logical_replication_slot(), createViewAsClause(), describeOneTableDetails(), describePublications(), describeRoles(), describeTableDetails(), determineNotNullFlags(), do_field(), drop_failover_replication_slots(), dropDBs(), dropRoles(), dropTablespaces(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpDomain(), dumpEnumType(), dumpForeignServer(), dumpFunc(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRelationStats(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSearchPath(), dumpSequence(), dumpSequenceData(), dumpStatisticsExt(), dumpTable(), dumpTableAttach(), 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(), exec_command_password(), ExecQueryTuples(), expand_dbname_patterns(), expand_extension_name_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), generate_object_name(), get_create_object_cmd(), get_db_infos(), get_language_name(), get_loadable_libraries(), get_next_possible_free_pg_type_oid(), get_parallel_tabidx_list(), get_parallel_tables_list(), get_primary_sysid(), get_remote_estimate(), get_subscription_count(), get_synchronized_snapshot(), get_table_relkind(), get_tablespace_paths(), get_template0_info(), getAccessMethods(), getAdditionalACLs(), getAggregates(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getLOs(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPartitioningInfo(), getPolicies(), getProcLangs(), getPublicationNamespaces(), getPublications(), getPublicationTables(), getRules(), GetSlotInformation(), getSubscriptions(), getSubscriptionTables(), getTableAttrs(), GetTableInfo(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_identify_system(), libpqrcv_processTuples(), libpqrcv_readtimelinehistoryfile(), listExtensionContents(), listSchemas(), listTSConfigsVerbose(), listTSParsersVerbose(), lo_initialize(), lookup_object_oid(), main(), make_tuple_from_result_row(), materializeResult(), old_9_6_invalidate_hash_indexes(), postgresAnalyzeForeignTable(), postgresGetAnalyzeInfoForForeignTable(), postgresImportForeignSchema(), PQconnectPoll(), PQdisplayTuples(), PQencryptPasswordConn(), PQprintTuples(), printCrosstab(), printQuery(), PrintResultInCrosstab(), process_data_type_check(), process_extension_updates(), process_incompat_polymorphics(), process_isn_and_int8_passing_mismatch(), process_old_cluster_logical_slot_infos(), process_old_sub_state_check(), process_queued_fetch_requests(), process_rel_infos(), process_result(), process_user_defined_encoding_conversions(), process_user_defined_postfix_ops(), process_with_oids_check(), processExtensionTables(), readCommandResponse(), ReadEndOfStreamingResult(), ReceiveXlogStream(), reindex_all_databases(), retrieve_objects(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_simple_query(), RunIdentifySystem(), server_is_in_recovery(), set_frozenxids(), set_replication_progress(), show_binary_results(), sql_exec(), sqlda_common_total_size(), StoreQueryTuple(), storeRow(), test_pipeline_abort(), test_singlerowmode(), test_transaction(), try_complete_step(), vacuum_all_databases(), vacuumlo(), verify_heap_slot_handler(), and wait_for_connection_state().

◆ pqInternalNotice()

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

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

939{
940 char msgBuf[1024];
941 va_list args;
942 PGresult *res;
943
944 if (hooks->noticeRec == NULL)
945 return; /* nobody home to receive notice? */
946
947 /* Format the message */
948 va_start(args, fmt);
949 vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
950 va_end(args);
951 msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
952
953 /* Make a PGresult to pass to the notice receiver */
955 if (!res)
956 return;
957 res->noticeHooks = *hooks;
958
959 /*
960 * Set up fields of notice.
961 */
965 /* XXX should provide a SQLSTATE too? */
966
967 /*
968 * Result text is always just the primary message + newline. If we can't
969 * allocate it, substitute "out of memory", as in pqSetResultError.
970 */
971 res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, false);
972 if (res->errMsg)
973 sprintf(res->errMsg, "%s\n", msgBuf);
974 else
975 res->errMsg = libpq_gettext("out of memory\n");
976
977 /*
978 * Pass to receiver, then free it.
979 */
980 res->noticeHooks.noticeRec(res->noticeHooks.noticeRecArg, res);
981 PQclear(res);
982}
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:563
void pqSaveMessageField(PGresult *res, char code, const char *value)
Definition: fe-exec.c:1060
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:134
#define vsnprintf
Definition: port.h:238
#define sprintf
Definition: port.h:241
#define PG_DIAG_SEVERITY_NONLOCALIZED
Definition: postgres_ext.h:56
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:58
#define PG_DIAG_SEVERITY
Definition: postgres_ext.h:55
PQnoticeReceiver noticeRec
Definition: libpq-int.h:157

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

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

◆ PQisBusy()

int PQisBusy ( PGconn conn)

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

2032{
2033 if (!conn)
2034 return false;
2035
2036 /* Parse any available data, if our state permits. */
2038
2039 /*
2040 * PQgetResult will return immediately in all states except BUSY. Also,
2041 * if we've detected read EOF and dropped the connection, we can expect
2042 * that PQgetResult will fail immediately. Note that we do *not* check
2043 * conn->write_failed here --- once that's become set, we know we have
2044 * trouble, but we need to keep trying to read until we have a complete
2045 * server message or detect read EOF.
2046 */
2048}

References pg_conn::asyncStatus, conn, CONNECTION_BAD, parseInput(), PGASYNC_BUSY, and pg_conn::status.

Referenced by advanceConnectionState(), confirm_query_canceled_impl(), dblink_is_busy(), libpqrcv_PQgetResult(), libpqsrv_get_result(), pgfdw_get_cleanup_result(), PQconnectPoll(), pqEndcopy3(), process_slot(), test_disallowed_in_pipeline(), test_pipelined_insert(), test_uniqviol(), try_complete_step(), and wait_on_slots().

◆ PQisnonblocking()

int PQisnonblocking ( const PGconn conn)

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

3984{
3985 if (!conn || conn->status == CONNECTION_BAD)
3986 return false;
3987 return pqIsnonblocking(conn);
3988}

References conn, CONNECTION_BAD, pqIsnonblocking, and pg_conn::status.

Referenced by test_disallowed_in_pipeline(), and test_simple_pipeline().

◆ PQisthreadsafe()

int PQisthreadsafe ( void  )

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

3993{
3994 return true;
3995}

◆ PQmakeEmptyPGresult()

PGresult * PQmakeEmptyPGresult ( PGconn conn,
ExecStatusType  status 
)

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

160{
161 PGresult *result;
162
163 result = (PGresult *) malloc(sizeof(PGresult));
164 if (!result)
165 return NULL;
166
167 result->ntups = 0;
168 result->numAttributes = 0;
169 result->attDescs = NULL;
170 result->tuples = NULL;
171 result->tupArrSize = 0;
172 result->numParameters = 0;
173 result->paramDescs = NULL;
174 result->resultStatus = status;
175 result->cmdStatus[0] = '\0';
176 result->binary = 0;
177 result->events = NULL;
178 result->nEvents = 0;
179 result->errMsg = NULL;
180 result->errFields = NULL;
181 result->errQuery = NULL;
182 result->null_field[0] = '\0';
183 result->curBlock = NULL;
184 result->curOffset = 0;
185 result->spaceLeft = 0;
186 result->memorySize = sizeof(PGresult);
187
188 if (conn)
189 {
190 /* copy connection data we might need for operations on PGresult */
191 result->noticeHooks = conn->noticeHooks;
193
194 /* consider copying conn's errorMessage */
195 switch (status)
196 {
198 case PGRES_COMMAND_OK:
199 case PGRES_TUPLES_OK:
200 case PGRES_COPY_OUT:
201 case PGRES_COPY_IN:
202 case PGRES_COPY_BOTH:
205 /* non-error cases */
206 break;
207 default:
208 /* we intentionally do not use or modify errorReported here */
209 pqSetResultError(result, &conn->errorMessage, 0);
210 break;
211 }
212
213 /* copy events last; result must be valid if we need to PQclear */
214 if (conn->nEvents > 0)
215 {
216 result->events = dupEvents(conn->events, conn->nEvents,
217 &result->memorySize);
218 if (!result->events)
219 {
220 PQclear(result);
221 return NULL;
222 }
223 result->nEvents = conn->nEvents;
224 }
225 }
226 else
227 {
228 /* defaults... */
229 result->noticeHooks.noticeRec = NULL;
230 result->noticeHooks.noticeRecArg = NULL;
231 result->noticeHooks.noticeProc = NULL;
232 result->noticeHooks.noticeProcArg = NULL;
234 }
235
236 return result;
237}
void pqSetResultError(PGresult *res, PQExpBuffer errorMessage, int offset)
Definition: fe-exec.c:692
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:124
@ PGRES_SINGLE_TUPLE
Definition: libpq-fe.h:137
@ PGRES_EMPTY_QUERY
Definition: libpq-fe.h:123
struct pg_result PGresult
Definition: libpq-fe.h:213
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
void * noticeProcArg
Definition: libpq-int.h:160
PQnoticeProcessor noticeProc
Definition: libpq-int.h:159
void * noticeRecArg
Definition: libpq-int.h:158
PQExpBufferData errorMessage
Definition: libpq-int.h:671
int nEvents
Definition: libpq-int.h:460
PGNoticeHooks noticeHooks
Definition: libpq-int.h:456
PGEvent * events
Definition: libpq-int.h:459
int curOffset
Definition: libpq-int.h:214
char null_field[1]
Definition: libpq-int.h:206
char * errMsg
Definition: libpq-int.h:201
int spaceLeft
Definition: libpq-int.h:215
char * errQuery
Definition: libpq-int.h:203

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

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

◆ PQnfields()

◆ PQnotifies()

PGnotify * PQnotifies ( PGconn conn)

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

2668{
2669 PGnotify *event;
2670
2671 if (!conn)
2672 return NULL;
2673
2674 /* Parse any available data to see if we can extract NOTIFY messages. */
2676
2677 event = conn->notifyHead;
2678 if (event)
2679 {
2680 conn->notifyHead = event->next;
2681 if (!conn->notifyHead)
2682 conn->notifyTail = NULL;
2683 event->next = NULL; /* don't let app see the internal state */
2684 }
2685 return event;
2686}
struct pgNotify * next
Definition: libpq-fe.h:233
PGnotify * notifyHead
Definition: libpq-int.h:478
PGnotify * notifyTail
Definition: libpq-int.h:479

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

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

◆ PQnparams()

int PQnparams ( const PGresult res)

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

3916{
3917 if (!res)
3918 return 0;
3919 return res->numParameters;
3920}

References pg_result::numParameters.

◆ PQntuples()

int PQntuples ( const PGresult res)

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

3482{
3483 if (!res)
3484 return 0;
3485 return res->ntups;
3486}

References pg_result::ntups.

Referenced by add_tablespace_footer(), addFooterToPublicationDesc(), append_depends_on_extension(), appendQualifiedRelation(), BaseBackup(), buildMatViewRefreshDependencies(), check_and_drop_existing_subscriptions(), check_for_connection_status(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_is_install_user(), check_new_cluster_logical_replication_slots(), check_new_cluster_subscription_configuration(), check_old_cluster_subscription_state(), cluster_all_databases(), collectBinaryUpgradeClassOids(), collectComments(), collectRoleNames(), collectSecLabels(), collectSequences(), compile_database_list(), compile_relation_list_one_db(), create_publication(), CreateReplicationSlot(), createViewAsClause(), describeOneTableDetails(), describePublications(), describeRoles(), describeTableDetails(), drop_failover_replication_slots(), dropDBs(), DropReplicationSlot(), dropRoles(), dropTablespaces(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpEnumType(), dumpOpclass(), dumpOpfamily(), dumpRelationStats(), dumpRoleGUCPrivs(), 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(), ExecQueryAndProcessResults(), ExecQueryTuples(), execute_dml_stmt(), execute_foreign_modify(), ExecuteSqlQueryForSingleRow(), expand_dbname_patterns(), expand_extension_name_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), fetch_more_data(), generate_object_name(), get_create_object_cmd(), get_db_infos(), get_loadable_libraries(), get_parallel_tabidx_list(), get_parallel_tables_list(), get_primary_sysid(), get_tablespace_paths(), get_template0_info(), getAccessMethods(), getAdditionalACLs(), getAggregates(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getIndexes(), getInherits(), getLOs(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPartitioningInfo(), getPolicies(), getProcLangs(), getPublicationNamespaces(), getPublications(), getPublicationTables(), getRules(), GetSlotInformation(), getSubscriptions(), getSubscriptionTables(), getTableAttrs(), GetTableInfo(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_endstreaming(), libpqrcv_identify_system(), libpqrcv_processTuples(), libpqrcv_readtimelinehistoryfile(), listDbRoleSettings(), listExtensionContents(), listSchemas(), listTables(), listTSConfigsVerbose(), listTSParsersVerbose(), lo_initialize(), lookup_object_oid(), main(), make_tuple_from_result_row(), materializeResult(), old_9_6_invalidate_hash_indexes(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresGetAnalyzeInfoForForeignTable(), postgresImportForeignSchema(), PQconnectPoll(), PQdisplayTuples(), PQencryptPasswordConn(), PQprint(), PQprintTuples(), printCrosstab(), printQuery(), PrintResultInCrosstab(), process_data_type_check(), process_extension_updates(), process_incompat_polymorphics(), process_isn_and_int8_passing_mismatch(), process_loadable_libraries(), process_old_cluster_logical_slot_infos(), process_old_sub_state_check(), process_queued_fetch_requests(), process_rel_infos(), process_user_defined_encoding_conversions(), process_user_defined_postfix_ops(), process_with_oids_check(), processExtensionTables(), readCommandResponse(), ReadEndOfStreamingResult(), ReceiveXlogStream(), reindex_all_databases(), retrieve_objects(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_simple_query(), RunIdentifySystem(), set_frozenxids(), set_replication_progress(), show_binary_results(), sql_exec(), StoreQueryTuple(), storeRow(), test_pipeline_abort(), test_singlerowmode(), test_transaction(), try_complete_step(), vacuum_all_databases(), vacuumlo(), verify_btree_slot_handler(), verify_heap_slot_handler(), and wait_for_connection_state().

◆ PQoidStatus()

char * PQoidStatus ( const PGresult res)

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

3766{
3767 /*
3768 * This must be enough to hold the result. Don't laugh, this is better
3769 * than what this function used to do.
3770 */
3771 static char buf[24];
3772
3773 size_t len;
3774
3775 if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
3776 return "";
3777
3778 len = strspn(res->cmdStatus + 7, "0123456789");
3779 if (len > sizeof(buf) - 1)
3780 len = sizeof(buf) - 1;
3781 memcpy(buf, res->cmdStatus + 7, len);
3782 buf[len] = '\0';
3783
3784 return buf;
3785}
static char * buf
Definition: pg_test_fsync.c:72

References buf, pg_result::cmdStatus, and len.

◆ PQoidValue()

Oid PQoidValue ( const PGresult res)

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

3794{
3795 char *endptr = NULL;
3796 unsigned long result;
3797
3798 if (!res ||
3799 strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
3800 res->cmdStatus[7] < '0' ||
3801 res->cmdStatus[7] > '9')
3802 return InvalidOid;
3803
3804 result = strtoul(res->cmdStatus + 7, &endptr, 10);
3805
3806 if (!endptr || (*endptr != ' ' && *endptr != '\0'))
3807 return InvalidOid;
3808 else
3809 return (Oid) result;
3810}
unsigned int Oid
Definition: postgres_ext.h:32

References pg_result::cmdStatus, and InvalidOid.

Referenced by ecpg_process_output(), and PrintQueryStatus().

◆ PQparamtype()

Oid PQparamtype ( const PGresult res,
int  param_num 
)

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

3927{
3928 if (!check_param_number(res, param_num))
3929 return InvalidOid;
3930 if (res->paramDescs)
3931 return res->paramDescs[param_num].typid;
3932 else
3933 return InvalidOid;
3934}
static int check_param_number(const PGresult *res, int param_num)
Definition: fe-exec.c:3548

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

◆ pqPipelineFlush()

static int pqPipelineFlush ( PGconn conn)
static

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

4017{
4020 return pqFlush(conn);
4021 return 0;
4022}
#define OUTBUFFER_THRESHOLD
Definition: libpq-int.h:928
int outCount
Definition: libpq-int.h:573

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

Referenced by pqPipelineSyncInternal(), PQsendFlushRequest(), PQsendPrepare(), PQsendQueryGuts(), and PQsendTypedCommand().

◆ pqPipelineProcessQueue()

static void pqPipelineProcessQueue ( PGconn conn)
static

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

3181{
3182 switch (conn->asyncStatus)
3183 {
3184 case PGASYNC_COPY_IN:
3185 case PGASYNC_COPY_OUT:
3186 case PGASYNC_COPY_BOTH:
3187 case PGASYNC_READY:
3188 case PGASYNC_READY_MORE:
3189 case PGASYNC_BUSY:
3190 /* client still has to process current query or results */
3191 return;
3192
3193 case PGASYNC_IDLE:
3194
3195 /*
3196 * If we're in IDLE mode and there's some command in the queue,
3197 * get us into PIPELINE_IDLE mode and process normally. Otherwise
3198 * there's nothing for us to do.
3199 */
3200 if (conn->cmd_queue_head != NULL)
3201 {
3203 break;
3204 }
3205 return;
3206
3209 /* next query please */
3210 break;
3211 }
3212
3213 /*
3214 * Reset partial-result mode. (Client has to set it up for each query, if
3215 * desired.)
3216 */
3217 conn->partialResMode = false;
3218 conn->singleRowMode = false;
3219 conn->maxChunkSize = 0;
3220
3221 /*
3222 * If there are no further commands to process in the queue, get us in
3223 * "real idle" mode now.
3224 */
3225 if (conn->cmd_queue_head == NULL)
3226 {
3228 return;
3229 }
3230
3231 /*
3232 * Reset the error state. This and the next couple of steps correspond to
3233 * what PQsendQueryStart didn't do for this query.
3234 */
3236
3237 /* Initialize async result-accumulation state */
3239
3242 {
3243 /*
3244 * In an aborted pipeline we don't get anything from the server for
3245 * each result; we're just discarding commands from the queue until we
3246 * get to the next sync from the server.
3247 *
3248 * The PGRES_PIPELINE_ABORTED results tell the client that its queries
3249 * got aborted.
3250 */
3252 if (!conn->result)
3253 {
3254 libpq_append_conn_error(conn, "out of memory");
3256 return;
3257 }
3259 }
3260 else
3261 {
3262 /* allow parsing to continue */
3264 }
3265}
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:779
@ PGRES_PIPELINE_ABORTED
Definition: libpq-fe.h:139
int maxChunkSize
Definition: libpq-int.h:474
bool singleRowMode
Definition: libpq-int.h:473
bool partialResMode
Definition: libpq-int.h:472

References Assert(), pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, libpq_append_conn_error(), pg_conn::maxChunkSize, pg_conn::partialResMode, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_PIPELINE_IDLE, PGASYNC_READY, PGASYNC_READY_MORE, PGQUERY_SYNC, PGRES_PIPELINE_ABORTED, pg_conn::pipelineStatus, PQ_PIPELINE_ABORTED, PQ_PIPELINE_OFF, pqClearAsyncResult(), pqClearConnErrorState, PQmakeEmptyPGresult(), pqSaveErrorResult(), PGcmdQueueEntry::queryclass, pg_conn::result, and pg_conn::singleRowMode.

Referenced by pqAppendCmdQueueEntry(), and PQgetResult().

◆ PQpipelineSync()

int PQpipelineSync ( PGconn conn)

◆ pqPipelineSyncInternal()

static int pqPipelineSyncInternal ( PGconn conn,
bool  immediate_flush 
)
static

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

3295{
3296 PGcmdQueueEntry *entry;
3297
3298 if (!conn)
3299 return 0;
3300
3302 {
3303 libpq_append_conn_error(conn, "cannot send pipeline when not in pipeline mode");
3304 return 0;
3305 }
3306
3307 switch (conn->asyncStatus)
3308 {
3309 case PGASYNC_COPY_IN:
3310 case PGASYNC_COPY_OUT:
3311 case PGASYNC_COPY_BOTH:
3312 /* should be unreachable */
3314 "internal error: cannot send pipeline while in COPY\n");
3315 return 0;
3316 case PGASYNC_READY:
3317 case PGASYNC_READY_MORE:
3318 case PGASYNC_BUSY:
3319 case PGASYNC_IDLE:
3321 /* OK to send sync */
3322 break;
3323 }
3324
3325 entry = pqAllocCmdQueueEntry(conn);
3326 if (entry == NULL)
3327 return 0; /* error msg already set */
3328
3329 entry->queryclass = PGQUERY_SYNC;
3330 entry->query = NULL;
3331
3332 /* construct the Sync message */
3333 if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
3334 pqPutMsgEnd(conn) < 0)
3335 goto sendFailed;
3336
3337 /*
3338 * Give the data a push. In nonblock mode, don't complain if we're unable
3339 * to send it all; PQgetResult() will do any additional flushing needed.
3340 * If immediate_flush is disabled, the data is pushed if we are past the
3341 * size threshold.
3342 */
3343 if (immediate_flush)
3344 {
3345 if (pqFlush(conn) < 0)
3346 goto sendFailed;
3347 }
3348 else
3349 {
3350 if (pqPipelineFlush(conn) < 0)
3351 goto sendFailed;
3352 }
3353
3354 /* OK, it's launched! */
3356
3357 return 1;
3358
3359sendFailed:
3361 /* error message should be set up already */
3362 return 0;
3363}
static PGcmdQueueEntry * pqAllocCmdQueueEntry(PGconn *conn)
Definition: fe-exec.c:1306
static void pqAppendCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1339
static int pqPipelineFlush(PGconn *conn)
Definition: fe-exec.c:4016
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:473
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:532
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
#define PqMsg_Sync
Definition: protocol.h:27

References appendPQExpBufferStr(), pg_conn::asyncStatus, conn, pg_conn::errorMessage, libpq_append_conn_error(), PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_PIPELINE_IDLE, PGASYNC_READY, PGASYNC_READY_MORE, PGQUERY_SYNC, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqAllocCmdQueueEntry(), pqAppendCmdQueueEntry(), pqFlush(), PqMsg_Sync, pqPipelineFlush(), pqPutMsgEnd(), pqPutMsgStart(), pqRecycleCmdQueueEntry(), PGcmdQueueEntry::query, and PGcmdQueueEntry::queryclass.

Referenced by PQpipelineSync(), and PQsendPipelineSync().

◆ PQprepare()

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

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

2309{
2310 if (!PQexecStart(conn))
2311 return NULL;
2312 if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
2313 return NULL;
2314 return PQexecFinish(conn);
2315}
int PQsendPrepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:1536

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

Referenced by DescribeQuery(), init_libpq_conn(), main(), prepare_common(), prepareCommand(), and test_uniqviol().

◆ pqPrepareAsyncResult()

PGresult * pqPrepareAsyncResult ( PGconn conn)

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

852{
853 PGresult *res;
854
855 res = conn->result;
856 if (res)
857 {
858 /*
859 * If the pre-existing result is an ERROR (presumably something
860 * received from the server), assume that it represents whatever is in
861 * conn->errorMessage, and advance errorReported.
862 */
865 }
866 else
867 {
868 /*
869 * We get here after internal-to-libpq errors. We should probably
870 * always have error_result = true, but if we don't, gin up some error
871 * text.
872 */
873 if (!conn->error_result)
874 libpq_append_conn_error(conn, "no error text available");
875
876 /* Paranoia: be sure errorReported offset is sane */
877 if (conn->errorReported < 0 ||
879 conn->errorReported = 0;
880
881 /*
882 * Make a PGresult struct for the error. We temporarily lie about the
883 * result status, so that PQmakeEmptyPGresult doesn't uselessly copy
884 * all of conn->errorMessage.
885 */
887 if (res)
888 {
889 /*
890 * Report whatever new error text we have, and advance
891 * errorReported.
892 */
896 }
897 else
898 {
899 /*
900 * Ouch, not enough memory for a PGresult. Fortunately, we have a
901 * card up our sleeve: we can use the static OOM_result. Casting
902 * away const here is a bit ugly, but it seems best to declare
903 * OOM_result as const, in hopes it will be allocated in read-only
904 * storage.
905 */
906 res = unconstify(PGresult *, &OOM_result);
907
908 /*
909 * Don't advance errorReported. Perhaps we'll be able to report
910 * the text later.
911 */
912 }
913 }
914
915 /*
916 * Replace conn->result with saved_result, if any. In the normal case
917 * there isn't a saved result and we're just dropping ownership of the
918 * current result. In partial-result mode this restores the situation to
919 * what it was before we created the current partial result.
920 */
922 conn->error_result = false; /* saved_result is never an error */
923 conn->saved_result = NULL;
924
925 return res;
926}
#define unconstify(underlying_type, expr)
Definition: c.h:1216
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:135
int errorReported
Definition: libpq-int.h:672

References conn, pg_conn::error_result, pg_conn::errorMessage, pg_conn::errorReported, PQExpBufferData::len, libpq_append_conn_error(), OOM_result, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PQmakeEmptyPGresult(), pqSetResultError(), pg_conn::result, pg_result::resultStatus, pg_conn::saved_result, and unconstify.

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

◆ PQputCopyData()

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

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

2696{
2697 if (!conn)
2698 return -1;
2701 {
2702 libpq_append_conn_error(conn, "no COPY in progress");
2703 return -1;
2704 }
2705
2706 /*
2707 * Process any NOTICE or NOTIFY messages that might be pending in the
2708 * input buffer. Since the server might generate many notices during the
2709 * COPY, we want to clean those out reasonably promptly to prevent
2710 * indefinite expansion of the input buffer. (Note: the actual read of
2711 * input data into the input buffer happens down inside pqSendSome, but
2712 * it's not authorized to get rid of the data again.)
2713 */
2715
2716 if (nbytes > 0)
2717 {
2718 /*
2719 * Try to flush any previously sent data in preference to growing the
2720 * output buffer. If we can't enlarge the buffer enough to hold the
2721 * data, return 0 in the nonblock case, else hard error. (For
2722 * simplicity, always assume 5 bytes of overhead.)
2723 */
2724 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2725 {
2726 if (pqFlush(conn) < 0)
2727 return -1;
2728 if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2729 conn))
2730 return pqIsnonblocking(conn) ? 0 : -1;
2731 }
2732 /* Send the data (too simple to delegate to fe-protocol files) */
2733 if (pqPutMsgStart(PqMsg_CopyData, conn) < 0 ||
2734 pqPutnchar(buffer, nbytes, conn) < 0 ||
2735 pqPutMsgEnd(conn) < 0)
2736 return -1;
2737 }
2738 return 1;
2739}
int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:287
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:202
#define PqMsg_CopyData
Definition: protocol.h:65
int outBufSize
Definition: libpq-int.h:572

References pg_conn::asyncStatus, conn, libpq_append_conn_error(), pg_conn::outBufSize, pg_conn::outCount, parseInput(), PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, pqCheckOutBufferSpace(), pqFlush(), pqIsnonblocking, PqMsg_CopyData, pqPutMsgEnd(), pqPutMsgStart(), and pqPutnchar().

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

◆ PQputCopyEnd()

int PQputCopyEnd ( PGconn conn,
const char *  errormsg 
)

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

2750{
2751 if (!conn)
2752 return -1;
2755 {
2756 libpq_append_conn_error(conn, "no COPY in progress");
2757 return -1;
2758 }
2759
2760 /*
2761 * Send the COPY END indicator. This is simple enough that we don't
2762 * bother delegating it to the fe-protocol files.
2763 */
2764 if (errormsg)
2765 {
2766 /* Send COPY FAIL */
2767 if (pqPutMsgStart(PqMsg_CopyFail, conn) < 0 ||
2768 pqPuts(errormsg, conn) < 0 ||
2769 pqPutMsgEnd(conn) < 0)
2770 return -1;
2771 }
2772 else
2773 {
2774 /* Send COPY DONE */
2775 if (pqPutMsgStart(PqMsg_CopyDone, conn) < 0 ||
2776 pqPutMsgEnd(conn) < 0)
2777 return -1;
2778 }
2779
2780 /*
2781 * If we sent the COPY command in extended-query mode, we must issue a
2782 * Sync as well.
2783 */
2784 if (conn->cmd_queue_head &&
2786 {
2787 if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
2788 pqPutMsgEnd(conn) < 0)
2789 return -1;
2790 }
2791
2792 /* Return to active duty */
2795 else
2797
2798 /* Try to flush data */
2799 if (pqFlush(conn) < 0)
2800 return -1;
2801
2802 return 1;
2803}
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:152
#define PqMsg_CopyDone
Definition: protocol.h:64
#define PqMsg_CopyFail
Definition: protocol.h:29

References pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, libpq_append_conn_error(), PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGQUERY_SIMPLE, pqFlush(), PqMsg_CopyDone, PqMsg_CopyFail, PqMsg_Sync, pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), and PGcmdQueueEntry::queryclass.

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

◆ PQputline()

int PQputline ( PGconn conn,
const char *  string 
)

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

2919{
2920 return PQputnbytes(conn, string, strlen(string));
2921}
int PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2928

References conn, and PQputnbytes().

Referenced by initPopulateTable().

◆ PQputnbytes()

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

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

2929{
2930 if (PQputCopyData(conn, buffer, nbytes) > 0)
2931 return 0;
2932 else
2933 return EOF;
2934}
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2695

References conn, and PQputCopyData().

Referenced by PQputline().

◆ pqRecycleCmdQueueEntry()

static void pqRecycleCmdQueueEntry ( PGconn conn,
PGcmdQueueEntry entry 
)
static

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

1387{
1388 if (entry == NULL)
1389 return;
1390
1391 /* recyclable entries should not have a follow-on command */
1392 Assert(entry->next == NULL);
1393
1394 if (entry->query)
1395 {
1396 free(entry->query);
1397 entry->query = NULL;
1398 }
1399
1400 entry->next = conn->cmd_queue_recycle;
1401 conn->cmd_queue_recycle = entry;
1402}

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

Referenced by pqCommandQueueAdvance(), pqPipelineSyncInternal(), PQsendPrepare(), PQsendQueryGuts(), PQsendQueryInternal(), and PQsendTypedCommand().

◆ PQresStatus()

char * PQresStatus ( ExecStatusType  status)

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

3420{
3421 if ((unsigned int) status >= lengthof(pgresStatus))
3422 return libpq_gettext("invalid ExecStatusType code");
3423 return pgresStatus[status];
3424}
#define lengthof(array)
Definition: c.h:759
char *const pgresStatus[]
Definition: fe-exec.c:32

References lengthof, libpq_gettext, and pgresStatus.

Referenced by BaseBackup(), process_result(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), and try_complete_step().

◆ PQresultAlloc()

void * PQresultAlloc ( PGresult res,
size_t  nBytes 
)

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

544{
545 /* Fail if argument is NULL or OOM_result */
546 if (!res || (const PGresult *) res == &OOM_result)
547 return NULL;
548
549 return pqResultAlloc(res, nBytes, true);
550}

References OOM_result, and pqResultAlloc().

Referenced by PQsetResultAttrs().

◆ pqResultAlloc()

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

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

564{
565 char *space;
566 PGresult_data *block;
567
568 if (!res)
569 return NULL;
570
571 if (nBytes <= 0)
572 return res->null_field;
573
574 /*
575 * If alignment is needed, round up the current position to an alignment
576 * boundary.
577 */
578 if (isBinary)
579 {
580 int offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
581
582 if (offset)
583 {
584 res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
585 res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
586 }
587 }
588
589 /* If there's enough space in the current block, no problem. */
590 if (nBytes <= (size_t) res->spaceLeft)
591 {
592 space = res->curBlock->space + res->curOffset;
593 res->curOffset += nBytes;
594 res->spaceLeft -= nBytes;
595 return space;
596 }
597
598 /*
599 * If the requested object is very large, give it its own block; this
600 * avoids wasting what might be most of the current block to start a new
601 * block. (We'd have to special-case requests bigger than the block size
602 * anyway.) The object is always given binary alignment in this case.
603 */
604 if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
605 {
606 size_t alloc_size = nBytes + PGRESULT_BLOCK_OVERHEAD;
607
608 block = (PGresult_data *) malloc(alloc_size);
609 if (!block)
610 return NULL;
611 res->memorySize += alloc_size;
612 space = block->space + PGRESULT_BLOCK_OVERHEAD;
613 if (res->curBlock)
614 {
615 /*
616 * Tuck special block below the active block, so that we don't
617 * have to waste the free space in the active block.
618 */
619 block->next = res->curBlock->next;
620 res->curBlock->next = block;
621 }
622 else
623 {
624 /* Must set up the new block as the first active block. */
625 block->next = NULL;
626 res->curBlock = block;
627 res->spaceLeft = 0; /* be sure it's marked full */
628 }
629 return space;
630 }
631
632 /* Otherwise, start a new block. */
634 if (!block)
635 return NULL;
637 block->next = res->curBlock;
638 res->curBlock = block;
639 if (isBinary)
640 {
641 /* object needs full alignment */
644 }
645 else
646 {
647 /* we can cram it right after the overhead pointer */
648 res->curOffset = sizeof(PGresult_data);
650 }
651
652 space = block->space + res->curOffset;
653 res->curOffset += nBytes;
654 res->spaceLeft -= nBytes;
655 return space;
656}
#define PGRESULT_DATA_BLOCKSIZE
Definition: fe-exec.c:142
#define PGRESULT_BLOCK_OVERHEAD
Definition: fe-exec.c:144
#define PGRESULT_SEP_ALLOC_THRESHOLD
Definition: fe-exec.c:145
#define PGRESULT_ALIGN_BOUNDARY
Definition: fe-exec.c:143
union pgresult_data PGresult_data
Definition: libpq-int.h:106
char space[1]
Definition: libpq-int.h:111

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

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

◆ PQresultErrorField()

char * PQresultErrorField ( const PGresult res,
int  fieldcode 
)

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

3467{
3468 PGMessageField *pfield;
3469
3470 if (!res)
3471 return NULL;
3472 for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
3473 {
3474 if (pfield->code == fieldcode)
3475 return pfield->contents;
3476 }
3477 return NULL;
3478}
struct pgMessageField * next
Definition: libpq-int.h:149
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:151

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

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

◆ PQresultErrorMessage()

◆ PQresultMemorySize()

size_t PQresultMemorySize ( const PGresult res)

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

664{
665 if (!res)
666 return 0;
667 return res->memorySize;
668}

References pg_result::memorySize.

◆ PQresultStatus()

ExecStatusType PQresultStatus ( const PGresult res)

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

3412{
3413 if (!res)
3414 return PGRES_FATAL_ERROR;
3415 return res->resultStatus;
3416}

References PGRES_FATAL_ERROR, and pg_result::resultStatus.

Referenced by _doSetSessionAuth(), _printTableAccessMethodNoStorage(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), AcceptResult(), advanceConnectionState(), BaseBackup(), check_and_drop_existing_subscriptions(), check_loadable_libraries(), check_prepare_conn(), check_publisher(), check_subscriber(), ClearOrSaveResult(), close_cursor(), compile_database_list(), compile_relation_list_one_db(), confirm_query_canceled_impl(), connect_database(), create_cursor(), create_logical_replication_slot(), create_publication(), create_subscription(), CreateReplicationSlot(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_record_internal(), deallocate_query(), DescribeQuery(), discardAbortedPipelineResults(), discardUntilSync(), do_sql_command_end(), drop_existing_subscriptions(), drop_failover_replication_slots(), drop_publication(), drop_replication_slot(), DropReplicationSlot(), dumpTableData_copy(), ecpg_check_PQresult(), ecpg_is_type_an_array(), ecpg_process_output(), enable_subscription(), EndDBCopyMode(), exec_command_password(), ExecQueryAndProcessResults(), execute_dml_stmt(), execute_foreign_modify(), executeCommand(), executeMaintenanceCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlQuery(), ExecuteSqlStatement(), executeStatement(), fetch_more_data(), generate_object_name(), get_create_object_cmd(), get_primary_sysid(), get_remote_estimate(), get_table_relkind(), GetConnection(), GetSlotInformation(), GetTableInfo(), handleCopyIn(), handleCopyOut(), HandleCopyResult(), HandleEndOfCopyStream(), init_libpq_conn(), initPopulateTable(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_alter_slot(), libpqrcv_connect(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_exec(), libpqrcv_identify_system(), libpqrcv_PQexec(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_startstreaming(), libpqsrv_get_result_last(), lo_close(), lo_creat(), lo_create(), lo_lseek(), lo_lseek64(), lo_open(), lo_read(), lo_tell(), lo_tell64(), lo_truncate(), lo_truncate64(), lo_unlink(), lo_write(), lockTableForWorker(), lookup_object_oid(), main(), materializeResult(), pgfdw_exec_cleanup_query_end(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresGetAnalyzeInfoForForeignTable(), postgresImportForeignSchema(), postgresReScanForeignScan(), PQconnectPoll(), PQencryptPasswordConn(), prepare_foreign_modify(), prepareCommand(), PrintQueryResult(), PrintQueryStatus(), PrintResultInCrosstab(), process_query_result(), process_queued_fetch_requests(), process_result(), readCommandResponse(), ReceiveCopyData(), ReceiveXlogStream(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_permutation(), run_simple_command(), run_simple_query(), RunIdentifySystem(), SendQuery(), server_is_in_recovery(), set_replication_progress(), setup_publisher(), should_processing_continue(), sql_conn(), sql_exec(), storeQueryResult(), StreamLogicalLog(), TableCommandResultHandler(), test_disallowed_in_pipeline(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), test_uniqviol(), try_complete_step(), tryExecuteStatement(), vacuumlo(), verify_btree_slot_handler(), verify_heap_slot_handler(), and wait_for_connection_state().

◆ pqResultStrdup()

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

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

676{
677 char *space = (char *) pqResultAlloc(res, strlen(str) + 1, false);
678
679 if (space)
680 strcpy(space, str);
681 return space;
682}

References pqResultAlloc(), and str.

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

◆ PQresultVerboseErrorMessage()

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

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

3438{
3439 PQExpBufferData workBuf;
3440
3441 /*
3442 * Because the caller is expected to free the result string, we must
3443 * strdup any constant result. We use plain strdup and document that
3444 * callers should expect NULL if out-of-memory.
3445 */
3446 if (!res ||
3449 return strdup(libpq_gettext("PGresult is not an error result\n"));
3450
3451 initPQExpBuffer(&workBuf);
3452
3453 pqBuildErrorMessage3(&workBuf, res, verbosity, show_context);
3454
3455 /* If insufficient memory to format the message, fail cleanly */
3456 if (PQExpBufferDataBroken(workBuf))
3457 {
3458 termPQExpBuffer(&workBuf);
3459 return strdup(libpq_gettext("out of memory\n"));
3460 }
3461
3462 return workBuf.data;
3463}
void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67

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

Referenced by exec_command_errverbose().

◆ pqRowProcessor()

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

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

1207{
1208 PGresult *res = conn->result;
1209 int nfields = res->numAttributes;
1210 const PGdataValue *columns = conn->rowBuf;
1211 PGresAttValue *tup;
1212 int i;
1213
1214 /*
1215 * In partial-result mode, if we don't already have a partial PGresult
1216 * then make one by cloning conn->result (which should hold the correct
1217 * result metadata by now). Then the original conn->result is moved over
1218 * to saved_result so that we can re-use it as a reference for future
1219 * partial results. The saved result will become active again after
1220 * pqPrepareAsyncResult() returns the partial result to the application.
1221 */
1222 if (conn->partialResMode && conn->saved_result == NULL)
1223 {
1224 /* Copy everything that should be in the result at this point */
1225 res = PQcopyResult(res,
1228 if (!res)
1229 return 0;
1230 /* Change result status to appropriate special value */
1232 /* And stash it as the active result */
1234 conn->result = res;
1235 }
1236
1237 /*
1238 * Basically we just allocate space in the PGresult for each field and
1239 * copy the data over.
1240 *
1241 * Note: on malloc failure, we return 0 leaving *errmsgp still NULL, which
1242 * caller will take to mean "out of memory". This is preferable to trying
1243 * to set up such a message here, because evidently there's not enough
1244 * memory for gettext() to do anything.
1245 */
1246 tup = (PGresAttValue *)
1247 pqResultAlloc(res, nfields * sizeof(PGresAttValue), true);
1248 if (tup == NULL)
1249 return 0;
1250
1251 for (i = 0; i < nfields; i++)
1252 {
1253 int clen = columns[i].len;
1254
1255 if (clen < 0)
1256 {
1257 /* null field */
1258 tup[i].len = NULL_LEN;
1259 tup[i].value = res->null_field;
1260 }
1261 else
1262 {
1263 bool isbinary = (res->attDescs[i].format != 0);
1264 char *val;
1265
1266 val = (char *) pqResultAlloc(res, clen + 1, isbinary);
1267 if (val == NULL)
1268 return 0;
1269
1270 /* copy and zero-terminate the data (even if it's binary) */
1271 memcpy(val, columns[i].value, clen);
1272 val[clen] = '\0';
1273
1274 tup[i].len = clen;
1275 tup[i].value = val;
1276 }
1277 }
1278
1279 /* And add the tuple to the PGresult's tuple array */
1280 if (!pqAddTuple(res, tup, errmsgp))
1281 return 0;
1282
1283 /*
1284 * Success. In partial-result mode, if we have enough rows then make the
1285 * result available to the client immediately.
1286 */
1287 if (conn->partialResMode && res->ntups >= conn->maxChunkSize)
1289
1290 return 1;
1291}
PGresult * PQcopyResult(const PGresult *src, int flags)
Definition: fe-exec.c:318
static bool pqAddTuple(PGresult *res, PGresAttValue *tup, const char **errmsgp)
Definition: fe-exec.c:993
long val
Definition: informix.c:689
static struct @165 value
PGdataValue * rowBuf
Definition: libpq-int.h:581

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

Referenced by getAnotherTuple().

◆ pqSaveErrorResult()

void pqSaveErrorResult ( PGconn conn)

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

804{
805 /* Drop any pending result ... */
807 /* ... and set flag to remember to make an error result later */
808 conn->error_result = true;
809}

References conn, pg_conn::error_result, and pqClearAsyncResult().

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

◆ pqSaveMessageField()

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

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

1061{
1062 PGMessageField *pfield;
1063
1064 pfield = (PGMessageField *)
1065 pqResultAlloc(res,
1066 offsetof(PGMessageField, contents) +
1067 strlen(value) + 1,
1068 true);
1069 if (!pfield)
1070 return; /* out of memory? */
1071 pfield->code = code;
1072 strcpy(pfield->contents, value);
1073 pfield->next = res->errFields;
1074 res->errFields = pfield;
1075}

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

Referenced by pqGetErrorNotice3(), and pqInternalNotice().

◆ pqSaveParameterStatus()

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

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

1082{
1083 pgParameterStatus *pstatus;
1084 pgParameterStatus *prev;
1085
1086 /*
1087 * Forget any old information about the parameter
1088 */
1089 for (pstatus = conn->pstatus, prev = NULL;
1090 pstatus != NULL;
1091 prev = pstatus, pstatus = pstatus->next)
1092 {
1093 if (strcmp(pstatus->name, name) == 0)
1094 {
1095 if (prev)
1096 prev->next = pstatus->next;
1097 else
1098 conn->pstatus = pstatus->next;
1099 free(pstatus); /* frees name and value strings too */
1100 break;
1101 }
1102 }
1103
1104 /*
1105 * Store new info as a single malloc block
1106 */
1107 pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
1108 strlen(name) + strlen(value) + 2);
1109 if (pstatus)
1110 {
1111 char *ptr;
1112
1113 ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
1114 pstatus->name = ptr;
1115 strcpy(ptr, name);
1116 ptr += strlen(name) + 1;
1117 pstatus->value = ptr;
1118 strcpy(ptr, value);
1119 pstatus->next = conn->pstatus;
1120 conn->pstatus = pstatus;
1121 }
1122
1123 /*
1124 * Save values of settings that are of interest to libpq in fields of the
1125 * PGconn object. We keep client_encoding and standard_conforming_strings
1126 * in static variables as well, so that PQescapeString and PQescapeBytea
1127 * can behave somewhat sanely (at least in single-connection-using
1128 * programs).
1129 */
1130 if (strcmp(name, "client_encoding") == 0)
1131 {
1133 /* if we don't recognize the encoding name, fall back to SQL_ASCII */
1134 if (conn->client_encoding < 0)
1137 }
1138 else if (strcmp(name, "standard_conforming_strings") == 0)
1139 {
1140 conn->std_strings = (strcmp(value, "on") == 0);
1142 }
1143 else if (strcmp(name, "server_version") == 0)
1144 {
1145 /* We convert the server version to numeric form. */
1146 int cnt;
1147 int vmaj,
1148 vmin,
1149 vrev;
1150
1151 cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
1152
1153 if (cnt == 3)
1154 {
1155 /* old style, e.g. 9.6.1 */
1156 conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
1157 }
1158 else if (cnt == 2)
1159 {
1160 if (vmaj >= 10)
1161 {
1162 /* new style, e.g. 10.1 */
1163 conn->sversion = 100 * 100 * vmaj + vmin;
1164 }
1165 else
1166 {
1167 /* old style without minor version, e.g. 9.6devel */
1168 conn->sversion = (100 * vmaj + vmin) * 100;
1169 }
1170 }
1171 else if (cnt == 1)
1172 {
1173 /* new style without minor version, e.g. 10devel */
1174 conn->sversion = 100 * 100 * vmaj;
1175 }
1176 else
1177 conn->sversion = 0; /* unknown */
1178 }
1179 else if (strcmp(name, "default_transaction_read_only") == 0)
1180 {
1182 (strcmp(value, "on") == 0) ? PG_BOOL_YES : PG_BOOL_NO;
1183 }
1184 else if (strcmp(name, "in_hot_standby") == 0)
1185 {
1187 (strcmp(value, "on") == 0) ? PG_BOOL_YES : PG_BOOL_NO;
1188 }
1189 else if (strcmp(name, "scram_iterations") == 0)
1190 {
1192 }
1193}
struct pgParameterStatus pgParameterStatus
@ PG_BOOL_YES
Definition: libpq-int.h:265
@ PG_BOOL_NO
Definition: libpq-int.h:266
#define pg_char_to_encoding
Definition: pg_wchar.h:629
struct pgParameterStatus * next
Definition: libpq-int.h:279
PGTernaryBool in_hot_standby
Definition: libpq-int.h:556
PGTernaryBool default_transaction_read_only
Definition: libpq-int.h:555
pgParameterStatus * pstatus
Definition: libpq-int.h:552
int scram_sha_256_iterations
Definition: libpq-int.h:601

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

Referenced by getParameterStatus().

◆ pqSaveWriteError()

static void pqSaveWriteError ( PGconn conn)
static

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

821{
822 /*
823 * If write_err_msg is null because of previous strdup failure, do what we
824 * can. (It's likely our machinations here will get OOM failures as well,
825 * but might as well try.)
826 */
827 if (conn->write_err_msg)
828 {
830 /* Avoid possibly appending the same message twice */
831 conn->write_err_msg[0] = '\0';
832 }
833 else
834 libpq_append_conn_error(conn, "write to server failed");
835
837}
char * write_err_msg
Definition: libpq-int.h:513

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

Referenced by PQgetResult().

◆ PQsendClosePortal()

int PQsendClosePortal ( PGconn conn,
const char *  portal 
)

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

2570{
2571 return PQsendTypedCommand(conn, PqMsg_Close, 'P', portal);
2572}

References conn, PqMsg_Close, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQsendClosePrepared()

int PQsendClosePrepared ( PGconn conn,
const char *  stmt 
)

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

2557{
2558 return PQsendTypedCommand(conn, PqMsg_Close, 'S', stmt);
2559}

References conn, PqMsg_Close, PQsendTypedCommand(), and stmt.

Referenced by ExecQueryAndProcessResults(), and test_prepared().

◆ PQsendDescribePortal()

int PQsendDescribePortal ( PGconn conn,
const char *  portal 
)

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

2505{
2506 return PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal);
2507}

References conn, PqMsg_Describe, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQsendDescribePrepared()

int PQsendDescribePrepared ( PGconn conn,
const char *  stmt 
)

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

2492{
2494}

References conn, PqMsg_Describe, PQsendTypedCommand(), and stmt.

Referenced by test_prepared().

◆ PQsendFlushRequest()

int PQsendFlushRequest ( PGconn conn)

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

3372{
3373 if (!conn)
3374 return 0;
3375
3376 /* Don't try to send if we know there's no live connection. */
3377 if (conn->status != CONNECTION_OK)
3378 {
3379 libpq_append_conn_error(conn, "no connection to the server");
3380 return 0;
3381 }
3382
3383 /* Can't send while already busy, either, unless enqueuing for later */
3384 if (conn->asyncStatus != PGASYNC_IDLE &&
3386 {
3387 libpq_append_conn_error(conn, "another command is already in progress");
3388 return 0;
3389 }
3390
3391 if (pqPutMsgStart(PqMsg_Flush, conn) < 0 ||
3392 pqPutMsgEnd(conn) < 0)
3393 {
3394 return 0;
3395 }
3396
3397 /*
3398 * Give the data a push (in pipeline mode, only if we're past the size
3399 * threshold). In nonblock mode, don't complain if we're unable to send
3400 * it all; PQgetResult() will do any additional flushing needed.
3401 */
3402 if (pqPipelineFlush(conn) < 0)
3403 return 0;
3404
3405 return 1;
3406}
#define PqMsg_Flush
Definition: protocol.h:24

References pg_conn::asyncStatus, conn, CONNECTION_OK, libpq_append_conn_error(), PGASYNC_IDLE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, PqMsg_Flush, pqPipelineFlush(), pqPutMsgEnd(), pqPutMsgStart(), and pg_conn::status.

Referenced by ExecQueryAndProcessResults(), test_nosync(), test_pipeline_idle(), test_singlerowmode(), and test_uniqviol().

◆ PQsendPipelineSync()

int PQsendPipelineSync ( PGconn conn)

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

3283{
3284 return pqPipelineSyncInternal(conn, false);
3285}

References conn, and pqPipelineSyncInternal().

Referenced by ExecQueryAndProcessResults(), executeMetaCommand(), and test_multi_pipelines().

◆ PQsendPrepare()

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

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

1539{
1540 PGcmdQueueEntry *entry = NULL;
1541
1542 if (!PQsendQueryStart(conn, true))
1543 return 0;
1544
1545 /* check the arguments */
1546 if (!stmtName)
1547 {
1548 libpq_append_conn_error(conn, "statement name is a null pointer");
1549 return 0;
1550 }
1551 if (!query)
1552 {
1553 libpq_append_conn_error(conn, "command string is a null pointer");
1554 return 0;
1555 }
1556 if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1557 {
1558 libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1560 return 0;
1561 }
1562
1563 entry = pqAllocCmdQueueEntry(conn);
1564 if (entry == NULL)
1565 return 0; /* error msg already set */
1566
1567 /* construct the Parse message */
1568 if (pqPutMsgStart(PqMsg_Parse, conn) < 0 ||
1569 pqPuts(stmtName, conn) < 0 ||
1570 pqPuts(query, conn) < 0)
1571 goto sendFailed;
1572
1573 if (nParams > 0 && paramTypes)
1574 {
1575 int i;
1576
1577 if (pqPutInt(nParams, 2, conn) < 0)
1578 goto sendFailed;
1579 for (i = 0; i < nParams; i++)
1580 {
1581 if (pqPutInt(paramTypes[i], 4, conn) < 0)
1582 goto sendFailed;
1583 }
1584 }
1585 else
1586 {
1587 if (pqPutInt(0, 2, conn) < 0)
1588 goto sendFailed;
1589 }
1590 if (pqPutMsgEnd(conn) < 0)
1591 goto sendFailed;
1592
1593 /* Add a Sync, unless in pipeline mode. */
1595 {
1596 if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
1597 pqPutMsgEnd(conn) < 0)
1598 goto sendFailed;
1599 }
1600
1601 /* remember we are doing just a Parse */
1602 entry->queryclass = PGQUERY_PREPARE;
1603
1604 /* and remember the query text too, if possible */
1605 /* if insufficient memory, query just winds up NULL */
1606 entry->query = strdup(query);
1607
1608 /*
1609 * Give the data a push (in pipeline mode, only if we're past the size
1610 * threshold). In nonblock mode, don't complain if we're unable to send
1611 * it all; PQgetResult() will do any additional flushing needed.
1612 */
1613 if (pqPipelineFlush(conn) < 0)
1614 goto sendFailed;
1615
1616 /* OK, it's launched! */
1618
1619 return 1;
1620
1621sendFailed:
1623 /* error message should be set up already */
1624 return 0;
1625}
static bool PQsendQueryStart(PGconn *conn, bool newQuery)
Definition: fe-exec.c:1673
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:253
#define PQ_QUERY_PARAM_MAX_LIMIT
Definition: libpq-fe.h:507
@ PGQUERY_PREPARE
Definition: libpq-int.h:330
#define PqMsg_Parse
Definition: protocol.h:25

References conn, i, libpq_append_conn_error(), PGQUERY_PREPARE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, PQ_QUERY_PARAM_MAX_LIMIT, pqAllocCmdQueueEntry(), pqAppendCmdQueueEntry(), PqMsg_Parse, PqMsg_Sync, pqPipelineFlush(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), pqRecycleCmdQueueEntry(), PQsendQueryStart(), PGcmdQueueEntry::query, and PGcmdQueueEntry::queryclass.

Referenced by ExecQueryAndProcessResults(), PQprepare(), prepare_foreign_modify(), test_pipelined_insert(), test_prepared(), and test_transaction().

◆ PQsendQuery()

◆ PQsendQueryContinue()

int PQsendQueryContinue ( PGconn conn,
const char *  query 
)

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

1423{
1424 return PQsendQueryInternal(conn, query, false);
1425}

References conn, and PQsendQueryInternal().

Referenced by PQconnectPoll().

◆ PQsendQueryGuts()

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

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

1766{
1767 int i;
1768 PGcmdQueueEntry *entry;
1769
1770 entry = pqAllocCmdQueueEntry(conn);
1771 if (entry == NULL)
1772 return 0; /* error msg already set */
1773
1774 /*
1775 * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync
1776 * (if not in pipeline mode), using specified statement name and the
1777 * unnamed portal.
1778 */
1779
1780 if (command)
1781 {
1782 /* construct the Parse message */
1783 if (pqPutMsgStart(PqMsg_Parse, conn) < 0 ||
1784 pqPuts(stmtName, conn) < 0 ||
1785 pqPuts(command, conn) < 0)
1786 goto sendFailed;
1787 if (nParams > 0 && paramTypes)
1788 {
1789 if (pqPutInt(nParams, 2, conn) < 0)
1790 goto sendFailed;
1791 for (i = 0; i < nParams; i++)
1792 {
1793 if (pqPutInt(paramTypes[i], 4, conn) < 0)
1794 goto sendFailed;
1795 }
1796 }
1797 else
1798 {
1799 if (pqPutInt(0, 2, conn) < 0)
1800 goto sendFailed;
1801 }
1802 if (pqPutMsgEnd(conn) < 0)
1803 goto sendFailed;
1804 }
1805
1806 /* Construct the Bind message */
1807 if (pqPutMsgStart(PqMsg_Bind, conn) < 0 ||
1808 pqPuts("", conn) < 0 ||
1809 pqPuts(stmtName, conn) < 0)
1810 goto sendFailed;
1811
1812 /* Send parameter formats */
1813 if (nParams > 0 && paramFormats)
1814 {
1815 if (pqPutInt(nParams, 2, conn) < 0)
1816 goto sendFailed;
1817 for (i = 0; i < nParams; i++)
1818 {
1819 if (pqPutInt(paramFormats[i], 2, conn) < 0)
1820 goto sendFailed;
1821 }
1822 }
1823 else
1824 {
1825 if (pqPutInt(0, 2, conn) < 0)
1826 goto sendFailed;
1827 }
1828
1829 if (pqPutInt(nParams, 2, conn) < 0)
1830 goto sendFailed;
1831
1832 /* Send parameters */
1833 for (i = 0; i < nParams; i++)
1834 {
1835 if (paramValues && paramValues[i])
1836 {
1837 int nbytes;
1838
1839 if (paramFormats && paramFormats[i] != 0)
1840 {
1841 /* binary parameter */
1842 if (paramLengths)
1843 nbytes = paramLengths[i];
1844 else
1845 {
1846 libpq_append_conn_error(conn, "length must be given for binary parameter");
1847 goto sendFailed;
1848 }
1849 }
1850 else
1851 {
1852 /* text parameter, do not use paramLengths */
1853 nbytes = strlen(paramValues[i]);
1854 }
1855 if (pqPutInt(nbytes, 4, conn) < 0 ||
1856 pqPutnchar(paramValues[i], nbytes, conn) < 0)
1857 goto sendFailed;
1858 }
1859 else
1860 {
1861 /* take the param as NULL */
1862 if (pqPutInt(-1, 4, conn) < 0)
1863 goto sendFailed;
1864 }
1865 }
1866 if (pqPutInt(1, 2, conn) < 0 ||
1867 pqPutInt(resultFormat, 2, conn))
1868 goto sendFailed;
1869 if (pqPutMsgEnd(conn) < 0)
1870 goto sendFailed;
1871
1872 /* construct the Describe Portal message */
1873 if (pqPutMsgStart(PqMsg_Describe, conn) < 0 ||
1874 pqPutc('P', conn) < 0 ||
1875 pqPuts("", conn) < 0 ||
1876 pqPutMsgEnd(conn) < 0)
1877 goto sendFailed;
1878
1879 /* construct the Execute message */
1880 if (pqPutMsgStart(PqMsg_Execute, conn) < 0 ||
1881 pqPuts("", conn) < 0 ||
1882 pqPutInt(0, 4, conn) < 0 ||
1883 pqPutMsgEnd(conn) < 0)
1884 goto sendFailed;
1885
1886 /* construct the Sync message if not in pipeline mode */
1888 {
1889 if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
1890 pqPutMsgEnd(conn) < 0)
1891 goto sendFailed;
1892 }
1893
1894 /* remember we are using extended query protocol */
1896
1897 /* and remember the query text too, if possible */
1898 /* if insufficient memory, query just winds up NULL */
1899 if (command)
1900 entry->query = strdup(command);
1901
1902 /*
1903 * Give the data a push (in pipeline mode, only if we're past the size
1904 * threshold). In nonblock mode, don't complain if we're unable to send
1905 * it all; PQgetResult() will do any additional flushing needed.
1906 */
1907 if (pqPipelineFlush(conn) < 0)
1908 goto sendFailed;
1909
1910 /* OK, it's launched! */
1912
1913 return 1;
1914
1915sendFailed:
1917 /* error message should be set up already */
1918 return 0;
1919}
int pqPutc(char c, PGconn *conn)
Definition: fe-misc.c:92
#define PqMsg_Bind
Definition: protocol.h:19
#define PqMsg_Execute
Definition: protocol.h:22

References conn, i, libpq_append_conn_error(), PGQUERY_EXTENDED, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqAllocCmdQueueEntry(), pqAppendCmdQueueEntry(), PqMsg_Bind, PqMsg_Describe, PqMsg_Execute, PqMsg_Parse, PqMsg_Sync, pqPipelineFlush(), pqPutc(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), pqPuts(), pqRecycleCmdQueueEntry(), PGcmdQueueEntry::query, and PGcmdQueueEntry::queryclass.

Referenced by PQsendQueryParams(), and PQsendQueryPrepared().

◆ PQsendQueryInternal()

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

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

1429{
1430 PGcmdQueueEntry *entry = NULL;
1431
1432 if (!PQsendQueryStart(conn, newQuery))
1433 return 0;
1434
1435 /* check the argument */
1436 if (!query)
1437 {
1438 libpq_append_conn_error(conn, "command string is a null pointer");
1439 return 0;
1440 }
1441
1443 {
1444 libpq_append_conn_error(conn, "%s not allowed in pipeline mode",
1445 "PQsendQuery");
1446 return 0;
1447 }
1448
1449 entry = pqAllocCmdQueueEntry(conn);
1450 if (entry == NULL)
1451 return 0; /* error msg already set */
1452
1453 /* Send the query message(s) */
1454 /* construct the outgoing Query message */
1455 if (pqPutMsgStart(PqMsg_Query, conn) < 0 ||
1456 pqPuts(query, conn) < 0 ||
1457 pqPutMsgEnd(conn) < 0)
1458 {
1459 /* error message should be set up already */
1461 return 0;
1462 }
1463
1464 /* remember we are using simple query protocol */
1465 entry->queryclass = PGQUERY_SIMPLE;
1466 /* and remember the query text too, if possible */
1467 entry->query = strdup(query);
1468
1469 /*
1470 * Give the data a push. In nonblock mode, don't complain if we're unable
1471 * to send it all; PQgetResult() will do any additional flushing needed.
1472 */
1473 if (pqFlush(conn) < 0)
1474 goto sendFailed;
1475
1476 /* OK, it's launched! */
1478
1479 return 1;
1480
1481sendFailed:
1483 /* error message should be set up already */
1484 return 0;
1485}
#define PqMsg_Query
Definition: protocol.h:26

References conn, libpq_append_conn_error(), PGQUERY_SIMPLE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqAllocCmdQueueEntry(), pqAppendCmdQueueEntry(), pqFlush(), PqMsg_Query, pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), pqRecycleCmdQueueEntry(), PQsendQueryStart(), PGcmdQueueEntry::query, and PGcmdQueueEntry::queryclass.

Referenced by PQsendQuery(), and PQsendQueryContinue().

◆ PQsendQueryParams()

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

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

1500{
1501 if (!PQsendQueryStart(conn, true))
1502 return 0;
1503
1504 /* check the arguments */
1505 if (!command)
1506 {
1507 libpq_append_conn_error(conn, "command string is a null pointer");
1508 return 0;
1509 }
1510 if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1511 {
1512 libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1514 return 0;
1515 }
1516
1517 return PQsendQueryGuts(conn,
1518 command,
1519 "", /* use unnamed statement */
1520 nParams,
1521 paramTypes,
1522 paramValues,
1523 paramLengths,
1524 paramFormats,
1525 resultFormat);
1526}
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:1757

References conn, libpq_append_conn_error(), PQ_QUERY_PARAM_MAX_LIMIT, PQsendQueryGuts(), and PQsendQueryStart().

Referenced by create_cursor(), ExecQueryAndProcessResults(), execute_dml_stmt(), libpqsrv_exec_params(), PQexecParams(), send_cancellable_query_impl(), sendCommand(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_simple_pipeline(), test_singlerowmode(), and test_transaction().

◆ PQsendQueryPrepared()

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

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

1640{
1641 if (!PQsendQueryStart(conn, true))
1642 return 0;
1643
1644 /* check the arguments */
1645 if (!stmtName)
1646 {
1647 libpq_append_conn_error(conn, "statement name is a null pointer");
1648 return 0;
1649 }
1650 if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1651 {
1652 libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1654 return 0;
1655 }
1656
1657 return PQsendQueryGuts(conn,
1658 NULL, /* no command to parse */
1659 stmtName,
1660 nParams,
1661 NULL, /* no param types */
1662 paramValues,
1663 paramLengths,
1664 paramFormats,
1665 resultFormat);
1666}

References conn, libpq_append_conn_error(), PQ_QUERY_PARAM_MAX_LIMIT, PQsendQueryGuts(), and PQsendQueryStart().

Referenced by ExecQueryAndProcessResults(), execute_foreign_modify(), PQexecPrepared(), process_queued_fetch_requests(), sendCommand(), test_pipelined_insert(), test_transaction(), and test_uniqviol().

◆ PQsendQueryStart()

static bool PQsendQueryStart ( PGconn conn,
bool  newQuery 
)
static

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

1674{
1675 if (!conn)
1676 return false;
1677
1678 /*
1679 * If this is the beginning of a query cycle, reset the error state.
1680 * However, in pipeline mode with something already queued, the error
1681 * buffer belongs to that command and we shouldn't clear it.
1682 */
1683 if (newQuery && conn->cmd_queue_head == NULL)
1685
1686 /* Don't try to send if we know there's no live connection. */
1687 if (conn->status != CONNECTION_OK)
1688 {
1689 libpq_append_conn_error(conn, "no connection to the server");
1690 return false;
1691 }
1692
1693 /* Can't send while already busy, either, unless enqueuing for later */
1694 if (conn->asyncStatus != PGASYNC_IDLE &&
1696 {
1697 libpq_append_conn_error(conn, "another command is already in progress");
1698 return false;
1699 }
1700
1702 {
1703 /*
1704 * When enqueuing commands we don't change much of the connection
1705 * state since it's already in use for the current command. The
1706 * connection state will get updated when pqPipelineProcessQueue()
1707 * advances to start processing the queued message.
1708 *
1709 * Just make sure we can safely enqueue given the current connection
1710 * state. We can enqueue behind another queue item, or behind a
1711 * non-queue command (one that sends its own sync), but we can't
1712 * enqueue if the connection is in a copy state.
1713 */
1714 switch (conn->asyncStatus)
1715 {
1716 case PGASYNC_IDLE:
1718 case PGASYNC_READY:
1719 case PGASYNC_READY_MORE:
1720 case PGASYNC_BUSY:
1721 /* ok to queue */
1722 break;
1723
1724 case PGASYNC_COPY_IN:
1725 case PGASYNC_COPY_OUT:
1726 case PGASYNC_COPY_BOTH:
1727 libpq_append_conn_error(conn, "cannot queue commands during COPY");
1728 return false;
1729 }
1730 }
1731 else
1732 {
1733 /*
1734 * This command's results will come in immediately. Initialize async
1735 * result-accumulation state
1736 */
1738
1739 /* reset partial-result mode */
1740 conn->partialResMode = false;
1741 conn->singleRowMode = false;
1742 conn->maxChunkSize = 0;
1743 }
1744
1745 /* ready to send command message */
1746 return true;
1747}

References pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, CONNECTION_OK, libpq_append_conn_error(), pg_conn::maxChunkSize, pg_conn::partialResMode, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_PIPELINE_IDLE, PGASYNC_READY, PGASYNC_READY_MORE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqClearAsyncResult(), pqClearConnErrorState, pg_conn::singleRowMode, and pg_conn::status.

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

◆ PQsendTypedCommand()

static int PQsendTypedCommand ( PGconn conn,
char  command,
char  type,
const char *  target 
)
static

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

2590{
2591 PGcmdQueueEntry *entry = NULL;
2592
2593 /* Treat null target as empty string */
2594 if (!target)
2595 target = "";
2596
2597 if (!PQsendQueryStart(conn, true))
2598 return 0;
2599
2600 entry = pqAllocCmdQueueEntry(conn);
2601 if (entry == NULL)
2602 return 0; /* error msg already set */
2603
2604 /* construct the Close message */
2605 if (pqPutMsgStart(command, conn) < 0 ||
2606 pqPutc(type, conn) < 0 ||
2607 pqPuts(target, conn) < 0 ||
2608 pqPutMsgEnd(conn) < 0)
2609 goto sendFailed;
2610
2611 /* construct the Sync message */
2613 {
2614 if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
2615 pqPutMsgEnd(conn) < 0)
2616 goto sendFailed;
2617 }
2618
2619 /* remember if we are doing a Close or a Describe */
2620 if (command == PqMsg_Close)
2621 {
2622 entry->queryclass = PGQUERY_CLOSE;
2623 }
2624 else if (command == PqMsg_Describe)
2625 {
2627 }
2628 else
2629 {
2630 libpq_append_conn_error(conn, "unrecognized message type \"%c\"", command);
2631 goto sendFailed;
2632 }
2633
2634 /*
2635 * Give the data a push (in pipeline mode, only if we're past the size
2636 * threshold). In nonblock mode, don't complain if we're unable to send
2637 * it all; PQgetResult() will do any additional flushing needed.
2638 */
2639 if (pqPipelineFlush(conn) < 0)
2640 goto sendFailed;
2641
2642 /* OK, it's launched! */
2644
2645 return 1;
2646
2647sendFailed:
2649 /* error message should be set up already */
2650 return 0;
2651}
@ PGQUERY_DESCRIBE
Definition: libpq-int.h:331
@ PGQUERY_CLOSE
Definition: libpq-int.h:333
const char * type

References conn, libpq_append_conn_error(), PGQUERY_CLOSE, PGQUERY_DESCRIBE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqAllocCmdQueueEntry(), pqAppendCmdQueueEntry(), PqMsg_Close, PqMsg_Describe, PqMsg_Sync, pqPipelineFlush(), pqPutc(), pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), pqRecycleCmdQueueEntry(), PQsendQueryStart(), PGcmdQueueEntry::queryclass, and type.

Referenced by PQclosePortal(), PQclosePrepared(), PQdescribePortal(), PQdescribePrepared(), PQsendClosePortal(), PQsendClosePrepared(), PQsendDescribePortal(), and PQsendDescribePrepared().

◆ PQsetChunkedRowsMode()

int PQsetChunkedRowsMode ( PGconn conn,
int  chunkSize 
)

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

1966{
1967 if (chunkSize > 0 && canChangeResultMode(conn))
1968 {
1969 conn->partialResMode = true;
1970 conn->singleRowMode = false;
1971 conn->maxChunkSize = chunkSize;
1972 return 1;
1973 }
1974 else
1975 return 0;
1976}
static bool canChangeResultMode(PGconn *conn)
Definition: fe-exec.c:1925

References canChangeResultMode(), conn, pg_conn::maxChunkSize, pg_conn::partialResMode, and pg_conn::singleRowMode.

Referenced by ExecQueryAndProcessResults(), and test_singlerowmode().

◆ PQsetnonblocking()

int PQsetnonblocking ( PGconn conn,
int  arg 
)

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

3945{
3946 bool barg;
3947
3948 if (!conn || conn->status == CONNECTION_BAD)
3949 return -1;
3950
3951 barg = (arg ? true : false);
3952
3953 /* early out if the socket is already in the state requested */
3954 if (barg == conn->nonblocking)
3955 return 0;
3956
3957 /*
3958 * to guarantee constancy for flushing/query/result-polling behavior we
3959 * need to flush the send queue at this point in order to guarantee proper
3960 * behavior. this is ok because either they are making a transition _from_
3961 * or _to_ blocking mode, either way we can block them.
3962 *
3963 * Clear error state in case pqFlush adds to it, unless we're actively
3964 * pipelining, in which case it seems best not to.
3965 */
3966 if (conn->cmd_queue_head == NULL)
3968
3969 /* if we are going from blocking to non-blocking flush here */
3970 if (pqFlush(conn))
3971 return -1;
3972
3973 conn->nonblocking = barg;
3974
3975 return 0;
3976}
return true
Definition: isn.c:127
void * arg
bool nonblocking
Definition: libpq-int.h:469

References arg, pg_conn::cmd_queue_head, conn, CONNECTION_BAD, pg_conn::nonblocking, pqClearConnErrorState, pqFlush(), pg_conn::status, and true.

Referenced by test_cancel(), test_pipelined_insert(), and test_uniqviol().

◆ PQsetResultAttrs()

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

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

250{
251 int i;
252
253 /* Fail if argument is NULL or OOM_result */
254 if (!res || (const PGresult *) res == &OOM_result)
255 return false;
256
257 /* If attrs already exist, they cannot be overwritten. */
258 if (res->numAttributes > 0)
259 return false;
260
261 /* ignore no-op request */
262 if (numAttributes <= 0 || !attDescs)
263 return true;
264
265 res->attDescs = (PGresAttDesc *)
266 PQresultAlloc(res, numAttributes * sizeof(PGresAttDesc));
267
268 if (!res->attDescs)
269 return false;
270
271 res->numAttributes = numAttributes;
272 memcpy(res->attDescs, attDescs, numAttributes * sizeof(PGresAttDesc));
273
274 /* deep-copy the attribute names, and determine format */
275 res->binary = 1;
276 for (i = 0; i < res->numAttributes; i++)
277 {
278 if (res->attDescs[i].name)
279 res->attDescs[i].name = pqResultStrdup(res, res->attDescs[i].name);
280 else
281 res->attDescs[i].name = res->null_field;
282
283 if (!res->attDescs[i].name)
284 return false;
285
286 if (res->attDescs[i].format == 0)
287 res->binary = 0;
288 }
289
290 return true;
291}
void * PQresultAlloc(PGresult *res, size_t nBytes)
Definition: fe-exec.c:543
char * pqResultStrdup(PGresult *res, const char *str)
Definition: fe-exec.c:675

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

Referenced by PQcopyResult().

◆ pqSetResultError()

void pqSetResultError ( PGresult res,
PQExpBuffer  errorMessage,
int  offset 
)

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

693{
694 char *msg;
695
696 if (!res)
697 return;
698
699 /*
700 * We handle two OOM scenarios here. The errorMessage buffer might be
701 * marked "broken" due to having previously failed to allocate enough
702 * memory for the message, or it might be fine but pqResultStrdup fails
703 * and returns NULL. In either case, just make res->errMsg point directly
704 * at a constant "out of memory" string.
705 */
706 if (!PQExpBufferBroken(errorMessage))
707 msg = pqResultStrdup(res, errorMessage->data + offset);
708 else
709 msg = NULL;
710 if (msg)
711 res->errMsg = msg;
712 else
713 res->errMsg = libpq_gettext("out of memory\n");
714}
#define PQExpBufferBroken(str)
Definition: pqexpbuffer.h:59

References PQExpBufferData::data, pg_result::errMsg, libpq_gettext, PQExpBufferBroken, and pqResultStrdup().

Referenced by pqGetErrorNotice3(), PQmakeEmptyPGresult(), and pqPrepareAsyncResult().

◆ PQsetSingleRowMode()

int PQsetSingleRowMode ( PGconn conn)

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

1949{
1951 {
1952 conn->partialResMode = true;
1953 conn->singleRowMode = true;
1954 conn->maxChunkSize = 1;
1955 return 1;
1956 }
1957 else
1958 return 0;
1959}

References canChangeResultMode(), conn, pg_conn::maxChunkSize, pg_conn::partialResMode, and pg_conn::singleRowMode.

Referenced by process_queued_fetch_requests(), storeQueryResult(), test_pipeline_abort(), and test_singlerowmode().

◆ PQsetvalue()

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

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

453{
454 PGresAttValue *attval;
455 const char *errmsg = NULL;
456
457 /* Fail if argument is NULL or OOM_result */
458 if (!res || (const PGresult *) res == &OOM_result)
459 return false;
460
461 /* Invalid field_num? */
462 if (!check_field_number(res, field_num))
463 return false;
464
465 /* Invalid tup_num, must be <= ntups */
466 if (tup_num < 0 || tup_num > res->ntups)
467 {
469 "row number %d is out of range 0..%d",
470 tup_num, res->ntups);
471 return false;
472 }
473
474 /* need to allocate a new tuple? */
475 if (tup_num == res->ntups)
476 {
477 PGresAttValue *tup;
478 int i;
479
480 tup = (PGresAttValue *)
481 pqResultAlloc(res, res->numAttributes * sizeof(PGresAttValue),
482 true);
483
484 if (!tup)
485 goto fail;
486
487 /* initialize each column to NULL */
488 for (i = 0; i < res->numAttributes; i++)
489 {
490 tup[i].len = NULL_LEN;
491 tup[i].value = res->null_field;
492 }
493
494 /* add it to the array */
495 if (!pqAddTuple(res, tup, &errmsg))
496 goto fail;
497 }
498
499 attval = &res->tuples[tup_num][field_num];
500
501 /* treat either NULL_LEN or NULL value pointer as a NULL field */
502 if (len == NULL_LEN || value == NULL)
503 {
504 attval->len = NULL_LEN;
505 attval->value = res->null_field;
506 }
507 else if (len <= 0)
508 {
509 attval->len = 0;
510 attval->value = res->null_field;
511 }
512 else
513 {
514 attval->value = (char *) pqResultAlloc(res, len + 1, true);
515 if (!attval->value)
516 goto fail;
517 attval->len = len;
518 memcpy(attval->value, value, len);
519 attval->value[len] = '\0';
520 }
521
522 return true;
523
524 /*
525 * Report failure via pqInternalNotice. If preceding code didn't provide
526 * an error message, assume "out of memory" was meant.
527 */
528fail:
529 if (!errmsg)
530 errmsg = libpq_gettext("out of memory");
531 pqInternalNotice(&res->noticeHooks, "%s", errmsg);
532
533 return false;
534}
int errmsg(const char *fmt,...)
Definition: elog.c:1070

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

Referenced by PQcopyResult().

◆ PQunescapeBytea()

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

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

4554{
4555 size_t strtextlen,
4556 buflen;
4557 unsigned char *buffer,
4558 *tmpbuf;
4559 size_t i,
4560 j;
4561
4562 if (strtext == NULL)
4563 return NULL;
4564
4565 strtextlen = strlen((const char *) strtext);
4566
4567 if (strtext[0] == '\\' && strtext[1] == 'x')
4568 {
4569 const unsigned char *s;
4570 unsigned char *p;
4571
4572 buflen = (strtextlen - 2) / 2;
4573 /* Avoid unportable malloc(0) */
4574 buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
4575 if (buffer == NULL)
4576 return NULL;
4577
4578 s = strtext + 2;
4579 p = buffer;
4580 while (*s)
4581 {
4582 char v1,
4583 v2;
4584
4585 /*
4586 * Bad input is silently ignored. Note that this includes
4587 * whitespace between hex pairs, which is allowed by byteain.
4588 */
4589 v1 = get_hex(*s++);
4590 if (!*s || v1 == (char) -1)
4591 continue;
4592 v2 = get_hex(*s++);
4593 if (v2 != (char) -1)
4594 *p++ = (v1 << 4) | v2;
4595 }
4596
4597 buflen = p - buffer;
4598 }
4599 else
4600 {
4601 /*
4602 * Length of input is max length of output, but add one to avoid
4603 * unportable malloc(0) if input is zero-length.
4604 */
4605 buffer = (unsigned char *) malloc(strtextlen + 1);
4606 if (buffer == NULL)
4607 return NULL;
4608
4609 for (i = j = 0; i < strtextlen;)
4610 {
4611 switch (strtext[i])
4612 {
4613 case '\\':
4614 i++;
4615 if (strtext[i] == '\\')
4616 buffer[j++] = strtext[i++];
4617 else
4618 {
4619 if ((ISFIRSTOCTDIGIT(strtext[i])) &&
4620 (ISOCTDIGIT(strtext[i + 1])) &&
4621 (ISOCTDIGIT(strtext[i + 2])))
4622 {
4623 int byte;
4624
4625 byte = OCTVAL(strtext[i++]);
4626 byte = (byte << 3) + OCTVAL(strtext[i++]);
4627 byte = (byte << 3) + OCTVAL(strtext[i++]);
4628 buffer[j++] = byte;
4629 }
4630 }
4631
4632 /*
4633 * Note: if we see '\' followed by something that isn't a
4634 * recognized escape sequence, we loop around having done
4635 * nothing except advance i. Therefore the something will
4636 * be emitted as ordinary data on the next cycle. Corner
4637 * case: '\' at end of string will just be discarded.
4638 */
4639 break;
4640
4641 default:
4642 buffer[j++] = strtext[i++];
4643 break;
4644 }
4645 }
4646 buflen = j; /* buflen is the length of the dequoted data */
4647 }
4648
4649 /* Shrink the buffer to be no larger than necessary */
4650 /* +1 avoids unportable behavior when buflen==0 */
4651 tmpbuf = realloc(buffer, buflen + 1);
4652
4653 /* It would only be a very brain-dead realloc that could fail, but... */
4654 if (!tmpbuf)
4655 {
4656 free(buffer);
4657 return NULL;
4658 }
4659
4660 *retbuflen = buflen;
4661 return tmpbuf;
4662}
static char get_hex(char c)
Definition: fe-exec.c:4389
#define ISOCTDIGIT(CH)
Definition: fe-exec.c:4537
#define OCTVAL(CH)
Definition: fe-exec.c:4538
#define ISFIRSTOCTDIGIT(CH)
Definition: fe-exec.c:4536
int j
Definition: isn.c:75
static StringInfoData tmpbuf
Definition: walsender.c:171

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

Variable Documentation

◆ hexlookup

const int8 hexlookup[128]
static
Initial value:
= {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
}

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

Referenced by get_hex().

◆ hextbl

const char hextbl[] = "0123456789abcdef"
static

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

Referenced by PQescapeByteaInternal().

◆ OOM_result

const PGresult OOM_result
static
Initial value:
= {
.resultStatus = PGRES_FATAL_ERROR,
.client_encoding = PG_SQL_ASCII,
.errMsg = "out of memory\n",
}

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

Referenced by PQclear(), pqPrepareAsyncResult(), PQresultAlloc(), PQsetResultAttrs(), and PQsetvalue().

◆ pgresStatus

char* const pgresStatus[]
Initial value:
= {
"PGRES_EMPTY_QUERY",
"PGRES_COMMAND_OK",
"PGRES_TUPLES_OK",
"PGRES_COPY_OUT",
"PGRES_COPY_IN",
"PGRES_BAD_RESPONSE",
"PGRES_NONFATAL_ERROR",
"PGRES_FATAL_ERROR",
"PGRES_COPY_BOTH",
"PGRES_SINGLE_TUPLE",
"PGRES_PIPELINE_SYNC",
"PGRES_PIPELINE_ABORTED",
"PGRES_TUPLES_CHUNK"
}

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

Referenced by PQresStatus().

◆ static_client_encoding

int static_client_encoding = PG_SQL_ASCII
static

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

Referenced by PQescapeString(), and pqSaveParameterStatus().

◆ static_std_strings

bool static_std_strings = false
static

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

Referenced by PQescapeBytea(), PQescapeString(), and pqSaveParameterStatus().