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)
 
int 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 bool add_size_overflow (size_t s1, size_t s2, size_t *dst)
 
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 4620 of file fe-exec.c.

◆ ISOCTDIGIT

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

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

◆ OCTVAL

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

Definition at line 4622 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

◆ add_size_overflow()

static bool add_size_overflow ( size_t  s1,
size_t  s2,
size_t *  dst 
)
static

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

4232{
4233 size_t result;
4234
4235 result = s1 + s2;
4236 if (result < s1 || result < s2)
4237 return true;
4238
4239 *dst = result;
4240 return false;
4241}
char * s1
char * s2

References s1, and s2.

Referenced by PQescapeByteaInternal(), and PQescapeInternal().

◆ canChangeResultMode()

static bool canChangeResultMode ( PGconn conn)
static

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

1942{
1943 /*
1944 * Only allow changing the mode when we have launched a query and not yet
1945 * received any results.
1946 */
1947 if (!conn)
1948 return false;
1950 return false;
1951 if (!conn->cmd_queue_head ||
1954 return false;
1956 return false;
1957 return true;
1958}
@ PGASYNC_BUSY
Definition: libpq-int.h:216
@ PGQUERY_SIMPLE
Definition: libpq-int.h:320
@ PGQUERY_EXTENDED
Definition: libpq-int.h:321
#define pgHavePendingResult(conn)
Definition: libpq-int.h:932
PGconn * conn
Definition: streamutil.c:52
PGQueryClass queryclass
Definition: libpq-int.h:345
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:463
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:489

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

3527{
3528 if (!res)
3529 return false; /* no way to display error message... */
3530 if (field_num < 0 || field_num >= res->numAttributes)
3531 {
3533 "column number %d is out of range 0..%d",
3534 field_num, res->numAttributes - 1);
3535 return false;
3536 }
3537 return true;
3538}
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:943
PGNoticeHooks noticeHooks
Definition: libpq-int.h:183
int numAttributes
Definition: libpq-int.h:167

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

3565{
3566 if (!res)
3567 return false; /* no way to display error message... */
3568 if (param_num < 0 || param_num >= res->numParameters)
3569 {
3571 "parameter number %d is out of range 0..%d",
3572 param_num, res->numParameters - 1);
3573 return false;
3574 }
3575
3576 return true;
3577}
int numParameters
Definition: libpq-int.h:172

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

3543{
3544 if (!res)
3545 return false; /* no way to display error message... */
3546 if (tup_num < 0 || tup_num >= res->ntups)
3547 {
3549 "row number %d is out of range 0..%d",
3550 tup_num, res->ntups - 1);
3551 return false;
3552 }
3553 if (field_num < 0 || field_num >= res->numAttributes)
3554 {
3556 "column number %d is out of range 0..%d",
3557 field_num, res->numAttributes - 1);
3558 return false;
3559 }
3560 return true;
3561}
int ntups
Definition: libpq-int.h:166

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:77
struct PGEvent PGEvent
void * passThrough
Definition: libpq-int.h:159
PGEventProc proc
Definition: libpq-int.h:157
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 4445 of file fe-exec.c.

4446{
4447 int res = -1;
4448
4449 if (c > 0 && c < 127)
4450 res = hexlookup[(unsigned char) c];
4451
4452 return (char) res;
4453}
static const int8 hexlookup[128]
Definition: fe-exec.c:4433
char * c

References hexlookup.

Referenced by PQunescapeBytea().

◆ getCopyResult()

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

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

2241{
2242 /*
2243 * If the server connection has been lost, don't pretend everything is
2244 * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
2245 * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
2246 * error in the earlier steps in PQgetResult). The text returned in the
2247 * result is whatever is in conn->errorMessage; we hope that was filled
2248 * with something relevant when the lost connection was detected.
2249 */
2250 if (conn->status != CONNECTION_OK)
2251 {
2254 return pqPrepareAsyncResult(conn);
2255 }
2256
2257 /* If we have an async result for the COPY, return that */
2258 if (conn->result && conn->result->resultStatus == copytype)
2259 return pqPrepareAsyncResult(conn);
2260
2261 /* Otherwise, invent a suitable PGresult */
2262 return PQmakeEmptyPGresult(conn, copytype);
2263}
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:856
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:808
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:159
@ CONNECTION_OK
Definition: libpq-fe.h:84
@ PGASYNC_IDLE
Definition: libpq-int.h:215
PGresult * result
Definition: libpq-int.h:606
ConnStatusType status
Definition: libpq-int.h:462
ExecStatusType resultStatus
Definition: libpq-int.h:174

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

2037{
2039}
void pqParseInput3(PGconn *conn)
Definition: fe-protocol3.c:69

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

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

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

1323{
1324 PGcmdQueueEntry *entry;
1325
1326 if (conn->cmd_queue_recycle == NULL)
1327 {
1328 entry = (PGcmdQueueEntry *) malloc(sizeof(PGcmdQueueEntry));
1329 if (entry == NULL)
1330 {
1331 libpq_append_conn_error(conn, "out of memory");
1332 return NULL;
1333 }
1334 }
1335 else
1336 {
1337 entry = conn->cmd_queue_recycle;
1338 conn->cmd_queue_recycle = entry->next;
1339 }
1340 entry->next = NULL;
1341 entry->query = NULL;
1342
1343 return entry;
1344}
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition: oauth-utils.c:95
struct PGcmdQueueEntry * next
Definition: libpq-int.h:347
PGcmdQueueEntry * cmd_queue_recycle
Definition: libpq-int.h:496

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

1356{
1357 Assert(entry->next == NULL);
1358
1359 if (conn->cmd_queue_head == NULL)
1360 conn->cmd_queue_head = entry;
1361 else
1362 conn->cmd_queue_tail->next = entry;
1363
1364 conn->cmd_queue_tail = entry;
1365
1366 switch (conn->pipelineStatus)
1367 {
1368 case PQ_PIPELINE_OFF:
1369 case PQ_PIPELINE_ON:
1370
1371 /*
1372 * When not in pipeline aborted state, if there's a result ready
1373 * to be consumed, let it be so (that is, don't change away from
1374 * READY or READY_MORE); otherwise set us busy to wait for
1375 * something to arrive from the server.
1376 */
1379 break;
1380
1382
1383 /*
1384 * In aborted pipeline state, we don't expect anything from the
1385 * server (since we don't send any queries that are queued).
1386 * Therefore, if IDLE then do what PQgetResult would do to let
1387 * itself consume commands from the queue; if we're in any other
1388 * state, we don't have to do anything.
1389 */
1390 if (conn->asyncStatus == PGASYNC_IDLE ||
1393 break;
1394 }
1395}
static void pqPipelineProcessQueue(PGconn *conn)
Definition: fe-exec.c:3196
Assert(PointerIsAligned(start, uint64))
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:187
@ PQ_PIPELINE_ABORTED
Definition: libpq-fe.h:189
@ PQ_PIPELINE_ON
Definition: libpq-fe.h:188
@ PGASYNC_PIPELINE_IDLE
Definition: libpq-int.h:225
PGcmdQueueEntry * cmd_queue_tail
Definition: libpq-int.h:490
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:469

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

3514{
3515 if (!res)
3516 return 0;
3517 return res->binary;
3518}
int binary
Definition: libpq-int.h:176

References pg_result::binary.

Referenced by HandleCopyResult().

◆ PQclear()

void PQclear ( PGresult res)

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

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

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 pqClearAsyncResult(), PQcopyResult(), PQexecFinish(), PQexecStart(), pqInternalNotice(), and PQmakeEmptyPGresult().

◆ pqClearAsyncResult()

void pqClearAsyncResult ( PGconn conn)

◆ PQclosePortal()

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

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

2556{
2557 if (!PQexecStart(conn))
2558 return NULL;
2559 if (!PQsendTypedCommand(conn, PqMsg_Close, 'P', portal))
2560 return NULL;
2561 return PQexecFinish(conn);
2562}
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2426
static int PQsendTypedCommand(PGconn *conn, char command, char type, const char *target)
Definition: fe-exec.c:2605
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2360
#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 2537 of file fe-exec.c.

2538{
2539 if (!PQexecStart(conn))
2540 return NULL;
2542 return NULL;
2543 return PQexecFinish(conn);
2544}
#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 3768 of file fe-exec.c.

3769{
3770 if (!res)
3771 return NULL;
3772 return res->cmdStatus;
3773}
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:175

References pg_result::cmdStatus.

◆ PQcmdTuples()

char * PQcmdTuples ( PGresult res)

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

3839{
3840 char *p,
3841 *c;
3842
3843 if (!res)
3844 return "";
3845
3846 if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3847 {
3848 p = res->cmdStatus + 7;
3849 /* INSERT: skip oid and space */
3850 while (*p && *p != ' ')
3851 p++;
3852 if (*p == 0)
3853 goto interpret_error; /* no space? */
3854 p++;
3855 }
3856 else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3857 strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3858 strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3859 p = res->cmdStatus + 7;
3860 else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0 ||
3861 strncmp(res->cmdStatus, "MERGE ", 6) == 0)
3862 p = res->cmdStatus + 6;
3863 else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3864 strncmp(res->cmdStatus, "COPY ", 5) == 0)
3865 p = res->cmdStatus + 5;
3866 else
3867 return "";
3868
3869 /* check that we have an integer (at least one digit, nothing else) */
3870 for (c = p; *c; c++)
3871 {
3872 if (!isdigit((unsigned char) *c))
3873 goto interpret_error;
3874 }
3875 if (c == p)
3876 goto interpret_error;
3877
3878 return p;
3879
3880interpret_error:
3882 "could not interpret result from server: %s",
3883 res->cmdStatus);
3884 return "";
3885}

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

◆ pqCommandQueueAdvance()

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

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

3159{
3160 PGcmdQueueEntry *prevquery;
3161
3162 if (conn->cmd_queue_head == NULL)
3163 return;
3164
3165 /*
3166 * If processing a query of simple query protocol, we only advance the
3167 * queue when we receive the ReadyForQuery message for it.
3168 */
3169 if (conn->cmd_queue_head->queryclass == PGQUERY_SIMPLE && !isReadyForQuery)
3170 return;
3171
3172 /*
3173 * If we're waiting for a SYNC, don't advance the queue until we get one.
3174 */
3175 if (conn->cmd_queue_head->queryclass == PGQUERY_SYNC && !gotSync)
3176 return;
3177
3178 /* delink element from queue */
3179 prevquery = conn->cmd_queue_head;
3181
3182 /* If the queue is now empty, reset the tail too */
3183 if (conn->cmd_queue_head == NULL)
3184 conn->cmd_queue_tail = NULL;
3185
3186 /* and make the queue element recyclable */
3187 prevquery->next = NULL;
3188 pqRecycleCmdQueueEntry(conn, prevquery);
3189}
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1402
@ PGQUERY_SYNC
Definition: libpq-int.h:324

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

2001{
2002 if (!conn)
2003 return 0;
2004
2005 /*
2006 * for non-blocking connections try to flush the send-queue, otherwise we
2007 * may never get a response for something that may not have already been
2008 * sent because it's in our write buffer!
2009 */
2010 if (pqIsnonblocking(conn))
2011 {
2012 if (pqFlush(conn) < 0)
2013 return 0;
2014 }
2015
2016 /*
2017 * Load more data, if available. We do this no matter what state we are
2018 * in, since we are probably getting called because the application wants
2019 * to get rid of a read-select condition. Note that we will NOT block
2020 * waiting for more input.
2021 */
2022 if (pqReadData(conn) < 0)
2023 return 0;
2024
2025 /* Parsing of the data waits till later. */
2026 return 1;
2027}
int pqReadData(PGconn *conn)
Definition: fe-misc.c:606
int pqFlush(PGconn *conn)
Definition: fe-misc.c:994
#define pqIsnonblocking(conn)
Definition: libpq-int.h:939

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

Referenced by advanceConnectionState(), consume_query_cancel_impl(), CopyStreamReceive(), dblink_get_notify(), dblink_is_busy(), do_sql_command_end(), ecpg_process_output(), 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:128
#define PG_COPYRES_TUPLES
Definition: libpq-fe.h:70
#define PG_COPYRES_ATTRS
Definition: libpq-fe.h:69
#define PG_COPYRES_EVENTS
Definition: libpq-fe.h:71
#define PG_COPYRES_NOTICEHOOKS
Definition: libpq-fe.h:72
const PGresult * src
Definition: libpq-events.h:60
PGresult * dest
Definition: libpq-events.h:61
int client_encoding
Definition: libpq-int.h:186
char * value
Definition: libpq-int.h:135

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

2491{
2492 if (!PQexecStart(conn))
2493 return NULL;
2494 if (!PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal))
2495 return NULL;
2496 return PQexecFinish(conn);
2497}
#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 2471 of file fe-exec.c.

2472{
2473 if (!PQexecStart(conn))
2474 return NULL;
2476 return NULL;
2477 return PQexecFinish(conn);
2478}

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

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

◆ PQendcopy()

int PQendcopy ( PGconn conn)

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

2966{
2967 if (!conn)
2968 return 0;
2969
2970 return pqEndcopy3(conn);
2971}
int pqEndcopy3(PGconn *conn)

References conn, and pqEndcopy3().

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

◆ PQenterPipelineMode()

int PQenterPipelineMode ( PGconn conn)

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

3059{
3060 if (!conn)
3061 return 0;
3062
3063 /* succeed with no action if already in pipeline mode */
3065 return 1;
3066
3068 {
3069 libpq_append_conn_error(conn, "cannot enter pipeline mode, connection not idle");
3070 return 0;
3071 }
3072
3074
3075 return 1;
3076}

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

4613{
4614 return PQescapeByteaInternal(NULL, from, from_length, to_length,
4616 false /* can't use hex */ );
4617}
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:4472
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 4596 of file fe-exec.c.

4599{
4600 if (!conn)
4601 return NULL;
4602
4603 if (conn->cmd_queue_head == NULL)
4605
4606 return PQescapeByteaInternal(conn, from, from_length, to_length,
4608 (conn->sversion >= 90000));
4609}
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:923
bool std_strings
Definition: libpq-int.h:557
int sversion
Definition: libpq-int.h:504

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

4475{
4476 const unsigned char *vp;
4477 unsigned char *rp;
4478 unsigned char *result;
4479 size_t i;
4480 size_t len;
4481 const size_t bslash_len = (std_strings ? 1 : 2);
4482
4483 /*
4484 * Calculate the escaped length, watching for overflow as we do with
4485 * PQescapeInternal(). The following code relies on a small constant
4486 * bslash_len so that small additions and multiplications don't need their
4487 * own overflow checks.
4488 *
4489 * Start with the empty string, which has 1 char ('\0').
4490 */
4491 len = 1;
4492
4493 if (use_hex)
4494 {
4495 /* We prepend "\x" and double each input character. */
4496 if (add_size_overflow(len, bslash_len + 1, &len) ||
4497 add_size_overflow(len, from_length, &len) ||
4498 add_size_overflow(len, from_length, &len))
4499 goto overflow;
4500 }
4501 else
4502 {
4503 vp = from;
4504 for (i = from_length; i > 0; i--, vp++)
4505 {
4506 if (*vp < 0x20 || *vp > 0x7e)
4507 {
4508 if (add_size_overflow(len, bslash_len + 3, &len)) /* octal "\ooo" */
4509 goto overflow;
4510 }
4511 else if (*vp == '\'')
4512 {
4513 if (add_size_overflow(len, 2, &len)) /* double each quote */
4514 goto overflow;
4515 }
4516 else if (*vp == '\\')
4517 {
4518 if (add_size_overflow(len, bslash_len * 2, &len)) /* double each backslash */
4519 goto overflow;
4520 }
4521 else
4522 {
4523 if (add_size_overflow(len, 1, &len))
4524 goto overflow;
4525 }
4526 }
4527 }
4528
4529 *to_length = len;
4530 rp = result = (unsigned char *) malloc(len);
4531 if (rp == NULL)
4532 {
4533 if (conn)
4534 libpq_append_conn_error(conn, "out of memory");
4535 return NULL;
4536 }
4537
4538 if (use_hex)
4539 {
4540 if (!std_strings)
4541 *rp++ = '\\';
4542 *rp++ = '\\';
4543 *rp++ = 'x';
4544 }
4545
4546 vp = from;
4547 for (i = from_length; i > 0; i--, vp++)
4548 {
4549 unsigned char c = *vp;
4550
4551 if (use_hex)
4552 {
4553 *rp++ = hextbl[(c >> 4) & 0xF];
4554 *rp++ = hextbl[c & 0xF];
4555 }
4556 else if (c < 0x20 || c > 0x7e)
4557 {
4558 if (!std_strings)
4559 *rp++ = '\\';
4560 *rp++ = '\\';
4561 *rp++ = (c >> 6) + '0';
4562 *rp++ = ((c >> 3) & 07) + '0';
4563 *rp++ = (c & 07) + '0';
4564 }
4565 else if (c == '\'')
4566 {
4567 *rp++ = '\'';
4568 *rp++ = '\'';
4569 }
4570 else if (c == '\\')
4571 {
4572 if (!std_strings)
4573 {
4574 *rp++ = '\\';
4575 *rp++ = '\\';
4576 }
4577 *rp++ = '\\';
4578 *rp++ = '\\';
4579 }
4580 else
4581 *rp++ = c;
4582 }
4583 *rp = '\0';
4584
4585 return result;
4586
4587overflow:
4588 if (conn)
4590 "escaped bytea size exceeds the maximum allowed (%zu)",
4591 SIZE_MAX);
4592 return NULL;
4593}
static const char hextbl[]
Definition: fe-exec.c:4431
static bool add_size_overflow(size_t s1, size_t s2, size_t *dst)
Definition: fe-exec.c:4231
const void size_t len

References add_size_overflow(), 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 4425 of file fe-exec.c.

4426{
4427 return PQescapeInternal(conn, str, len, true);
4428}
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:4251
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 4251 of file fe-exec.c.

4252{
4253 const char *s;
4254 char *result;
4255 char *rp;
4256 size_t num_quotes = 0; /* single or double, depending on as_ident */
4257 size_t num_backslashes = 0;
4258 size_t input_len = strnlen(str, len);
4259 size_t result_size;
4260 char quote_char = as_ident ? '"' : '\'';
4261 bool validated_mb = false;
4262
4263 /* We must have a connection, else fail immediately. */
4264 if (!conn)
4265 return NULL;
4266
4267 if (conn->cmd_queue_head == NULL)
4269
4270 /*
4271 * Scan the string for characters that must be escaped and for invalidly
4272 * encoded data.
4273 */
4274 s = str;
4275 for (size_t remaining = input_len; remaining > 0; remaining--, s++)
4276 {
4277 if (*s == quote_char)
4278 ++num_quotes;
4279 else if (*s == '\\')
4280 ++num_backslashes;
4281 else if (IS_HIGHBIT_SET(*s))
4282 {
4283 int charlen;
4284
4285 /* Slow path for possible multibyte characters */
4287 s, remaining);
4288
4289 if (charlen > remaining)
4290 {
4291 /* Multibyte character overruns allowable length. */
4292 libpq_append_conn_error(conn, "incomplete multibyte character");
4293 return NULL;
4294 }
4295
4296 /*
4297 * If we haven't already, check that multibyte characters are
4298 * valid. It's important to verify that as invalid multi-byte
4299 * characters could e.g. be used to "skip" over quote characters,
4300 * e.g. when parsing character-by-character.
4301 *
4302 * We check validity once, for the whole remainder of the string,
4303 * when we first encounter any multi-byte character. Some
4304 * encodings have optimized implementations for longer strings.
4305 */
4306 if (!validated_mb)
4307 {
4309 != remaining)
4310 {
4311 libpq_append_conn_error(conn, "invalid multibyte character");
4312 return NULL;
4313 }
4314 validated_mb = true;
4315 }
4316
4317 /* Adjust s, bearing in mind that for loop will increment it. */
4318 s += charlen - 1;
4319 remaining -= charlen - 1;
4320 }
4321 }
4322
4323 /*
4324 * Allocate output buffer. Protect against overflow, in case the caller
4325 * has allocated a large fraction of the available size_t.
4326 */
4327 if (add_size_overflow(input_len, num_quotes, &result_size) ||
4328 add_size_overflow(result_size, 3, &result_size)) /* two quotes plus a NUL */
4329 goto overflow;
4330
4331 if (!as_ident && num_backslashes > 0)
4332 {
4333 if (add_size_overflow(result_size, num_backslashes, &result_size) ||
4334 add_size_overflow(result_size, 2, &result_size)) /* for " E" prefix */
4335 goto overflow;
4336 }
4337
4338 result = rp = (char *) malloc(result_size);
4339 if (rp == NULL)
4340 {
4341 libpq_append_conn_error(conn, "out of memory");
4342 return NULL;
4343 }
4344
4345 /*
4346 * If we are escaping a literal that contains backslashes, we use the
4347 * escape string syntax so that the result is correct under either value
4348 * of standard_conforming_strings. We also emit a leading space in this
4349 * case, to guard against the possibility that the result might be
4350 * interpolated immediately following an identifier.
4351 */
4352 if (!as_ident && num_backslashes > 0)
4353 {
4354 *rp++ = ' ';
4355 *rp++ = 'E';
4356 }
4357
4358 /* Opening quote. */
4359 *rp++ = quote_char;
4360
4361 /*
4362 * Use fast path if possible.
4363 *
4364 * We've already verified that the input string is well-formed in the
4365 * current encoding. If it contains no quotes and, in the case of
4366 * literal-escaping, no backslashes, then we can just copy it directly to
4367 * the output buffer, adding the necessary quotes.
4368 *
4369 * If not, we must rescan the input and process each character
4370 * individually.
4371 */
4372 if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
4373 {
4374 memcpy(rp, str, input_len);
4375 rp += input_len;
4376 }
4377 else
4378 {
4379 s = str;
4380 for (size_t remaining = input_len; remaining > 0; remaining--, s++)
4381 {
4382 if (*s == quote_char || (!as_ident && *s == '\\'))
4383 {
4384 *rp++ = *s;
4385 *rp++ = *s;
4386 }
4387 else if (!IS_HIGHBIT_SET(*s))
4388 *rp++ = *s;
4389 else
4390 {
4392
4393 while (1)
4394 {
4395 *rp++ = *s;
4396 if (--i == 0)
4397 break;
4398 remaining--;
4399 ++s; /* for loop will provide the final increment */
4400 }
4401 }
4402 }
4403 }
4404
4405 /* Closing quote and terminating NUL. */
4406 *rp++ = quote_char;
4407 *rp = '\0';
4408
4409 return result;
4410
4411overflow:
4413 "escaped string size exceeds the maximum allowed (%zu)",
4414 SIZE_MAX);
4415 return NULL;
4416}
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1155
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:556
int pg_encoding_mblen_or_incomplete(int encoding, const char *mbstr, size_t remaining)
Definition: wchar.c:2147
int pg_encoding_verifymbstr(int encoding, const char *mbstr, int len)
Definition: wchar.c:2202
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:2135

References add_size_overflow(), 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_mblen_or_incomplete(), 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 4215 of file fe-exec.c.

4216{
4217 return PQescapeStringInternal(NULL, to, from, length, NULL,
4220}
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:4087
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 4193 of file fe-exec.c.

4196{
4197 if (!conn)
4198 {
4199 /* force empty-string result */
4200 *to = '\0';
4201 if (error)
4202 *error = 1;
4203 return 0;
4204 }
4205
4206 if (conn->cmd_queue_head == NULL)
4208
4209 return PQescapeStringInternal(conn, to, from, length, error,
4211 conn->std_strings);
4212}
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 4087 of file fe-exec.c.

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

References conn, encoding, error(), i, IS_HIGHBIT_SET, libpq_append_conn_error(), pg_encoding_mblen_or_incomplete(), 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 2278 of file fe-exec.c.

2279{
2280 if (!PQexecStart(conn))
2281 return NULL;
2282 if (!PQsendQuery(conn, query))
2283 return NULL;
2284 return PQexecFinish(conn);
2285}
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1432

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

Referenced by _doSetSessionAuth(), _printTableAccessMethodNoStorage(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), check_and_drop_existing_subscriptions(), check_and_drop_publications(), 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_subscription(), 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(), get_publisher_databases(), 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 2426 of file fe-exec.c.

2427{
2428 PGresult *result;
2429 PGresult *lastResult;
2430
2431 /*
2432 * For backwards compatibility, return the last result if there are more
2433 * than one. (We used to have logic here to concatenate successive error
2434 * messages, but now that happens automatically, since conn->errorMessage
2435 * will continue to accumulate errors throughout this loop.)
2436 *
2437 * We have to stop if we see copy in/out/both, however. We will resume
2438 * parsing after application performs the data transfer.
2439 *
2440 * Also stop if the connection is lost (else we'll loop infinitely).
2441 */
2442 lastResult = NULL;
2443 while ((result = PQgetResult(conn)) != NULL)
2444 {
2445 PQclear(lastResult);
2446 lastResult = result;
2447 if (result->resultStatus == PGRES_COPY_IN ||
2448 result->resultStatus == PGRES_COPY_OUT ||
2449 result->resultStatus == PGRES_COPY_BOTH ||
2451 break;
2452 }
2453
2454 return lastResult;
2455}
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2078
@ CONNECTION_BAD
Definition: libpq-fe.h:85
@ PGRES_COPY_IN
Definition: libpq-fe.h:132
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:137
@ PGRES_COPY_OUT
Definition: libpq-fe.h:131

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

2300{
2301 if (!PQexecStart(conn))
2302 return NULL;
2303 if (!PQsendQueryParams(conn, command,
2304 nParams, paramTypes, paramValues, paramLengths,
2305 paramFormats, resultFormat))
2306 return NULL;
2307 return PQexecFinish(conn);
2308}
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:1508

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

2346{
2347 if (!PQexecStart(conn))
2348 return NULL;
2349 if (!PQsendQueryPrepared(conn, stmtName,
2350 nParams, paramValues, paramLengths,
2351 paramFormats, resultFormat))
2352 return NULL;
2353 return PQexecFinish(conn);
2354}
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:1649

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

Referenced by ecpg_execute(), and try_complete_step().

◆ PQexecStart()

static bool PQexecStart ( PGconn conn)
static

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

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

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

3090{
3091 if (!conn)
3092 return 0;
3093
3097 conn->cmd_queue_head == NULL)
3098 return 1;
3099
3100 switch (conn->asyncStatus)
3101 {
3102 case PGASYNC_READY:
3103 case PGASYNC_READY_MORE:
3104 /* there are some uncollected results */
3105 libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
3106 return 0;
3107
3108 case PGASYNC_BUSY:
3109 libpq_append_conn_error(conn, "cannot exit pipeline mode while busy");
3110 return 0;
3111
3112 case PGASYNC_IDLE:
3114 /* OK */
3115 break;
3116
3117 case PGASYNC_COPY_IN:
3118 case PGASYNC_COPY_OUT:
3119 case PGASYNC_COPY_BOTH:
3120 libpq_append_conn_error(conn, "cannot exit pipeline mode while in COPY");
3121 }
3122
3123 /* still work to process */
3124 if (conn->cmd_queue_head != NULL)
3125 {
3126 libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
3127 return 0;
3128 }
3129
3132
3133 /* Flush any pending data in out buffer */
3134 if (pqFlush(conn) < 0)
3135 return 0; /* error message is setup already */
3136 return 1;
3137}
@ PGASYNC_COPY_OUT
Definition: libpq-int.h:223
@ PGASYNC_READY_MORE
Definition: libpq-int.h:219
@ PGASYNC_READY
Definition: libpq-int.h:217
@ PGASYNC_COPY_BOTH
Definition: libpq-int.h:224
@ PGASYNC_COPY_IN
Definition: libpq-int.h:222

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

3725{
3726 if (!check_field_number(res, field_num))
3727 return 0;
3728 if (res->attDescs)
3729 return res->attDescs[field_num].format;
3730 else
3731 return 0;
3732}
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3526

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

3758{
3759 if (!check_field_number(res, field_num))
3760 return 0;
3761 if (res->attDescs)
3762 return res->attDescs[field_num].atttypmod;
3763 else
3764 return 0;
3765}
int atttypmod
Definition: libpq-fe.h:313

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

3003{
3004 *result_len = 0;
3005
3006 if (!conn)
3007 return NULL;
3008
3009 /*
3010 * Since this is the beginning of a query cycle, reset the error state.
3011 * However, in pipeline mode with something already queued, the error
3012 * buffer belongs to that command and we shouldn't clear it.
3013 */
3014 if (conn->cmd_queue_head == NULL)
3016
3018 {
3019 libpq_append_conn_error(conn, "%s not allowed in pipeline mode", "PQfn");
3020 return NULL;
3021 }
3022
3025 {
3026 libpq_append_conn_error(conn, "connection in wrong state");
3027 return NULL;
3028 }
3029
3030 return pqFunctionCall3(conn, fnid,
3031 result_buf, result_len,
3032 result_is_int,
3033 args, nargs);
3034}
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:499

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 
)

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

3584{
3585 if (!check_field_number(res, field_num))
3586 return NULL;
3587 if (res->attDescs)
3588 return res->attDescs[field_num].name;
3589 else
3590 return NULL;
3591}
char * name
Definition: libpq-fe.h:307

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

◆ PQfnumber()

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

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

3606{
3607 char *field_case;
3608 bool in_quotes;
3609 bool all_lower = true;
3610 const char *iptr;
3611 char *optr;
3612 int i;
3613
3614 if (!res)
3615 return -1;
3616
3617 /*
3618 * Note: it is correct to reject a zero-length input string; the proper
3619 * input to match a zero-length field name would be "".
3620 */
3621 if (field_name == NULL ||
3622 field_name[0] == '\0' ||
3623 res->attDescs == NULL)
3624 return -1;
3625
3626 /*
3627 * Check if we can avoid the strdup() and related work because the
3628 * passed-in string wouldn't be changed before we do the check anyway.
3629 */
3630 for (iptr = field_name; *iptr; iptr++)
3631 {
3632 char c = *iptr;
3633
3634 if (c == '"' || c != pg_tolower((unsigned char) c))
3635 {
3636 all_lower = false;
3637 break;
3638 }
3639 }
3640
3641 if (all_lower)
3642 for (i = 0; i < res->numAttributes; i++)
3643 if (strcmp(field_name, res->attDescs[i].name) == 0)
3644 return i;
3645
3646 /* Fall through to the normal check if that didn't work out. */
3647
3648 /*
3649 * Note: this code will not reject partially quoted strings, eg
3650 * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
3651 * condition.
3652 */
3653 field_case = strdup(field_name);
3654 if (field_case == NULL)
3655 return -1; /* grotty */
3656
3657 in_quotes = false;
3658 optr = field_case;
3659 for (iptr = field_case; *iptr; iptr++)
3660 {
3661 char c = *iptr;
3662
3663 if (in_quotes)
3664 {
3665 if (c == '"')
3666 {
3667 if (iptr[1] == '"')
3668 {
3669 /* doubled quotes become a single quote */
3670 *optr++ = '"';
3671 iptr++;
3672 }
3673 else
3674 in_quotes = false;
3675 }
3676 else
3677 *optr++ = c;
3678 }
3679 else if (c == '"')
3680 in_quotes = true;
3681 else
3682 {
3683 c = pg_tolower((unsigned char) c);
3684 *optr++ = c;
3685 }
3686 }
3687 *optr = '\0';
3688
3689 for (i = 0; i < res->numAttributes; i++)
3690 {
3691 if (strcmp(field_case, res->attDescs[i].name) == 0)
3692 {
3693 free(field_case);
3694 return i;
3695 }
3696 }
3697 free(field_case);
3698 return -1;
3699}
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(), check_new_cluster_replication_slots(), collectComments(), collectSecLabels(), describeOneTableDetails(), dropRoles(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpDatabase(), dumpDomain(), dumpEnumType(), dumpFunc(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRelationStats_dumper(), dumpRoleMembership(), dumpRoles(), dumpTableSchema(), dumpTSConfig(), dumpUserMappings(), get_db_infos(), get_subscription_info(), 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(), getSubscriptionRelations(), getSubscriptions(), 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_inconsistent_notnull(), process_isn_and_int8_passing_mismatch(), process_old_cluster_logical_slot_infos(), process_old_sub_state_check(), process_rel_infos(), process_unicode_update(), 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 4065 of file fe-exec.c.

4066{
4067 PQfreemem(notify);
4068}
void PQfreemem(void *ptr)
Definition: fe-exec.c:4048

References PQfreemem().

◆ PQfsize()

int PQfsize ( const PGresult res,
int  field_num 
)

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

3747{
3748 if (!check_field_number(res, field_num))
3749 return 0;
3750 if (res->attDescs)
3751 return res->attDescs[field_num].typlen;
3752 else
3753 return 0;
3754}

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

3703{
3704 if (!check_field_number(res, field_num))
3705 return InvalidOid;
3706 if (res->attDescs)
3707 return res->attDescs[field_num].tableid;
3708 else
3709 return InvalidOid;
3710}
#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 3713 of file fe-exec.c.

3714{
3715 if (!check_field_number(res, field_num))
3716 return 0;
3717 if (res->attDescs)
3718 return res->attDescs[field_num].columnid;
3719 else
3720 return 0;
3721}
int columnid
Definition: libpq-fe.h:309

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

2833{
2834 *buffer = NULL; /* for all failure cases */
2835 if (!conn)
2836 return -2;
2839 {
2840 libpq_append_conn_error(conn, "no COPY in progress");
2841 return -2;
2842 }
2843 return pqGetCopyData3(conn, buffer, async);
2844}
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 3917 of file fe-exec.c.

3918{
3919 if (!check_tuple_field_number(res, tup_num, field_num))
3920 return 1; /* pretend it is null */
3921 if (res->tuples[tup_num][field_num].len == NULL_LEN)
3922 return 1;
3923 else
3924 return 0;
3925}
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3541
#define NULL_LEN
Definition: libpq-int.h:130

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

◆ PQgetlength()

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

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

3904{
3905 if (!check_tuple_field_number(res, tup_num, field_num))
3906 return 0;
3907 if (res->tuples[tup_num][field_num].len != NULL_LEN)
3908 return res->tuples[tup_num][field_num].len;
3909 else
3910 return 0;
3911}

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

◆ PQgetline()

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

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

2871{
2872 if (!buffer || length <= 0)
2873 return EOF;
2874 *buffer = '\0';
2875 /* length must be at least 3 to hold the \. terminator! */
2876 if (length < 3)
2877 return EOF;
2878
2879 if (!conn)
2880 return EOF;
2881
2882 return pqGetline3(conn, buffer, length);
2883}
int pqGetline3(PGconn *conn, char *s, int maxlen)

References conn, and pqGetline3().

◆ PQgetlineAsync()

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

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

2918{
2919 if (!conn)
2920 return -1;
2921
2922 return pqGetlineAsync3(conn, buffer, bufsize);
2923}
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 2078 of file fe-exec.c.

2079{
2080 PGresult *res;
2081
2082 if (!conn)
2083 return NULL;
2084
2085 /* Parse any available data, if our state permits. */
2087
2088 /* If not ready to return something, block until we are. */
2089 while (conn->asyncStatus == PGASYNC_BUSY)
2090 {
2091 int flushResult;
2092
2093 /*
2094 * If data remains unsent, send it. Else we might be waiting for the
2095 * result of a command the backend hasn't even got yet.
2096 */
2097 while ((flushResult = pqFlush(conn)) > 0)
2098 {
2099 if (pqWait(false, true, conn))
2100 {
2101 flushResult = -1;
2102 break;
2103 }
2104 }
2105
2106 /*
2107 * Wait for some more data, and load it. (Note: if the connection has
2108 * been lost, pqWait should return immediately because the socket
2109 * should be read-ready, either with the last server data or with an
2110 * EOF indication. We expect therefore that this won't result in any
2111 * undue delay in reporting a previous write failure.)
2112 */
2113 if (flushResult ||
2114 pqWait(true, false, conn) ||
2115 pqReadData(conn) < 0)
2116 {
2117 /* Report the error saved by pqWait or pqReadData */
2120 return pqPrepareAsyncResult(conn);
2121 }
2122
2123 /* Parse it. */
2125
2126 /*
2127 * If we had a write error, but nothing above obtained a query result
2128 * or detected a read error, report the write error.
2129 */
2131 {
2134 return pqPrepareAsyncResult(conn);
2135 }
2136 }
2137
2138 /* Return the appropriate thing. */
2139 switch (conn->asyncStatus)
2140 {
2141 case PGASYNC_IDLE:
2142 res = NULL; /* query is complete */
2143 break;
2146
2147 /*
2148 * We're about to return the NULL that terminates the round of
2149 * results from the current query; prepare to send the results of
2150 * the next query, if any, when we're called next. If there's no
2151 * next element in the command queue, this gets us in IDLE state.
2152 */
2154 res = NULL; /* query is complete */
2155 break;
2156
2157 case PGASYNC_READY:
2159
2160 /*
2161 * Normally pqPrepareAsyncResult will have left conn->result
2162 * empty. Otherwise, "res" must be a not-full PGRES_TUPLES_CHUNK
2163 * result, which we want to return to the caller while staying in
2164 * PGASYNC_READY state. Then the next call here will return the
2165 * empty PGRES_TUPLES_OK result that was restored from
2166 * saved_result, after which we can proceed.
2167 */
2168 if (conn->result)
2169 {
2171 break;
2172 }
2173
2174 /* Advance the queue as appropriate */
2177
2179 {
2180 /*
2181 * We're about to send the results of the current query. Set
2182 * us idle now, and ...
2183 */
2185
2186 /*
2187 * ... in cases when we're sending a pipeline-sync result,
2188 * move queue processing forwards immediately, so that next
2189 * time we're called, we're prepared to return the next result
2190 * received from the server. In all other cases, leave the
2191 * queue state change for next time, so that a terminating
2192 * NULL result is sent.
2193 *
2194 * (In other words: we don't return a NULL after a pipeline
2195 * sync.)
2196 */
2199 }
2200 else
2201 {
2202 /* Set the state back to BUSY, allowing parsing to proceed. */
2204 }
2205 break;
2206 case PGASYNC_READY_MORE:
2208 /* Set the state back to BUSY, allowing parsing to proceed. */
2210 break;
2211 case PGASYNC_COPY_IN:
2213 break;
2214 case PGASYNC_COPY_OUT:
2216 break;
2217 case PGASYNC_COPY_BOTH:
2219 break;
2220 default:
2221 libpq_append_conn_error(conn, "unexpected asyncStatus: %d", (int) conn->asyncStatus);
2223 conn->asyncStatus = PGASYNC_IDLE; /* try to restore valid state */
2225 break;
2226 }
2227
2228 /* Time to fire PGEVT_RESULTCREATE events, if there are any */
2229 if (res && res->nEvents > 0)
2230 (void) PQfireResultCreateEvents(conn, res);
2231
2232 return res;
2233}
static void pqSaveWriteError(PGconn *conn)
Definition: fe-exec.c:825
void pqCommandQueueAdvance(PGconn *conn, bool isReadyForQuery, bool gotSync)
Definition: fe-exec.c:3158
static PGresult * getCopyResult(PGconn *conn, ExecStatusType copytype)
Definition: fe-exec.c:2240
static void parseInput(PGconn *conn)
Definition: fe-exec.c:2036
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:1019
int PQfireResultCreateEvents(PGconn *conn, PGresult *res)
Definition: libpq-events.c:185
@ PGRES_TUPLES_CHUNK
Definition: libpq-fe.h:142
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:139
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 PQexecFinish(), and PQexecStart().

◆ PQgetvalue()

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

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

3893{
3894 if (!check_tuple_field_number(res, tup_num, field_num))
3895 return NULL;
3896 return res->tuples[tup_num][field_num].value;
3897}

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

◆ pqInternalNotice()

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

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

944{
945 char msgBuf[1024];
946 va_list args;
947 PGresult *res;
948
949 if (hooks->noticeRec == NULL)
950 return; /* nobody home to receive notice? */
951
952 /* Format the message */
953 va_start(args, fmt);
954 vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
955 va_end(args);
956 msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
957
958 /* Make a PGresult to pass to the notice receiver */
960 if (!res)
961 return;
962 res->noticeHooks = *hooks;
963
964 /*
965 * Set up fields of notice.
966 */
970 /* XXX should provide a SQLSTATE too? */
971
972 /*
973 * Result text is always just the primary message + newline. If we can't
974 * allocate it, substitute "out of memory", as in pqSetResultError.
975 */
976 res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, false);
977 if (res->errMsg)
978 sprintf(res->errMsg, "%s\n", msgBuf);
979 else
980 res->errMsg = libpq_gettext("out of memory\n");
981
982 /*
983 * Pass to receiver, then free it.
984 */
985 res->noticeHooks.noticeRec(res->noticeHooks.noticeRecArg, res);
986 PQclear(res);
987}
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:1065
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:135
#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:149

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

2048{
2049 if (!conn)
2050 return false;
2051
2052 /* Parse any available data, if our state permits. */
2054
2055 /*
2056 * PQgetResult will return immediately in all states except BUSY. Also,
2057 * if we've detected read EOF and dropped the connection, we can expect
2058 * that PQgetResult will fail immediately. Note that we do *not* check
2059 * conn->write_failed here --- once that's become set, we know we have
2060 * trouble, but we need to keep trying to read until we have a complete
2061 * server message or detect read EOF.
2062 */
2064}

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

Referenced by advanceConnectionState(), consume_query_cancel_impl(), dblink_is_busy(), 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 3999 of file fe-exec.c.

4000{
4001 if (!conn || conn->status == CONNECTION_BAD)
4002 return false;
4003 return pqIsnonblocking(conn);
4004}

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

4009{
4010 return true;
4011}

◆ 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:697
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:125
@ PGRES_SINGLE_TUPLE
Definition: libpq-fe.h:138
@ PGRES_EMPTY_QUERY
Definition: libpq-fe.h:124
struct pg_result PGresult
Definition: libpq-fe.h:214
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
void * noticeProcArg
Definition: libpq-int.h:152
PQnoticeProcessor noticeProc
Definition: libpq-int.h:151
void * noticeRecArg
Definition: libpq-int.h:150
PQExpBufferData errorMessage
Definition: libpq-int.h:683
int nEvents
Definition: libpq-int.h:458
PGNoticeHooks noticeHooks
Definition: libpq-int.h:454
PGEvent * events
Definition: libpq-int.h:457
int curOffset
Definition: libpq-int.h:206
char null_field[1]
Definition: libpq-int.h:198
char * errMsg
Definition: libpq-int.h:193
int spaceLeft
Definition: libpq-int.h:207
char * errQuery
Definition: libpq-int.h:195

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()

int PQnfields ( const PGresult res)

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

3506{
3507 if (!res)
3508 return 0;
3509 return res->numAttributes;
3510}

References pg_result::numAttributes.

◆ PQnotifies()

PGnotify * PQnotifies ( PGconn conn)

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

2684{
2685 PGnotify *event;
2686
2687 if (!conn)
2688 return NULL;
2689
2690 /* Parse any available data to see if we can extract NOTIFY messages. */
2692
2693 event = conn->notifyHead;
2694 if (event)
2695 {
2696 conn->notifyHead = event->next;
2697 if (!conn->notifyHead)
2698 conn->notifyTail = NULL;
2699 event->next = NULL; /* don't let app see the internal state */
2700 }
2701 return event;
2702}
struct pgNotify * next
Definition: libpq-fe.h:234
PGnotify * notifyHead
Definition: libpq-int.h:476
PGnotify * notifyTail
Definition: libpq-int.h:477

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

3932{
3933 if (!res)
3934 return 0;
3935 return res->numParameters;
3936}

References pg_result::numParameters.

◆ PQntuples()

int PQntuples ( const PGresult res)

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

3498{
3499 if (!res)
3500 return 0;
3501 return res->ntups;
3502}

References pg_result::ntups.

◆ PQoidStatus()

char * PQoidStatus ( const PGresult res)

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

3782{
3783 /*
3784 * This must be enough to hold the result. Don't laugh, this is better
3785 * than what this function used to do.
3786 */
3787 static char buf[24];
3788
3789 size_t len;
3790
3791 if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
3792 return "";
3793
3794 len = strspn(res->cmdStatus + 7, "0123456789");
3795 if (len > sizeof(buf) - 1)
3796 len = sizeof(buf) - 1;
3797 memcpy(buf, res->cmdStatus + 7, len);
3798 buf[len] = '\0';
3799
3800 return buf;
3801}
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 3809 of file fe-exec.c.

3810{
3811 char *endptr = NULL;
3812 unsigned long result;
3813
3814 if (!res ||
3815 strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
3816 res->cmdStatus[7] < '0' ||
3817 res->cmdStatus[7] > '9')
3818 return InvalidOid;
3819
3820 result = strtoul(res->cmdStatus + 7, &endptr, 10);
3821
3822 if (!endptr || (*endptr != ' ' && *endptr != '\0'))
3823 return InvalidOid;
3824 else
3825 return (Oid) result;
3826}
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 3942 of file fe-exec.c.

3943{
3944 if (!check_param_number(res, param_num))
3945 return InvalidOid;
3946 if (res->paramDescs)
3947 return res->paramDescs[param_num].typid;
3948 else
3949 return InvalidOid;
3950}
static int check_param_number(const PGresult *res, int param_num)
Definition: fe-exec.c:3564

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

◆ pqPipelineFlush()

static int pqPipelineFlush ( PGconn conn)
static

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

4033{
4036 return pqFlush(conn);
4037 return 0;
4038}
#define OUTBUFFER_THRESHOLD
Definition: libpq-int.h:944
int outCount
Definition: libpq-int.h:585

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

3197{
3198 switch (conn->asyncStatus)
3199 {
3200 case PGASYNC_COPY_IN:
3201 case PGASYNC_COPY_OUT:
3202 case PGASYNC_COPY_BOTH:
3203 case PGASYNC_READY:
3204 case PGASYNC_READY_MORE:
3205 case PGASYNC_BUSY:
3206 /* client still has to process current query or results */
3207 return;
3208
3209 case PGASYNC_IDLE:
3210
3211 /*
3212 * If we're in IDLE mode and there's some command in the queue,
3213 * get us into PIPELINE_IDLE mode and process normally. Otherwise
3214 * there's nothing for us to do.
3215 */
3216 if (conn->cmd_queue_head != NULL)
3217 {
3219 break;
3220 }
3221 return;
3222
3225 /* next query please */
3226 break;
3227 }
3228
3229 /*
3230 * Reset partial-result mode. (Client has to set it up for each query, if
3231 * desired.)
3232 */
3233 conn->partialResMode = false;
3234 conn->singleRowMode = false;
3235 conn->maxChunkSize = 0;
3236
3237 /*
3238 * If there are no further commands to process in the queue, get us in
3239 * "real idle" mode now.
3240 */
3241 if (conn->cmd_queue_head == NULL)
3242 {
3244 return;
3245 }
3246
3247 /*
3248 * Reset the error state. This and the next couple of steps correspond to
3249 * what PQsendQueryStart didn't do for this query.
3250 */
3252
3253 /* Initialize async result-accumulation state */
3255
3258 {
3259 /*
3260 * In an aborted pipeline we don't get anything from the server for
3261 * each result; we're just discarding commands from the queue until we
3262 * get to the next sync from the server.
3263 *
3264 * The PGRES_PIPELINE_ABORTED results tell the client that its queries
3265 * got aborted.
3266 */
3268 if (!conn->result)
3269 {
3270 libpq_append_conn_error(conn, "out of memory");
3272 return;
3273 }
3275 }
3276 else
3277 {
3278 /* allow parsing to continue */
3280 }
3281}
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:784
@ PGRES_PIPELINE_ABORTED
Definition: libpq-fe.h:140
int maxChunkSize
Definition: libpq-int.h:472
bool singleRowMode
Definition: libpq-int.h:471
bool partialResMode
Definition: libpq-int.h:470

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

3311{
3312 PGcmdQueueEntry *entry;
3313
3314 if (!conn)
3315 return 0;
3316
3318 {
3319 libpq_append_conn_error(conn, "cannot send pipeline when not in pipeline mode");
3320 return 0;
3321 }
3322
3323 switch (conn->asyncStatus)
3324 {
3325 case PGASYNC_COPY_IN:
3326 case PGASYNC_COPY_OUT:
3327 case PGASYNC_COPY_BOTH:
3328 /* should be unreachable */
3330 "internal error: cannot send pipeline while in COPY\n");
3331 return 0;
3332 case PGASYNC_READY:
3333 case PGASYNC_READY_MORE:
3334 case PGASYNC_BUSY:
3335 case PGASYNC_IDLE:
3337 /* OK to send sync */
3338 break;
3339 }
3340
3341 entry = pqAllocCmdQueueEntry(conn);
3342 if (entry == NULL)
3343 return 0; /* error msg already set */
3344
3345 entry->queryclass = PGQUERY_SYNC;
3346 entry->query = NULL;
3347
3348 /* construct the Sync message */
3349 if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
3350 pqPutMsgEnd(conn) < 0)
3351 goto sendFailed;
3352
3353 /*
3354 * Give the data a push. In nonblock mode, don't complain if we're unable
3355 * to send it all; PQgetResult() will do any additional flushing needed.
3356 * If immediate_flush is disabled, the data is pushed if we are past the
3357 * size threshold.
3358 */
3359 if (immediate_flush)
3360 {
3361 if (pqFlush(conn) < 0)
3362 goto sendFailed;
3363 }
3364 else
3365 {
3366 if (pqPipelineFlush(conn) < 0)
3367 goto sendFailed;
3368 }
3369
3370 /* OK, it's launched! */
3372
3373 return 1;
3374
3375sendFailed:
3377 /* error message should be set up already */
3378 return 0;
3379}
static PGcmdQueueEntry * pqAllocCmdQueueEntry(PGconn *conn)
Definition: fe-exec.c:1322
static void pqAppendCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1355
static int pqPipelineFlush(PGconn *conn)
Definition: fe-exec.c:4032
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 2322 of file fe-exec.c.

2325{
2326 if (!PQexecStart(conn))
2327 return NULL;
2328 if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
2329 return NULL;
2330 return PQexecFinish(conn);
2331}
int PQsendPrepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:1552

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

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

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

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

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

2766{
2767 if (!conn)
2768 return -1;
2771 {
2772 libpq_append_conn_error(conn, "no COPY in progress");
2773 return -1;
2774 }
2775
2776 /*
2777 * Send the COPY END indicator. This is simple enough that we don't
2778 * bother delegating it to the fe-protocol files.
2779 */
2780 if (errormsg)
2781 {
2782 /* Send COPY FAIL */
2783 if (pqPutMsgStart(PqMsg_CopyFail, conn) < 0 ||
2784 pqPuts(errormsg, conn) < 0 ||
2785 pqPutMsgEnd(conn) < 0)
2786 return -1;
2787 }
2788 else
2789 {
2790 /* Send COPY DONE */
2791 if (pqPutMsgStart(PqMsg_CopyDone, conn) < 0 ||
2792 pqPutMsgEnd(conn) < 0)
2793 return -1;
2794 }
2795
2796 /*
2797 * If we sent the COPY command in extended-query mode, we must issue a
2798 * Sync as well.
2799 */
2800 if (conn->cmd_queue_head &&
2802 {
2803 if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
2804 pqPutMsgEnd(conn) < 0)
2805 return -1;
2806 }
2807
2808 /* Return to active duty */
2811 else
2813
2814 /* Try to flush data */
2815 if (pqFlush(conn) < 0)
2816 return -1;
2817
2818 return 1;
2819}
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 ProcessWALDataMsg().

◆ PQputline()

int PQputline ( PGconn conn,
const char *  string 
)

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

2935{
2936 return PQputnbytes(conn, string, strlen(string));
2937}
int PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2944

References conn, and PQputnbytes().

Referenced by initPopulateTable().

◆ PQputnbytes()

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

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

2945{
2946 if (PQputCopyData(conn, buffer, nbytes) > 0)
2947 return 0;
2948 else
2949 return EOF;
2950}
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2711

References conn, and PQputCopyData().

Referenced by PQputline().

◆ pqRecycleCmdQueueEntry()

static void pqRecycleCmdQueueEntry ( PGconn conn,
PGcmdQueueEntry entry 
)
static

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

1403{
1404 if (entry == NULL)
1405 return;
1406
1407 /* recyclable entries should not have a follow-on command */
1408 Assert(entry->next == NULL);
1409
1410 if (entry->query)
1411 {
1412 free(entry->query);
1413 entry->query = NULL;
1414 }
1415
1416 entry->next = conn->cmd_queue_recycle;
1417 conn->cmd_queue_recycle = entry;
1418}

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

3436{
3437 if ((unsigned int) status >= lengthof(pgresStatus))
3438 return libpq_gettext("invalid ExecStatusType code");
3439 return pgresStatus[status];
3440}
#define lengthof(array)
Definition: c.h:792
char *const pgresStatus[]
Definition: fe-exec.c:32

References lengthof, libpq_gettext, and pgresStatus.

Referenced by BaseBackup(), confirm_result_status_impl(), consume_null_result_impl(), process_result(), test_pipeline_abort(), test_pipelined_insert(), test_prepared(), 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;
607
608 /* Don't wrap around with overly large requests. */
609 if (nBytes > SIZE_MAX - PGRESULT_BLOCK_OVERHEAD)
610 return NULL;
611
612 alloc_size = nBytes + PGRESULT_BLOCK_OVERHEAD;
613 block = (PGresult_data *) malloc(alloc_size);
614 if (!block)
615 return NULL;
616 res->memorySize += alloc_size;
617 space = block->space + PGRESULT_BLOCK_OVERHEAD;
618 if (res->curBlock)
619 {
620 /*
621 * Tuck special block below the active block, so that we don't
622 * have to waste the free space in the active block.
623 */
624 block->next = res->curBlock->next;
625 res->curBlock->next = block;
626 }
627 else
628 {
629 /* Must set up the new block as the first active block. */
630 block->next = NULL;
631 res->curBlock = block;
632 res->spaceLeft = 0; /* be sure it's marked full */
633 }
634 return space;
635 }
636
637 /* Otherwise, start a new block. */
639 if (!block)
640 return NULL;
642 block->next = res->curBlock;
643 res->curBlock = block;
644 if (isBinary)
645 {
646 /* object needs full alignment */
649 }
650 else
651 {
652 /* we can cram it right after the overhead pointer */
653 res->curOffset = sizeof(PGresult_data);
655 }
656
657 space = block->space + res->curOffset;
658 res->curOffset += nBytes;
659 res->spaceLeft -= nBytes;
660 return space;
661}
#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:98
char space[1]
Definition: libpq-int.h:103

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

3483{
3484 PGMessageField *pfield;
3485
3486 if (!res)
3487 return NULL;
3488 for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
3489 {
3490 if (pfield->code == fieldcode)
3491 return pfield->contents;
3492 }
3493 return NULL;
3494}
struct pgMessageField * next
Definition: libpq-int.h:141
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:143

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

◆ PQresultErrorMessage()

char * PQresultErrorMessage ( const PGresult res)

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

3444{
3445 if (!res || !res->errMsg)
3446 return "";
3447 return res->errMsg;
3448}

References pg_result::errMsg.

◆ PQresultMemorySize()

size_t PQresultMemorySize ( const PGresult res)

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

669{
670 if (!res)
671 return 0;
672 return res->memorySize;
673}

References pg_result::memorySize.

◆ PQresultStatus()

ExecStatusType PQresultStatus ( const PGresult res)

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

3428{
3429 if (!res)
3430 return PGRES_FATAL_ERROR;
3431 return res->resultStatus;
3432}

References PGRES_FATAL_ERROR, and pg_result::resultStatus.

◆ pqResultStrdup()

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

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

681{
682 char *space = (char *) pqResultAlloc(res, strlen(str) + 1, false);
683
684 if (space)
685 strcpy(space, str);
686 return space;
687}

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

3454{
3455 PQExpBufferData workBuf;
3456
3457 /*
3458 * Because the caller is expected to free the result string, we must
3459 * strdup any constant result. We use plain strdup and document that
3460 * callers should expect NULL if out-of-memory.
3461 */
3462 if (!res ||
3465 return strdup(libpq_gettext("PGresult is not an error result\n"));
3466
3467 initPQExpBuffer(&workBuf);
3468
3469 pqBuildErrorMessage3(&workBuf, res, verbosity, show_context);
3470
3471 /* If insufficient memory to format the message, fail cleanly */
3472 if (PQExpBufferDataBroken(workBuf))
3473 {
3474 termPQExpBuffer(&workBuf);
3475 return strdup(libpq_gettext("out of memory\n"));
3476 }
3477
3478 return workBuf.data;
3479}
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 1222 of file fe-exec.c.

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

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

809{
810 /* Drop any pending result ... */
812 /* ... and set flag to remember to make an error result later */
813 conn->error_result = true;
814}

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

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

◆ pqSaveMessageField()

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

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

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

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

Referenced by pqGetErrorNotice3(), and pqInternalNotice().

◆ pqSaveParameterStatus()

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

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

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

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

826{
827 /*
828 * If write_err_msg is null because of previous strdup failure, do what we
829 * can. (It's likely our machinations here will get OOM failures as well,
830 * but might as well try.)
831 */
832 if (conn->write_err_msg)
833 {
835 /* Avoid possibly appending the same message twice */
836 conn->write_err_msg[0] = '\0';
837 }
838 else
839 libpq_append_conn_error(conn, "write to server failed");
840
842}
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 2585 of file fe-exec.c.

2586{
2587 return PQsendTypedCommand(conn, PqMsg_Close, 'P', portal);
2588}

References conn, PqMsg_Close, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQsendClosePrepared()

int PQsendClosePrepared ( PGconn conn,
const char *  stmt 
)

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

2573{
2574 return PQsendTypedCommand(conn, PqMsg_Close, 'S', stmt);
2575}

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

Referenced by ExecQueryAndProcessResults(), and test_prepared().

◆ PQsendDescribePortal()

int PQsendDescribePortal ( PGconn conn,
const char *  portal 
)

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

2521{
2522 return PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal);
2523}

References conn, PqMsg_Describe, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQsendDescribePrepared()

int PQsendDescribePrepared ( PGconn conn,
const char *  stmt 
)

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

2508{
2510}

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

Referenced by test_prepared().

◆ PQsendFlushRequest()

int PQsendFlushRequest ( PGconn conn)

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

3388{
3389 if (!conn)
3390 return 0;
3391
3392 /* Don't try to send if we know there's no live connection. */
3393 if (conn->status != CONNECTION_OK)
3394 {
3395 libpq_append_conn_error(conn, "no connection to the server");
3396 return 0;
3397 }
3398
3399 /* Can't send while already busy, either, unless enqueuing for later */
3400 if (conn->asyncStatus != PGASYNC_IDLE &&
3402 {
3403 libpq_append_conn_error(conn, "another command is already in progress");
3404 return 0;
3405 }
3406
3407 if (pqPutMsgStart(PqMsg_Flush, conn) < 0 ||
3408 pqPutMsgEnd(conn) < 0)
3409 {
3410 return 0;
3411 }
3412
3413 /*
3414 * Give the data a push (in pipeline mode, only if we're past the size
3415 * threshold). In nonblock mode, don't complain if we're unable to send
3416 * it all; PQgetResult() will do any additional flushing needed.
3417 */
3418 if (pqPipelineFlush(conn) < 0)
3419 return 0;
3420
3421 return 1;
3422}
#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 3298 of file fe-exec.c.

3299{
3300 return pqPipelineSyncInternal(conn, false);
3301}

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

1555{
1556 PGcmdQueueEntry *entry = NULL;
1557
1558 if (!PQsendQueryStart(conn, true))
1559 return 0;
1560
1561 /* check the arguments */
1562 if (!stmtName)
1563 {
1564 libpq_append_conn_error(conn, "statement name is a null pointer");
1565 return 0;
1566 }
1567 if (!query)
1568 {
1569 libpq_append_conn_error(conn, "command string is a null pointer");
1570 return 0;
1571 }
1572 if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1573 {
1574 libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1576 return 0;
1577 }
1578
1579 entry = pqAllocCmdQueueEntry(conn);
1580 if (entry == NULL)
1581 return 0; /* error msg already set */
1582
1583 /* construct the Parse message */
1584 if (pqPutMsgStart(PqMsg_Parse, conn) < 0 ||
1585 pqPuts(stmtName, conn) < 0 ||
1586 pqPuts(query, conn) < 0)
1587 goto sendFailed;
1588
1589 if (nParams > 0 && paramTypes)
1590 {
1591 int i;
1592
1593 if (pqPutInt(nParams, 2, conn) < 0)
1594 goto sendFailed;
1595 for (i = 0; i < nParams; i++)
1596 {
1597 if (pqPutInt(paramTypes[i], 4, conn) < 0)
1598 goto sendFailed;
1599 }
1600 }
1601 else
1602 {
1603 if (pqPutInt(0, 2, conn) < 0)
1604 goto sendFailed;
1605 }
1606 if (pqPutMsgEnd(conn) < 0)
1607 goto sendFailed;
1608
1609 /* Add a Sync, unless in pipeline mode. */
1611 {
1612 if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
1613 pqPutMsgEnd(conn) < 0)
1614 goto sendFailed;
1615 }
1616
1617 /* remember we are doing just a Parse */
1618 entry->queryclass = PGQUERY_PREPARE;
1619
1620 /* and remember the query text too, if possible */
1621 /* if insufficient memory, query just winds up NULL */
1622 entry->query = strdup(query);
1623
1624 /*
1625 * Give the data a push (in pipeline mode, only if we're past the size
1626 * threshold). In nonblock mode, don't complain if we're unable to send
1627 * it all; PQgetResult() will do any additional flushing needed.
1628 */
1629 if (pqPipelineFlush(conn) < 0)
1630 goto sendFailed;
1631
1632 /* OK, it's launched! */
1634
1635 return 1;
1636
1637sendFailed:
1639 /* error message should be set up already */
1640 return 0;
1641}
static bool PQsendQueryStart(PGconn *conn, bool newQuery)
Definition: fe-exec.c:1689
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:322
#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 1438 of file fe-exec.c.

1439{
1440 return PQsendQueryInternal(conn, query, false);
1441}

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

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

1445{
1446 PGcmdQueueEntry *entry = NULL;
1447
1448 if (!PQsendQueryStart(conn, newQuery))
1449 return 0;
1450
1451 /* check the argument */
1452 if (!query)
1453 {
1454 libpq_append_conn_error(conn, "command string is a null pointer");
1455 return 0;
1456 }
1457
1459 {
1460 libpq_append_conn_error(conn, "%s not allowed in pipeline mode",
1461 "PQsendQuery");
1462 return 0;
1463 }
1464
1465 entry = pqAllocCmdQueueEntry(conn);
1466 if (entry == NULL)
1467 return 0; /* error msg already set */
1468
1469 /* Send the query message(s) */
1470 /* construct the outgoing Query message */
1471 if (pqPutMsgStart(PqMsg_Query, conn) < 0 ||
1472 pqPuts(query, conn) < 0 ||
1473 pqPutMsgEnd(conn) < 0)
1474 {
1475 /* error message should be set up already */
1477 return 0;
1478 }
1479
1480 /* remember we are using simple query protocol */
1481 entry->queryclass = PGQUERY_SIMPLE;
1482 /* and remember the query text too, if possible */
1483 entry->query = strdup(query);
1484
1485 /*
1486 * Give the data a push. In nonblock mode, don't complain if we're unable
1487 * to send it all; PQgetResult() will do any additional flushing needed.
1488 */
1489 if (pqFlush(conn) < 0)
1490 goto sendFailed;
1491
1492 /* OK, it's launched! */
1494
1495 return 1;
1496
1497sendFailed:
1499 /* error message should be set up already */
1500 return 0;
1501}
#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 1508 of file fe-exec.c.

1516{
1517 if (!PQsendQueryStart(conn, true))
1518 return 0;
1519
1520 /* check the arguments */
1521 if (!command)
1522 {
1523 libpq_append_conn_error(conn, "command string is a null pointer");
1524 return 0;
1525 }
1526 if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1527 {
1528 libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1530 return 0;
1531 }
1532
1533 return PQsendQueryGuts(conn,
1534 command,
1535 "", /* use unnamed statement */
1536 nParams,
1537 paramTypes,
1538 paramValues,
1539 paramLengths,
1540 paramFormats,
1541 resultFormat);
1542}
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:1773

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

1656{
1657 if (!PQsendQueryStart(conn, true))
1658 return 0;
1659
1660 /* check the arguments */
1661 if (!stmtName)
1662 {
1663 libpq_append_conn_error(conn, "statement name is a null pointer");
1664 return 0;
1665 }
1666 if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1667 {
1668 libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1670 return 0;
1671 }
1672
1673 return PQsendQueryGuts(conn,
1674 NULL, /* no command to parse */
1675 stmtName,
1676 nParams,
1677 NULL, /* no param types */
1678 paramValues,
1679 paramLengths,
1680 paramFormats,
1681 resultFormat);
1682}

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

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

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

2606{
2607 PGcmdQueueEntry *entry = NULL;
2608
2609 /* Treat null target as empty string */
2610 if (!target)
2611 target = "";
2612
2613 if (!PQsendQueryStart(conn, true))
2614 return 0;
2615
2616 entry = pqAllocCmdQueueEntry(conn);
2617 if (entry == NULL)
2618 return 0; /* error msg already set */
2619
2620 /* construct the Close message */
2621 if (pqPutMsgStart(command, conn) < 0 ||
2622 pqPutc(type, conn) < 0 ||
2623 pqPuts(target, conn) < 0 ||
2624 pqPutMsgEnd(conn) < 0)
2625 goto sendFailed;
2626
2627 /* construct the Sync message */
2629 {
2630 if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
2631 pqPutMsgEnd(conn) < 0)
2632 goto sendFailed;
2633 }
2634
2635 /* remember if we are doing a Close or a Describe */
2636 if (command == PqMsg_Close)
2637 {
2638 entry->queryclass = PGQUERY_CLOSE;
2639 }
2640 else if (command == PqMsg_Describe)
2641 {
2643 }
2644 else
2645 {
2646 libpq_append_conn_error(conn, "unrecognized message type \"%c\"", command);
2647 goto sendFailed;
2648 }
2649
2650 /*
2651 * Give the data a push (in pipeline mode, only if we're past the size
2652 * threshold). In nonblock mode, don't complain if we're unable to send
2653 * it all; PQgetResult() will do any additional flushing needed.
2654 */
2655 if (pqPipelineFlush(conn) < 0)
2656 goto sendFailed;
2657
2658 /* OK, it's launched! */
2660
2661 return 1;
2662
2663sendFailed:
2665 /* error message should be set up already */
2666 return 0;
2667}
@ PGQUERY_DESCRIBE
Definition: libpq-int.h:323
@ PGQUERY_CLOSE
Definition: libpq-int.h:325
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 1981 of file fe-exec.c.

1982{
1983 if (chunkSize > 0 && canChangeResultMode(conn))
1984 {
1985 conn->partialResMode = true;
1986 conn->singleRowMode = false;
1987 conn->maxChunkSize = chunkSize;
1988 return 1;
1989 }
1990 else
1991 return 0;
1992}
static bool canChangeResultMode(PGconn *conn)
Definition: fe-exec.c:1941

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

3961{
3962 bool barg;
3963
3964 if (!conn || conn->status == CONNECTION_BAD)
3965 return -1;
3966
3967 barg = (arg ? true : false);
3968
3969 /* early out if the socket is already in the state requested */
3970 if (barg == conn->nonblocking)
3971 return 0;
3972
3973 /*
3974 * to guarantee constancy for flushing/query/result-polling behavior we
3975 * need to flush the send queue at this point in order to guarantee proper
3976 * behavior. this is ok because either they are making a transition _from_
3977 * or _to_ blocking mode, either way we can block them.
3978 *
3979 * Clear error state in case pqFlush adds to it, unless we're actively
3980 * pipelining, in which case it seems best not to.
3981 */
3982 if (conn->cmd_queue_head == NULL)
3984
3985 /* if we are going from blocking to non-blocking flush here */
3986 if (pqFlush(conn))
3987 return -1;
3988
3989 conn->nonblocking = barg;
3990
3991 return 0;
3992}
return true
Definition: isn.c:130
void * arg
bool nonblocking
Definition: libpq-int.h:467

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:680

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

698{
699 char *msg;
700
701 if (!res)
702 return;
703
704 /*
705 * We handle two OOM scenarios here. The errorMessage buffer might be
706 * marked "broken" due to having previously failed to allocate enough
707 * memory for the message, or it might be fine but pqResultStrdup fails
708 * and returns NULL. In either case, just make res->errMsg point directly
709 * at a constant "out of memory" string.
710 */
711 if (!PQExpBufferBroken(errorMessage))
712 msg = pqResultStrdup(res, errorMessage->data + offset);
713 else
714 msg = NULL;
715 if (msg)
716 res->errMsg = msg;
717 else
718 res->errMsg = libpq_gettext("out of memory\n");
719}
#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 1964 of file fe-exec.c.

1965{
1967 {
1968 conn->partialResMode = true;
1969 conn->singleRowMode = true;
1970 conn->maxChunkSize = 1;
1971 return 1;
1972 }
1973 else
1974 return 0;
1975}

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, (size_t) 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:1080

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

4638{
4639 size_t strtextlen,
4640 buflen;
4641 unsigned char *buffer,
4642 *tmpbuf;
4643 size_t i,
4644 j;
4645
4646 if (strtext == NULL)
4647 return NULL;
4648
4649 strtextlen = strlen((const char *) strtext);
4650
4651 if (strtext[0] == '\\' && strtext[1] == 'x')
4652 {
4653 const unsigned char *s;
4654 unsigned char *p;
4655
4656 buflen = (strtextlen - 2) / 2;
4657 /* Avoid unportable malloc(0) */
4658 buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
4659 if (buffer == NULL)
4660 return NULL;
4661
4662 s = strtext + 2;
4663 p = buffer;
4664 while (*s)
4665 {
4666 char v1,
4667 v2;
4668
4669 /*
4670 * Bad input is silently ignored. Note that this includes
4671 * whitespace between hex pairs, which is allowed by byteain.
4672 */
4673 v1 = get_hex(*s++);
4674 if (!*s || v1 == (char) -1)
4675 continue;
4676 v2 = get_hex(*s++);
4677 if (v2 != (char) -1)
4678 *p++ = (v1 << 4) | v2;
4679 }
4680
4681 buflen = p - buffer;
4682 }
4683 else
4684 {
4685 /*
4686 * Length of input is max length of output, but add one to avoid
4687 * unportable malloc(0) if input is zero-length.
4688 */
4689 buffer = (unsigned char *) malloc(strtextlen + 1);
4690 if (buffer == NULL)
4691 return NULL;
4692
4693 for (i = j = 0; i < strtextlen;)
4694 {
4695 switch (strtext[i])
4696 {
4697 case '\\':
4698 i++;
4699 if (strtext[i] == '\\')
4700 buffer[j++] = strtext[i++];
4701 else
4702 {
4703 if ((ISFIRSTOCTDIGIT(strtext[i])) &&
4704 (ISOCTDIGIT(strtext[i + 1])) &&
4705 (ISOCTDIGIT(strtext[i + 2])))
4706 {
4707 int byte;
4708
4709 byte = OCTVAL(strtext[i++]);
4710 byte = (byte << 3) + OCTVAL(strtext[i++]);
4711 byte = (byte << 3) + OCTVAL(strtext[i++]);
4712 buffer[j++] = byte;
4713 }
4714 }
4715
4716 /*
4717 * Note: if we see '\' followed by something that isn't a
4718 * recognized escape sequence, we loop around having done
4719 * nothing except advance i. Therefore the something will
4720 * be emitted as ordinary data on the next cycle. Corner
4721 * case: '\' at end of string will just be discarded.
4722 */
4723 break;
4724
4725 default:
4726 buffer[j++] = strtext[i++];
4727 break;
4728 }
4729 }
4730 buflen = j; /* buflen is the length of the dequoted data */
4731 }
4732
4733 /* Shrink the buffer to be no larger than necessary */
4734 /* +1 avoids unportable behavior when buflen==0 */
4735 tmpbuf = realloc(buffer, buflen + 1);
4736
4737 /* It would only be a very brain-dead realloc that could fail, but... */
4738 if (!tmpbuf)
4739 {
4740 free(buffer);
4741 return NULL;
4742 }
4743
4744 *retbuflen = buflen;
4745 return tmpbuf;
4746}
static char get_hex(char c)
Definition: fe-exec.c:4445
#define ISOCTDIGIT(CH)
Definition: fe-exec.c:4621
#define OCTVAL(CH)
Definition: fe-exec.c:4622
#define ISFIRSTOCTDIGIT(CH)
Definition: fe-exec.c:4620
int j
Definition: isn.c:78
static StringInfoData tmpbuf
Definition: walsender.c:178

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

Referenced by get_hex().

◆ hextbl

const char hextbl[] = "0123456789abcdef"
static

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