Header And Logo

PostgreSQL
| The world's most advanced open source database.

Defines | Functions | Variables

fe-exec.c File Reference

#include "postgres_fe.h"
#include <ctype.h>
#include <fcntl.h>
#include "libpq-fe.h"
#include "libpq-int.h"
#include "mb/pg_wchar.h"
#include <unistd.h>
Include dependency graph for fe-exec.c:

Go to the source code of this file.

Defines

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

Functions

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

Variables

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

Define Documentation

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

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

Referenced by PQunescapeBytea().

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

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

Referenced by PQunescapeBytea().

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

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

Referenced by PQunescapeBytea().

#define PGRESULT_ALIGN_BOUNDARY   MAXIMUM_ALIGNOF

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

Referenced by pqResultAlloc().

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

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

Referenced by pqResultAlloc().

#define PGRESULT_DATA_BLOCKSIZE   2048

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

Referenced by pqResultAlloc().

#define PGRESULT_SEP_ALLOC_THRESHOLD   (PGRESULT_DATA_BLOCKSIZE / 2)

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

Referenced by pqResultAlloc().


Function Documentation

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

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

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

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

{
    if (!res)
        return FALSE;           /* no way to display error message... */
    if (field_num < 0 || field_num >= res->numAttributes)
    {
        pqInternalNotice(&res->noticeHooks,
                         "column number %d is out of range 0..%d",
                         field_num, res->numAttributes - 1);
        return FALSE;
    }
    return TRUE;
}

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

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

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

Referenced by PQparamtype().

{
    if (!res)
        return FALSE;           /* no way to display error message... */
    if (param_num < 0 || param_num >= res->numParameters)
    {
        pqInternalNotice(&res->noticeHooks,
                         "parameter number %d is out of range 0..%d",
                         param_num, res->numParameters - 1);
        return FALSE;
    }

    return TRUE;
}

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

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

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

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

{
    if (!res)
        return FALSE;           /* no way to display error message... */
    if (tup_num < 0 || tup_num >= res->ntups)
    {
        pqInternalNotice(&res->noticeHooks,
                         "row number %d is out of range 0..%d",
                         tup_num, res->ntups - 1);
        return FALSE;
    }
    if (field_num < 0 || field_num >= res->numAttributes)
    {
        pqInternalNotice(&res->noticeHooks,
                         "column number %d is out of range 0..%d",
                         field_num, res->numAttributes - 1);
        return FALSE;
    }
    return TRUE;
}

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

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

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

Referenced by PQcopyResult(), and PQmakeEmptyPGresult().

{
    PGEvent    *newEvents;
    int         i;

    if (!events || count <= 0)
        return NULL;

    newEvents = (PGEvent *) malloc(count * sizeof(PGEvent));
    if (!newEvents)
        return NULL;

    for (i = 0; i < count; i++)
    {
        newEvents[i].proc = events[i].proc;
        newEvents[i].passThrough = events[i].passThrough;
        newEvents[i].data = NULL;
        newEvents[i].resultInitialized = FALSE;
        newEvents[i].name = strdup(events[i].name);
        if (!newEvents[i].name)
        {
            while (--i >= 0)
                free(newEvents[i].name);
            free(newEvents);
            return NULL;
        }
    }

    return newEvents;
}

static char get_hex ( char  c  )  [inline, static]

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

References hexlookup.

Referenced by PQunescapeBytea().

{
    int         res = -1;

    if (c > 0 && c < 127)
        res = hexlookup[(unsigned char) c];

    return (char) res;
}

static void parseInput ( PGconn conn  )  [static]
static bool pqAddTuple ( PGresult res,
PGresAttValue tup 
) [static]

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

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

Referenced by pqRowProcessor(), and PQsetvalue().

{
    if (res->ntups >= res->tupArrSize)
    {
        /*
         * Try to grow the array.
         *
         * We can use realloc because shallow copying of the structure is
         * okay. Note that the first time through, res->tuples is NULL. While
         * ANSI says that realloc() should act like malloc() in that case,
         * some old C libraries (like SunOS 4.1.x) coredump instead. On
         * failure realloc is supposed to return NULL without damaging the
         * existing allocation. Note that the positions beyond res->ntups are
         * garbage, not necessarily NULL.
         */
        int         newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
        PGresAttValue **newTuples;

        if (res->tuples == NULL)
            newTuples = (PGresAttValue **)
                malloc(newSize * sizeof(PGresAttValue *));
        else
            newTuples = (PGresAttValue **)
                realloc(res->tuples, newSize * sizeof(PGresAttValue *));
        if (!newTuples)
            return FALSE;       /* malloc or realloc failed */
        res->tupArrSize = newSize;
        res->tuples = newTuples;
    }
    res->tuples[res->ntups] = tup;
    res->ntups++;
    return TRUE;
}

int PQbinaryTuples ( const PGresult res  ) 

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

References pg_result::binary.

Referenced by ProcessResult().

{
    if (!res)
        return 0;
    return res->binary;
}

void pqCatenateResultError ( PGresult res,
const char *  msg 
)

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

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

Referenced by PQexecFinish(), and pqSaveErrorResult().

{
    PQExpBufferData errorBuf;

    if (!res || !msg)
        return;
    initPQExpBuffer(&errorBuf);
    if (res->errMsg)
        appendPQExpBufferStr(&errorBuf, res->errMsg);
    appendPQExpBufferStr(&errorBuf, msg);
    pqSetResultError(res, errorBuf.data);
    termPQExpBuffer(&errorBuf);
}

void PQclear ( PGresult res  ) 

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

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

Referenced by _doSetSessionAuth(), _doSetWithOids(), _selectOutputSchema(), _selectTablespace(), add_tablespace_footer(), BaseBackup(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_rel_oid(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), buildShSecLabels(), check_for_isn_and_int8_passing_mismatch(), check_for_prepared_transactions(), check_for_reg_data_type_usage(), check_is_super_user(), check_loadable_libraries(), close_cursor(), cluster_all_databases(), convertTSFunction(), create_cursor(), createViewAsClause(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_res_error(), deallocate_one(), describeAggregates(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describeRoles(), describeTableDetails(), describeTablespaces(), describeTypes(), descriptor_free(), discard_response(), do_lo_import(), do_lo_list(), do_sql_command(), do_watch(), doCustom(), dropDBs(), dropRoles(), dropTablespaces(), dumpAgg(), dumpBaseType(), dumpBlobs(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpCreateDB(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpDbRoleConfig(), dumpDomain(), dumpEnumType(), dumpFunc(), dumpGroups(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSequence(), dumpSequenceData(), dumpTable(), dumpTableData_copy(), dumpTableData_insert(), dumpTableSchema(), dumpTablespaces(), dumpTSConfig(), dumpTSDictionary(), dumpUserConfig(), dumpUserMappings(), ecpg_check_PQresult(), ecpg_execute(), ecpg_is_type_an_array(), ECPGdescribe(), ECPGsetcommit(), ECPGtrans(), EndDBCopyMode(), exec_command(), ExecQueryUsingCursor(), executeCommand(), executeMaintenanceCommand(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlStatement(), executeStatement(), expand_schema_name_patterns(), expand_table_name_patterns(), fail_lo_xact(), fetch_more_data(), findLastBuiltinOid_V70(), findLastBuiltinOid_V71(), finish_lo_xact(), get_create_function_cmd(), get_db_infos(), get_loadable_libraries(), get_pg_database_relfilenode(), get_rel_infos(), get_remote_estimate(), get_synchronized_snapshot(), get_tablespace_paths(), getAggregates(), getBlobs(), getCasts(), getCollations(), getConstraints(), getConversions(), getCopyStart(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getParamDescriptions(), getProcLangs(), getRowDescriptions(), getRules(), getTableAttrs(), getTables(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), handleCopyIn(), handleCopyOut(), init(), install_support_functions_in_new_db(), libpqrcv_endstreaming(), libpqrcv_identify_system(), libpqrcv_PQexec(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_startstreaming(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listOneExtensionContents(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), lo_close(), lo_creat(), lo_create(), lo_initialize(), lo_lseek(), lo_lseek64(), lo_open(), lo_read(), lo_tell(), lo_tell64(), lo_truncate(), lo_truncate64(), lo_unlink(), lo_write(), lockTableNoWait(), lookup_function_oid(), main(), materializeQueryResult(), materializeResult(), new_9_0_populate_pg_largeobject_metadata(), objectDescription(), old_8_3_check_for_name_data_type_usage(), old_8_3_check_for_tsquery_usage(), old_8_3_check_ltree_usage(), old_8_3_create_sequence_script(), old_8_3_invalidate_bpchar_pattern_ops_indexes(), old_8_3_invalidate_hash_gin_indexes(), old_8_3_rebuild_tsvector_tables(), permissionsList(), pgfdw_report_error(), pgfdw_subxact_callback(), pgfdw_xact_callback(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresEndForeignModify(), postgresExecForeignDelete(), postgresExecForeignInsert(), postgresExecForeignUpdate(), postgresReScanForeignScan(), pqClearAsyncResult(), PQconnectPoll(), PQcopyResult(), pqEndcopy2(), pqEndcopy3(), PQexecFinish(), PQexecStart(), pqGetErrorNotice2(), pqGetErrorNotice3(), pqInternalNotice(), PQmakeEmptyPGresult(), pqRowProcessor(), PQsetClientEncoding(), pqSetenvPoll(), prepare_common(), prepare_foreign_modify(), process_file(), ProcessResult(), PSQLexec(), ReceiveXlogStream(), reindex_all_databases(), run_permutation(), SendQuery(), set_frozenxids(), set_locale_and_encoding(), sql_exec(), start_lo_xact(), store_returning_result(), storeQueryResult(), StreamLog(), try_complete_step(), uninstall_support_functions_from_new_cluster(), vacuum_all_databases(), and vacuumlo().

{
    PGresult_data *block;
    int         i;

    if (!res)
        return;

    for (i = 0; i < res->nEvents; i++)
    {
        /* only send DESTROY to successfully-initialized event procs */
        if (res->events[i].resultInitialized)
        {
            PGEventResultDestroy evt;

            evt.result = res;
            (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
                                       res->events[i].passThrough);
        }
        free(res->events[i].name);
    }

    if (res->events)
        free(res->events);

    /* Free all the subsidiary blocks */
    while ((block = res->curBlock) != NULL)
    {
        res->curBlock = block->next;
        free(block);
    }

    /* Free the top-level tuple pointer array */
    if (res->tuples)
        free(res->tuples);

    /* zero out the pointer fields to catch programming errors */
    res->attDescs = NULL;
    res->tuples = NULL;
    res->paramDescs = NULL;
    res->errFields = NULL;
    res->events = NULL;
    res->nEvents = 0;
    /* res->curBlock was zeroed out earlier */

    /* Free the PGresult structure itself */
    free(res);
}

void pqClearAsyncResult ( PGconn conn  ) 

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

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

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

{
    if (conn->result)
        PQclear(conn->result);
    conn->result = NULL;
    if (conn->next_result)
        PQclear(conn->next_result);
    conn->next_result = NULL;
}

char* PQcmdStatus ( PGresult res  ) 

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

References pg_result::cmdStatus.

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

{
    if (!res)
        return NULL;
    return res->cmdStatus;
}

char* PQcmdTuples ( PGresult res  ) 

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

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

Referenced by ecpg_execute(), postgresExecForeignDelete(), postgresExecForeignInsert(), and postgresExecForeignUpdate().

{
    char       *p,
               *c;

    if (!res)
        return "";

    if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
    {
        p = res->cmdStatus + 7;
        /* INSERT: skip oid and space */
        while (*p && *p != ' ')
            p++;
        if (*p == 0)
            goto interpret_error;       /* no space? */
        p++;
    }
    else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
             strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
             strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
        p = res->cmdStatus + 7;
    else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
        p = res->cmdStatus + 6;
    else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
             strncmp(res->cmdStatus, "COPY ", 5) == 0)
        p = res->cmdStatus + 5;
    else
        return "";

    /* check that we have an integer (at least one digit, nothing else) */
    for (c = p; *c; c++)
    {
        if (!isdigit((unsigned char) *c))
            goto interpret_error;
    }
    if (c == p)
        goto interpret_error;

    return p;

interpret_error:
    pqInternalNotice(&res->noticeHooks,
                     "could not interpret result from server: %s",
                     res->cmdStatus);
    return "";
}

int PQconsumeInput ( PGconn conn  ) 

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

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

Referenced by dblink_get_notify(), dblink_is_busy(), doCustom(), HandleCopyStream(), libpqrcv_PQexec(), libpqrcv_receive(), main(), and try_complete_step().

{
    if (!conn)
        return 0;

    /*
     * for non-blocking connections try to flush the send-queue, otherwise we
     * may never get a response for something that may not have already been
     * sent because it's in our write buffer!
     */
    if (pqIsnonblocking(conn))
    {
        if (pqFlush(conn) < 0)
            return 0;
    }

    /*
     * Load more data, if available. We do this no matter what state we are
     * in, since we are probably getting called because the application wants
     * to get rid of a read-select condition. Note that we will NOT block
     * waiting for more input.
     */
    if (pqReadData(conn) < 0)
        return 0;

    /* Parsing of the data waits till later. */
    return 1;
}

PGresult* PQcopyResult ( const PGresult src,
int  flags 
)

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

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

Referenced by pqRowProcessor().

{
    PGresult   *dest;
    int         i;

    if (!src)
        return NULL;

    dest = PQmakeEmptyPGresult(NULL, PGRES_TUPLES_OK);
    if (!dest)
        return NULL;

    /* Always copy these over.  Is cmdStatus really useful here? */
    dest->client_encoding = src->client_encoding;
    strcpy(dest->cmdStatus, src->cmdStatus);

    /* Wants attrs? */
    if (flags & (PG_COPYRES_ATTRS | PG_COPYRES_TUPLES))
    {
        if (!PQsetResultAttrs(dest, src->numAttributes, src->attDescs))
        {
            PQclear(dest);
            return NULL;
        }
    }

    /* Wants to copy tuples? */
    if (flags & PG_COPYRES_TUPLES)
    {
        int         tup,
                    field;

        for (tup = 0; tup < src->ntups; tup++)
        {
            for (field = 0; field < src->numAttributes; field++)
            {
                if (!PQsetvalue(dest, tup, field,
                                src->tuples[tup][field].value,
                                src->tuples[tup][field].len))
                {
                    PQclear(dest);
                    return NULL;
                }
            }
        }
    }

    /* Wants to copy notice hooks? */
    if (flags & PG_COPYRES_NOTICEHOOKS)
        dest->noticeHooks = src->noticeHooks;

    /* Wants to copy PGEvents? */
    if ((flags & PG_COPYRES_EVENTS) && src->nEvents > 0)
    {
        dest->events = dupEvents(src->events, src->nEvents);
        if (!dest->events)
        {
            PQclear(dest);
            return NULL;
        }
        dest->nEvents = src->nEvents;
    }

    /* Okay, trigger PGEVT_RESULTCOPY event */
    for (i = 0; i < dest->nEvents; i++)
    {
        if (src->events[i].resultInitialized)
        {
            PGEventResultCopy evt;

            evt.src = src;
            evt.dest = dest;
            if (!dest->events[i].proc(PGEVT_RESULTCOPY, &evt,
                                      dest->events[i].passThrough))
            {
                PQclear(dest);
                return NULL;
            }
            dest->events[i].resultInitialized = TRUE;
        }
    }

    return dest;
}

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

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

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

{
    if (!PQexecStart(conn))
        return NULL;
    if (!PQsendDescribe(conn, 'P', portal))
        return NULL;
    return PQexecFinish(conn);
}

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

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

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

Referenced by ECPGdescribe().

{
    if (!PQexecStart(conn))
        return NULL;
    if (!PQsendDescribe(conn, 'S', stmt))
        return NULL;
    return PQexecFinish(conn);
}

int PQendcopy ( PGconn conn  ) 

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

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

Referenced by ecpg_check_PQresult(), and init().

{
    if (!conn)
        return 0;

    if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
        return pqEndcopy3(conn);
    else
        return pqEndcopy2(conn);
}

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

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

References NULL, PQescapeByteaInternal(), and static_std_strings.

{
    return PQescapeByteaInternal(NULL, from, from_length, to_length,
                                 static_std_strings,
                                 false /* can't use hex */ );
}

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

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

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

{
    if (!conn)
        return NULL;
    return PQescapeByteaInternal(conn, from, from_length, to_length,
                                 conn->std_strings,
                                 (conn->sversion >= 90000));
}

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

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

Referenced by PQescapeBytea(), and PQescapeByteaConn().

{
    const unsigned char *vp;
    unsigned char *rp;
    unsigned char *result;
    size_t      i;
    size_t      len;
    size_t      bslash_len = (std_strings ? 1 : 2);

    /*
     * empty string has 1 char ('\0')
     */
    len = 1;

    if (use_hex)
    {
        len += bslash_len + 1 + 2 * from_length;
    }
    else
    {
        vp = from;
        for (i = from_length; i > 0; i--, vp++)
        {
            if (*vp < 0x20 || *vp > 0x7e)
                len += bslash_len + 3;
            else if (*vp == '\'')
                len += 2;
            else if (*vp == '\\')
                len += bslash_len + bslash_len;
            else
                len++;
        }
    }

    *to_length = len;
    rp = result = (unsigned char *) malloc(len);
    if (rp == NULL)
    {
        if (conn)
            printfPQExpBuffer(&conn->errorMessage,
                              libpq_gettext("out of memory\n"));
        return NULL;
    }

    if (use_hex)
    {
        if (!std_strings)
            *rp++ = '\\';
        *rp++ = '\\';
        *rp++ = 'x';
    }

    vp = from;
    for (i = from_length; i > 0; i--, vp++)
    {
        unsigned char c = *vp;

        if (use_hex)
        {
            *rp++ = hextbl[(c >> 4) & 0xF];
            *rp++ = hextbl[c & 0xF];
        }
        else if (c < 0x20 || c > 0x7e)
        {
            if (!std_strings)
                *rp++ = '\\';
            *rp++ = '\\';
            *rp++ = (c >> 6) + '0';
            *rp++ = ((c >> 3) & 07) + '0';
            *rp++ = (c & 07) + '0';
        }
        else if (c == '\'')
        {
            *rp++ = '\'';
            *rp++ = '\'';
        }
        else if (c == '\\')
        {
            if (!std_strings)
            {
                *rp++ = '\\';
                *rp++ = '\\';
            }
            *rp++ = '\\';
            *rp++ = '\\';
        }
        else
            *rp++ = c;
    }
    *rp = '\0';

    return result;
}

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

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

References PQescapeInternal().

Referenced by init(), and vacuumlo().

{
    return PQescapeInternal(conn, str, len, true);
}

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

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

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

Referenced by PQescapeIdentifier(), and PQescapeLiteral().

{
    const char *s;
    char       *result;
    char       *rp;
    int         num_quotes = 0; /* single or double, depending on as_ident */
    int         num_backslashes = 0;
    int         input_len;
    int         result_size;
    char        quote_char = as_ident ? '"' : '\'';

    /* We must have a connection, else fail immediately. */
    if (!conn)
        return NULL;

    /* Scan the string for characters that must be escaped. */
    for (s = str; (s - str) < len && *s != '\0'; ++s)
    {
        if (*s == quote_char)
            ++num_quotes;
        else if (*s == '\\')
            ++num_backslashes;
        else if (IS_HIGHBIT_SET(*s))
        {
            int         charlen;

            /* Slow path for possible multibyte characters */
            charlen = pg_encoding_mblen(conn->client_encoding, s);

            /* Multibyte character overruns allowable length. */
            if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
            {
                printfPQExpBuffer(&conn->errorMessage,
                          libpq_gettext("incomplete multibyte character\n"));
                return NULL;
            }

            /* Adjust s, bearing in mind that for loop will increment it. */
            s += charlen - 1;
        }
    }

    /* Allocate output buffer. */
    input_len = s - str;
    result_size = input_len + num_quotes + 3;   /* two quotes, plus a NUL */
    if (!as_ident && num_backslashes > 0)
        result_size += num_backslashes + 2;
    result = rp = (char *) malloc(result_size);
    if (rp == NULL)
    {
        printfPQExpBuffer(&conn->errorMessage,
                          libpq_gettext("out of memory\n"));
        return NULL;
    }

    /*
     * If we are escaping a literal that contains backslashes, we use the
     * escape string syntax so that the result is correct under either value
     * of standard_conforming_strings.  We also emit a leading space in this
     * case, to guard against the possibility that the result might be
     * interpolated immediately following an identifier.
     */
    if (!as_ident && num_backslashes > 0)
    {
        *rp++ = ' ';
        *rp++ = 'E';
    }

    /* Opening quote. */
    *rp++ = quote_char;

    /*
     * Use fast path if possible.
     *
     * We've already verified that the input string is well-formed in the
     * current encoding.  If it contains no quotes and, in the case of
     * literal-escaping, no backslashes, then we can just copy it directly to
     * the output buffer, adding the necessary quotes.
     *
     * If not, we must rescan the input and process each character
     * individually.
     */
    if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
    {
        memcpy(rp, str, input_len);
        rp += input_len;
    }
    else
    {
        for (s = str; s - str < input_len; ++s)
        {
            if (*s == quote_char || (!as_ident && *s == '\\'))
            {
                *rp++ = *s;
                *rp++ = *s;
            }
            else if (!IS_HIGHBIT_SET(*s))
                *rp++ = *s;
            else
            {
                int         i = pg_encoding_mblen(conn->client_encoding, s);

                while (1)
                {
                    *rp++ = *s;
                    if (--i == 0)
                        break;
                    ++s;        /* for loop will provide the final increment */
                }
            }
        }
    }

    /* Closing quote and terminating NUL. */
    *rp++ = quote_char;
    *rp = '\0';

    return result;
}

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

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

References PQescapeInternal().

{
    return PQescapeInternal(conn, str, len, false);
}

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

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

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

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

{
    if (!conn)
    {
        /* force empty-string result */
        *to = '\0';
        if (error)
            *error = 1;
        return 0;
    }
    return PQescapeStringInternal(conn, to, from, length, error,
                                  conn->client_encoding,
                                  conn->std_strings);
}

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

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

Referenced by PQescapeString(), and PQescapeStringConn().

{
    const char *source = from;
    char       *target = to;
    size_t      remaining = length;

    if (error)
        *error = 0;

    while (remaining > 0 && *source != '\0')
    {
        char        c = *source;
        int         len;
        int         i;

        /* Fast path for plain ASCII */
        if (!IS_HIGHBIT_SET(c))
        {
            /* Apply quoting if needed */
            if (SQL_STR_DOUBLE(c, !std_strings))
                *target++ = c;
            /* Copy the character */
            *target++ = c;
            source++;
            remaining--;
            continue;
        }

        /* Slow path for possible multibyte characters */
        len = pg_encoding_mblen(encoding, source);

        /* Copy the character */
        for (i = 0; i < len; i++)
        {
            if (remaining == 0 || *source == '\0')
                break;
            *target++ = *source++;
            remaining--;
        }

        /*
         * If we hit premature end of string (ie, incomplete multibyte
         * character), try to pad out to the correct length with spaces. We
         * may not be able to pad completely, but we will always be able to
         * insert at least one pad space (since we'd not have quoted a
         * multibyte character).  This should be enough to make a string that
         * the server will error out on.
         */
        if (i < len)
        {
            if (error)
                *error = 1;
            if (conn)
                printfPQExpBuffer(&conn->errorMessage,
                          libpq_gettext("incomplete multibyte character\n"));
            for (; i < len; i++)
            {
                if (((size_t) (target - to)) / 2 >= length)
                    break;
                *target++ = ' ';
            }
            break;
        }
    }

    /* Write the terminating NUL character. */
    *target = '\0';

    return target - to;
}

PGresult* PQexec ( PGconn conn,
const char *  query 
)
static PGresult * PQexecFinish ( PGconn conn  )  [static]

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

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

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

{
    PGresult   *result;
    PGresult   *lastResult;

    /*
     * For backwards compatibility, return the last result if there are more
     * than one --- but merge error messages if we get more than one error
     * result.
     *
     * We have to stop if we see copy in/out/both, however. We will resume
     * parsing after application performs the data transfer.
     *
     * Also stop if the connection is lost (else we'll loop infinitely).
     */
    lastResult = NULL;
    while ((result = PQgetResult(conn)) != NULL)
    {
        if (lastResult)
        {
            if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
                result->resultStatus == PGRES_FATAL_ERROR)
            {
                pqCatenateResultError(lastResult, result->errMsg);
                PQclear(result);
                result = lastResult;

                /*
                 * Make sure PQerrorMessage agrees with concatenated result
                 */
                resetPQExpBuffer(&conn->errorMessage);
                appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
            }
            else
                PQclear(lastResult);
        }
        lastResult = result;
        if (result->resultStatus == PGRES_COPY_IN ||
            result->resultStatus == PGRES_COPY_OUT ||
            result->resultStatus == PGRES_COPY_BOTH ||
            conn->status == CONNECTION_BAD)
            break;
    }

    return lastResult;
}

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

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

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

{
    if (!PQexecStart(conn))
        return NULL;
    if (!PQsendQueryParams(conn, command,
                           nParams, paramTypes, paramValues, paramLengths,
                           paramFormats, resultFormat))
        return NULL;
    return PQexecFinish(conn);
}

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

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

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

Referenced by ecpg_execute(), postgresExecForeignDelete(), postgresExecForeignInsert(), postgresExecForeignUpdate(), and try_complete_step().

{
    if (!PQexecStart(conn))
        return NULL;
    if (!PQsendQueryPrepared(conn, stmtName,
                             nParams, paramValues, paramLengths,
                             paramFormats, resultFormat))
        return NULL;
    return PQexecFinish(conn);
}

static bool PQexecStart ( PGconn conn  )  [static]

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

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

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

{
    PGresult   *result;

    if (!conn)
        return false;

    /*
     * Silently discard any prior query result that application didn't eat.
     * This is probably poor design, but it's here for backward compatibility.
     */
    while ((result = PQgetResult(conn)) != NULL)
    {
        ExecStatusType resultStatus = result->resultStatus;

        PQclear(result);        /* only need its status */
        if (resultStatus == PGRES_COPY_IN)
        {
            if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
            {
                /* In protocol 3, we can get out of a COPY IN state */
                if (PQputCopyEnd(conn,
                         libpq_gettext("COPY terminated by new PQexec")) < 0)
                    return false;
                /* keep waiting to swallow the copy's failure message */
            }
            else
            {
                /* In older protocols we have to punt */
                printfPQExpBuffer(&conn->errorMessage,
                  libpq_gettext("COPY IN state must be terminated first\n"));
                return false;
            }
        }
        else if (resultStatus == PGRES_COPY_OUT)
        {
            if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
            {
                /*
                 * In protocol 3, we can get out of a COPY OUT state: we just
                 * switch back to BUSY and allow the remaining COPY data to be
                 * dropped on the floor.
                 */
                conn->asyncStatus = PGASYNC_BUSY;
                /* keep waiting to swallow the copy's completion message */
            }
            else
            {
                /* In older protocols we have to punt */
                printfPQExpBuffer(&conn->errorMessage,
                 libpq_gettext("COPY OUT state must be terminated first\n"));
                return false;
            }
        }
        else if (resultStatus == PGRES_COPY_BOTH)
        {
            /* We don't allow PQexec during COPY BOTH */
            printfPQExpBuffer(&conn->errorMessage,
                     libpq_gettext("PQexec not allowed during COPY BOTH\n"));
            return false;
        }
        /* check for loss of connection, too */
        if (conn->status == CONNECTION_BAD)
            return false;
    }

    /* OK to send a command */
    return true;
}

int PQfformat ( const PGresult res,
int  field_num 
)

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

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

Referenced by ecpg_get_data(), and ecpg_store_result().

{
    if (!check_field_number(res, field_num))
        return 0;
    if (res->attDescs)
        return res->attDescs[field_num].format;
    else
        return 0;
}

int PQflush ( PGconn conn  ) 

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

References pqFlush().

Referenced by HandleCopyStream(), libpqrcv_endstreaming(), libpqrcv_send(), and sendFeedback().

{
    return pqFlush(conn);
}

int PQfmod ( const PGresult res,
int  field_num 
)

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

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

Referenced by ECPGget_desc().

{
    if (!check_field_number(res, field_num))
        return 0;
    if (res->attDescs)
        return res->attDescs[field_num].atttypmod;
    else
        return 0;
}

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

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

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

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

{
    *actual_result_len = 0;

    if (!conn)
        return NULL;

    /* clear the error string */
    resetPQExpBuffer(&conn->errorMessage);

    if (conn->sock < 0 || conn->asyncStatus != PGASYNC_IDLE ||
        conn->result != NULL)
    {
        printfPQExpBuffer(&conn->errorMessage,
                          libpq_gettext("connection in wrong state\n"));
        return NULL;
    }

    if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
        return pqFunctionCall3(conn, fnid,
                               result_buf, actual_result_len,
                               result_is_int,
                               args, nargs);
    else
        return pqFunctionCall2(conn, fnid,
                               result_buf, actual_result_len,
                               result_is_int,
                               args, nargs);
}

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

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

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

Referenced by binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_rel_oid(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), check_for_isn_and_int8_passing_mismatch(), check_for_reg_data_type_usage(), collectComments(), collectSecLabels(), dropRoles(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpDatabase(), dumpDomain(), dumpEnumType(), dumpFunc(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoles(), dumpTableSchema(), dumpTSConfig(), dumpUserMappings(), findLastBuiltinOid_V70(), findLastBuiltinOid_V71(), get_db_infos(), get_pg_database_relfilenode(), get_rel_infos(), get_tablespace_paths(), getAggregates(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getIndexes(), getInherits(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getProcLangs(), getRules(), getTableAttrs(), getTables(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), new_9_0_populate_pg_largeobject_metadata(), old_8_3_check_for_name_data_type_usage(), old_8_3_check_for_tsquery_usage(), old_8_3_check_ltree_usage(), old_8_3_create_sequence_script(), old_8_3_invalidate_bpchar_pattern_ops_indexes(), old_8_3_invalidate_hash_gin_indexes(), old_8_3_rebuild_tsvector_tables(), set_frozenxids(), set_locale_and_encoding(), and show_binary_results().

{
    char       *field_case;
    bool        in_quotes;
    char       *iptr;
    char       *optr;
    int         i;

    if (!res)
        return -1;

    /*
     * Note: it is correct to reject a zero-length input string; the proper
     * input to match a zero-length field name would be "".
     */
    if (field_name == NULL ||
        field_name[0] == '\0' ||
        res->attDescs == NULL)
        return -1;

    /*
     * Note: this code will not reject partially quoted strings, eg
     * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
     * condition.
     */
    field_case = strdup(field_name);
    if (field_case == NULL)
        return -1;              /* grotty */

    in_quotes = false;
    optr = field_case;
    for (iptr = field_case; *iptr; iptr++)
    {
        char        c = *iptr;

        if (in_quotes)
        {
            if (c == '"')
            {
                if (iptr[1] == '"')
                {
                    /* doubled quotes become a single quote */
                    *optr++ = '"';
                    iptr++;
                }
                else
                    in_quotes = false;
            }
            else
                *optr++ = c;
        }
        else if (c == '"')
            in_quotes = true;
        else
        {
            c = pg_tolower((unsigned char) c);
            *optr++ = c;
        }
    }
    *optr = '\0';

    for (i = 0; i < res->numAttributes; i++)
    {
        if (strcmp(field_case, res->attDescs[i].name) == 0)
        {
            free(field_case);
            return i;
        }
    }
    free(field_case);
    return -1;
}

void PQfreemem ( void *  ptr  ) 
void PQfreeNotify ( PGnotify notify  ) 

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

References PQfreemem().

{
    PQfreemem(notify);
}

int PQfsize ( const PGresult res,
int  field_num 
)

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

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

Referenced by ecpg_build_compat_sqlda(), and ECPGget_desc().

{
    if (!check_field_number(res, field_num))
        return 0;
    if (res->attDescs)
        return res->attDescs[field_num].typlen;
    else
        return 0;
}

Oid PQftable ( const PGresult res,
int  field_num 
)

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

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

{
    if (!check_field_number(res, field_num))
        return InvalidOid;
    if (res->attDescs)
        return res->attDescs[field_num].tableid;
    else
        return InvalidOid;
}

int PQftablecol ( const PGresult res,
int  field_num 
)

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

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

{
    if (!check_field_number(res, field_num))
        return 0;
    if (res->attDescs)
        return res->attDescs[field_num].columnid;
    else
        return 0;
}

Oid PQftype ( const PGresult res,
int  field_num 
)

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

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

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

{
    if (!check_field_number(res, field_num))
        return InvalidOid;
    if (res->attDescs)
        return res->attDescs[field_num].typid;
    else
        return InvalidOid;
}

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

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

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

Referenced by dumpTableData_copy(), ecpg_execute(), handleCopyOut(), HandleCopyStream(), libpqrcv_receive(), ReceiveAndUnpackTarFile(), and ReceiveTarFile().

{
    *buffer = NULL;             /* for all failure cases */
    if (!conn)
        return -2;
    if (conn->asyncStatus != PGASYNC_COPY_OUT &&
        conn->asyncStatus != PGASYNC_COPY_BOTH)
    {
        printfPQExpBuffer(&conn->errorMessage,
                          libpq_gettext("no COPY in progress\n"));
        return -2;
    }
    if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
        return pqGetCopyData3(conn, buffer, async);
    else
        return pqGetCopyData2(conn, buffer, async);
}

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

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

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

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

{
    if (!check_tuple_field_number(res, tup_num, field_num))
        return 0;
    if (res->tuples[tup_num][field_num].len != NULL_LEN)
        return res->tuples[tup_num][field_num].len;
    else
        return 0;
}

int PQgetline ( PGconn conn,
char *  s,
int  maxlen 
)

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

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

{
    if (!s || maxlen <= 0)
        return EOF;
    *s = '\0';
    /* maxlen must be at least 3 to hold the \. terminator! */
    if (maxlen < 3)
        return EOF;

    if (!conn)
        return EOF;

    if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
        return pqGetline3(conn, s, maxlen);
    else
        return pqGetline2(conn, s, maxlen);
}

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

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

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

Referenced by pqGetline3().

{
    if (!conn)
        return -1;

    if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
        return pqGetlineAsync3(conn, buffer, bufsize);
    else
        return pqGetlineAsync2(conn, buffer, bufsize);
}

PGresult* PQgetResult ( PGconn conn  ) 

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

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

Referenced by BaseBackup(), dblink_record_internal(), discard_response(), doCustom(), dumpTableData_copy(), ecpg_execute(), EndDBCopyMode(), handleCopyIn(), handleCopyOut(), HandleCopyStream(), libpqrcv_endstreaming(), libpqrcv_PQexec(), libpqrcv_receive(), materializeQueryResult(), PQconnectPoll(), pqEndcopy2(), pqEndcopy3(), PQexecFinish(), PQexecStart(), pqSetenvPoll(), ProcessResult(), ReceiveAndUnpackTarFile(), ReceiveTarFile(), ReceiveXlogStream(), run_permutation(), storeQueryResult(), and try_complete_step().

{
    PGresult   *res;

    if (!conn)
        return NULL;

    /* Parse any available data, if our state permits. */
    parseInput(conn);

    /* If not ready to return something, block until we are. */
    while (conn->asyncStatus == PGASYNC_BUSY)
    {
        int         flushResult;

        /*
         * If data remains unsent, send it.  Else we might be waiting for the
         * result of a command the backend hasn't even got yet.
         */
        while ((flushResult = pqFlush(conn)) > 0)
        {
            if (pqWait(FALSE, TRUE, conn))
            {
                flushResult = -1;
                break;
            }
        }

        /* Wait for some more data, and load it. */
        if (flushResult ||
            pqWait(TRUE, FALSE, conn) ||
            pqReadData(conn) < 0)
        {
            /*
             * conn->errorMessage has been set by pqWait or pqReadData. We
             * want to append it to any already-received error message.
             */
            pqSaveErrorResult(conn);
            conn->asyncStatus = PGASYNC_IDLE;
            return pqPrepareAsyncResult(conn);
        }

        /* Parse it. */
        parseInput(conn);
    }

    /* Return the appropriate thing. */
    switch (conn->asyncStatus)
    {
        case PGASYNC_IDLE:
            res = NULL;         /* query is complete */
            break;
        case PGASYNC_READY:
            res = pqPrepareAsyncResult(conn);
            /* Set the state back to BUSY, allowing parsing to proceed. */
            conn->asyncStatus = PGASYNC_BUSY;
            break;
        case PGASYNC_COPY_IN:
            if (conn->result && conn->result->resultStatus == PGRES_COPY_IN)
                res = pqPrepareAsyncResult(conn);
            else
                res = PQmakeEmptyPGresult(conn, PGRES_COPY_IN);
            break;
        case PGASYNC_COPY_OUT:
            if (conn->result && conn->result->resultStatus == PGRES_COPY_OUT)
                res = pqPrepareAsyncResult(conn);
            else
                res = PQmakeEmptyPGresult(conn, PGRES_COPY_OUT);
            break;
        case PGASYNC_COPY_BOTH:
            if (conn->result && conn->result->resultStatus == PGRES_COPY_BOTH)
                res = pqPrepareAsyncResult(conn);
            else
                res = PQmakeEmptyPGresult(conn, PGRES_COPY_BOTH);
            break;
        default:
            printfPQExpBuffer(&conn->errorMessage,
                              libpq_gettext("unexpected asyncStatus: %d\n"),
                              (int) conn->asyncStatus);
            res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
            break;
    }

    if (res)
    {
        int         i;

        for (i = 0; i < res->nEvents; i++)
        {
            PGEventResultCreate evt;

            evt.conn = conn;
            evt.result = res;
            if (!res->events[i].proc(PGEVT_RESULTCREATE, &evt,
                                     res->events[i].passThrough))
            {
                printfPQExpBuffer(&conn->errorMessage,
                                  libpq_gettext("PGEventProc \"%s\" failed during PGEVT_RESULTCREATE event\n"),
                                  res->events[i].name);
                pqSetResultError(res, conn->errorMessage.data);
                res->resultStatus = PGRES_FATAL_ERROR;
                break;
            }
            res->events[i].resultInitialized = TRUE;
        }
    }

    return res;
}

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

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

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

Referenced by add_tablespace_footer(), BaseBackup(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_rel_oid(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), check_for_isn_and_int8_passing_mismatch(), check_for_reg_data_type_usage(), check_is_super_user(), cluster_all_databases(), collectComments(), collectSecLabels(), convertTSFunction(), createViewAsClause(), describeOneTableDetails(), describeRoles(), describeTableDetails(), do_field(), dropDBs(), dropRoles(), dropTablespaces(), dumpAgg(), dumpBaseType(), dumpBlobs(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpCreateDB(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpDbRoleConfig(), dumpDomain(), dumpEnumType(), dumpForeignServer(), dumpFunc(), dumpGroups(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSequence(), dumpSequenceData(), dumpTable(), dumpTableData_insert(), dumpTableSchema(), dumpTablespaces(), dumpTSConfig(), dumpTSDictionary(), dumpUserConfig(), dumpUserMappings(), ecpg_get_data(), ecpg_is_type_an_array(), ecpg_set_compat_sqlda(), ecpg_set_native_sqlda(), ecpg_store_result(), emitShSecLabels(), expand_schema_name_patterns(), expand_table_name_patterns(), findLastBuiltinOid_V70(), findLastBuiltinOid_V71(), get_create_function_cmd(), get_db_infos(), get_loadable_libraries(), get_pg_database_relfilenode(), get_rel_infos(), get_remote_estimate(), get_synchronized_snapshot(), get_tablespace_paths(), getAggregates(), getBlobs(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getProcLangs(), getRules(), getTableAttrs(), getTables(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), libpqrcv_endstreaming(), libpqrcv_identify_system(), libpqrcv_readtimelinehistoryfile(), listExtensionContents(), listTSConfigsVerbose(), listTSParsersVerbose(), lo_initialize(), lockTableNoWait(), lookup_function_oid(), main(), make_tuple_from_result_row(), materializeResult(), new_9_0_populate_pg_largeobject_metadata(), old_8_3_check_for_name_data_type_usage(), old_8_3_check_for_tsquery_usage(), old_8_3_check_ltree_usage(), old_8_3_create_sequence_script(), old_8_3_invalidate_bpchar_pattern_ops_indexes(), old_8_3_invalidate_hash_gin_indexes(), old_8_3_rebuild_tsvector_tables(), postgresAnalyzeForeignTable(), PQdisplayTuples(), PQprintTuples(), pqSetenvPoll(), printQuery(), printResultSet(), ReceiveAndUnpackTarFile(), ReceiveTarFile(), ReceiveXlogStream(), reindex_all_databases(), set_frozenxids(), set_locale_and_encoding(), show_binary_results(), sql_exec(), sqlda_common_total_size(), StoreQueryTuple(), storeRow(), StreamLog(), vacuum_all_databases(), and vacuumlo().

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

void pqHandleSendFailure ( PGconn conn  ) 

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

References parseInput(), and pqReadData().

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

{
    /*
     * Accept any available input data, ignoring errors.  Note that if
     * pqReadData decides the backend has closed the channel, it will close
     * our side of the socket --- that's just what we want here.
     */
    while (pqReadData(conn) > 0)
         /* loop until no more data readable */ ;

    /*
     * Parse any available input messages.  Since we are in PGASYNC_IDLE
     * state, only NOTICE and NOTIFY messages will be eaten.
     */
    parseInput(conn);
}

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

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

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

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

{
    char        msgBuf[1024];
    va_list     args;
    PGresult   *res;

    if (hooks->noticeRec == NULL)
        return;                 /* nobody home to receive notice? */

    /* Format the message */
    va_start(args, fmt);
    vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
    va_end(args);
    msgBuf[sizeof(msgBuf) - 1] = '\0';  /* make real sure it's terminated */

    /* Make a PGresult to pass to the notice receiver */
    res = PQmakeEmptyPGresult(NULL, PGRES_NONFATAL_ERROR);
    if (!res)
        return;
    res->noticeHooks = *hooks;

    /*
     * Set up fields of notice.
     */
    pqSaveMessageField(res, PG_DIAG_MESSAGE_PRIMARY, msgBuf);
    pqSaveMessageField(res, PG_DIAG_SEVERITY, libpq_gettext("NOTICE"));
    /* XXX should provide a SQLSTATE too? */

    /*
     * Result text is always just the primary message + newline. If we can't
     * allocate it, don't bother invoking the receiver.
     */
    res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, FALSE);
    if (res->errMsg)
    {
        sprintf(res->errMsg, "%s\n", msgBuf);

        /*
         * Pass to receiver, then free it.
         */
        (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
    }
    PQclear(res);
}

int PQisBusy ( PGconn conn  ) 

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

References pg_conn::asyncStatus, and parseInput().

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

{
    if (!conn)
        return FALSE;

    /* Parse any available data, if our state permits. */
    parseInput(conn);

    /* PQgetResult will return immediately in all states except BUSY. */
    return conn->asyncStatus == PGASYNC_BUSY;
}

int PQisnonblocking ( const PGconn conn  ) 

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

References pqIsnonblocking.

{
    return pqIsnonblocking(conn);
}

int PQisthreadsafe ( void   ) 

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

{
#ifdef ENABLE_THREAD_SAFETY
    return true;
#else
    return false;
#endif
}

PGresult* PQmakeEmptyPGresult ( PGconn conn,
ExecStatusType  status 
)

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

References pg_result::attDescs, pg_result::binary, pg_conn::client_encoding, pg_result::client_encoding, pg_result::cmdStatus, pg_result::curBlock, pg_result::curOffset, PQExpBufferData::data, dupEvents(), pg_result::errFields, pg_result::errMsg, pg_conn::errorMessage, pg_conn::events, pg_result::events, malloc, pg_conn::nEvents, pg_result::nEvents, pg_conn::noticeHooks, pg_result::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, PGRES_COMMAND_OK, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_EMPTY_QUERY, PGRES_SINGLE_TUPLE, PGRES_TUPLES_OK, PQclear(), pqSetResultError(), pg_result::resultStatus, pg_result::spaceLeft, pg_result::tupArrSize, and pg_result::tuples.

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

{
    PGresult   *result;

    result = (PGresult *) malloc(sizeof(PGresult));
    if (!result)
        return NULL;

    result->ntups = 0;
    result->numAttributes = 0;
    result->attDescs = NULL;
    result->tuples = NULL;
    result->tupArrSize = 0;
    result->numParameters = 0;
    result->paramDescs = NULL;
    result->resultStatus = status;
    result->cmdStatus[0] = '\0';
    result->binary = 0;
    result->events = NULL;
    result->nEvents = 0;
    result->errMsg = NULL;
    result->errFields = NULL;
    result->null_field[0] = '\0';
    result->curBlock = NULL;
    result->curOffset = 0;
    result->spaceLeft = 0;

    if (conn)
    {
        /* copy connection data we might need for operations on PGresult */
        result->noticeHooks = conn->noticeHooks;
        result->client_encoding = conn->client_encoding;

        /* consider copying conn's errorMessage */
        switch (status)
        {
            case PGRES_EMPTY_QUERY:
            case PGRES_COMMAND_OK:
            case PGRES_TUPLES_OK:
            case PGRES_COPY_OUT:
            case PGRES_COPY_IN:
            case PGRES_COPY_BOTH:
            case PGRES_SINGLE_TUPLE:
                /* non-error cases */
                break;
            default:
                pqSetResultError(result, conn->errorMessage.data);
                break;
        }

        /* copy events last; result must be valid if we need to PQclear */
        if (conn->nEvents > 0)
        {
            result->events = dupEvents(conn->events, conn->nEvents);
            if (!result->events)
            {
                PQclear(result);
                return NULL;
            }
            result->nEvents = conn->nEvents;
        }
    }
    else
    {
        /* defaults... */
        result->noticeHooks.noticeRec = NULL;
        result->noticeHooks.noticeRecArg = NULL;
        result->noticeHooks.noticeProc = NULL;
        result->noticeHooks.noticeProcArg = NULL;
        result->client_encoding = PG_SQL_ASCII;
    }

    return result;
}

int PQnfields ( const PGresult res  ) 
PGnotify* PQnotifies ( PGconn conn  ) 

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

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

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

{
    PGnotify   *event;

    if (!conn)
        return NULL;

    /* Parse any available data to see if we can extract NOTIFY messages. */
    parseInput(conn);

    event = conn->notifyHead;
    if (event)
    {
        conn->notifyHead = event->next;
        if (!conn->notifyHead)
            conn->notifyTail = NULL;
        event->next = NULL;     /* don't let app see the internal state */
    }
    return event;
}

int PQnparams ( const PGresult res  ) 

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

References pg_result::numParameters.

{
    if (!res)
        return 0;
    return res->numParameters;
}

int PQntuples ( const PGresult res  ) 

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

References pg_result::ntups.

Referenced by add_tablespace_footer(), BaseBackup(), buildMatViewRefreshDependencies(), check_for_isn_and_int8_passing_mismatch(), check_for_prepared_transactions(), check_for_reg_data_type_usage(), check_is_super_user(), cluster_all_databases(), collectComments(), collectSecLabels(), createViewAsClause(), describeOneTableDetails(), describeRoles(), describeTableDetails(), dropDBs(), dropRoles(), dropTablespaces(), dumpBlobs(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpCreateDB(), dumpDatabaseConfig(), dumpDatabases(), dumpDbRoleConfig(), dumpEnumType(), dumpGroups(), dumpOpclass(), dumpOpfamily(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSequence(), dumpSequenceData(), dumpTable(), dumpTableData_insert(), dumpTablespaces(), dumpTSConfig(), dumpUserConfig(), dumpUserMappings(), ecpg_execute(), ecpg_is_type_an_array(), ecpg_store_result(), ECPGget_desc(), emitShSecLabels(), ExecQueryUsingCursor(), ExecuteSqlQueryForSingleRow(), expand_schema_name_patterns(), expand_table_name_patterns(), fetch_more_data(), get_create_function_cmd(), get_db_infos(), get_loadable_libraries(), get_rel_infos(), get_tablespace_paths(), getAggregates(), getBlobs(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getIndexes(), getInherits(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getProcLangs(), getRules(), getTableAttrs(), getTables(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), libpqrcv_endstreaming(), libpqrcv_identify_system(), libpqrcv_readtimelinehistoryfile(), listDbRoleSettings(), listExtensionContents(), listTables(), listTSConfigsVerbose(), listTSParsersVerbose(), lo_initialize(), lookup_function_oid(), main(), make_tuple_from_result_row(), materializeResult(), old_8_3_check_for_name_data_type_usage(), old_8_3_check_for_tsquery_usage(), old_8_3_check_ltree_usage(), old_8_3_create_sequence_script(), old_8_3_invalidate_bpchar_pattern_ops_indexes(), old_8_3_invalidate_hash_gin_indexes(), old_8_3_rebuild_tsvector_tables(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresExecForeignDelete(), postgresExecForeignInsert(), postgresExecForeignUpdate(), PQdisplayTuples(), PQprint(), PQprintTuples(), pqSetenvPoll(), printQuery(), printResultSet(), ReceiveXlogStream(), reindex_all_databases(), set_frozenxids(), set_locale_and_encoding(), show_binary_results(), sql_exec(), StoreQueryTuple(), storeRow(), StreamLog(), try_complete_step(), vacuum_all_databases(), and vacuumlo().

{
    if (!res)
        return 0;
    return res->ntups;
}

char* PQoidStatus ( const PGresult res  ) 

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

References buf, and pg_result::cmdStatus.

{
    /*
     * This must be enough to hold the result. Don't laugh, this is better
     * than what this function used to do.
     */
    static char buf[24];

    size_t      len;

    if (!res || !res->cmdStatus || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
        return "";

    len = strspn(res->cmdStatus + 7, "0123456789");
    if (len > 23)
        len = 23;
    strncpy(buf, res->cmdStatus + 7, len);
    buf[len] = '\0';

    return buf;
}

Oid PQoidValue ( const PGresult res  ) 

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

References pg_result::cmdStatus.

Referenced by ecpg_execute(), and PrintQueryStatus().

{
    char       *endptr = NULL;
    unsigned long result;

    if (!res ||
        !res->cmdStatus ||
        strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
        res->cmdStatus[7] < '0' ||
        res->cmdStatus[7] > '9')
        return InvalidOid;

    result = strtoul(res->cmdStatus + 7, &endptr, 10);

    if (!endptr || (*endptr != ' ' && *endptr != '\0'))
        return InvalidOid;
    else
        return (Oid) result;
}

Oid PQparamtype ( const PGresult res,
int  param_num 
)

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

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

{
    if (!check_param_number(res, param_num))
        return InvalidOid;
    if (res->paramDescs)
        return res->paramDescs[param_num].typid;
    else
        return InvalidOid;
}

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

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

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

Referenced by doCustom(), main(), prepare_common(), and prepare_foreign_modify().

{
    if (!PQexecStart(conn))
        return NULL;
    if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
        return NULL;
    return PQexecFinish(conn);
}

PGresult* pqPrepareAsyncResult ( PGconn conn  ) 

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

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

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

{
    PGresult   *res;

    /*
     * conn->result is the PGresult to return.  If it is NULL (which probably
     * shouldn't happen) we assume there is an appropriate error message in
     * conn->errorMessage.
     */
    res = conn->result;
    if (!res)
        res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
    else
    {
        /*
         * Make sure PQerrorMessage agrees with result; it could be different
         * if we have concatenated messages.
         */
        resetPQExpBuffer(&conn->errorMessage);
        appendPQExpBufferStr(&conn->errorMessage,
                             PQresultErrorMessage(res));
    }

    /*
     * Replace conn->result with next_result, if any.  In the normal case
     * there isn't a next result and we're just dropping ownership of the
     * current result.  In single-row mode this restores the situation to what
     * it was before we created the current single-row result.
     */
    conn->result = conn->next_result;
    conn->next_result = NULL;

    return res;
}

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

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

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

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

{
    if (!conn)
        return -1;
    if (conn->asyncStatus != PGASYNC_COPY_IN &&
        conn->asyncStatus != PGASYNC_COPY_BOTH)
    {
        printfPQExpBuffer(&conn->errorMessage,
                          libpq_gettext("no COPY in progress\n"));
        return -1;
    }

    /*
     * Process any NOTICE or NOTIFY messages that might be pending in the
     * input buffer.  Since the server might generate many notices during the
     * COPY, we want to clean those out reasonably promptly to prevent
     * indefinite expansion of the input buffer.  (Note: the actual read of
     * input data into the input buffer happens down inside pqSendSome, but
     * it's not authorized to get rid of the data again.)
     */
    parseInput(conn);

    if (nbytes > 0)
    {
        /*
         * Try to flush any previously sent data in preference to growing the
         * output buffer.  If we can't enlarge the buffer enough to hold the
         * data, return 0 in the nonblock case, else hard error. (For
         * simplicity, always assume 5 bytes of overhead even in protocol 2.0
         * case.)
         */
        if ((conn->outBufSize - conn->outCount - 5) < nbytes)
        {
            if (pqFlush(conn) < 0)
                return -1;
            if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
                                      conn))
                return pqIsnonblocking(conn) ? 0 : -1;
        }
        /* Send the data (too simple to delegate to fe-protocol files) */
        if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
        {
            if (pqPutMsgStart('d', false, conn) < 0 ||
                pqPutnchar(buffer, nbytes, conn) < 0 ||
                pqPutMsgEnd(conn) < 0)
                return -1;
        }
        else
        {
            if (pqPutMsgStart(0, false, conn) < 0 ||
                pqPutnchar(buffer, nbytes, conn) < 0 ||
                pqPutMsgEnd(conn) < 0)
                return -1;
        }
    }
    return 1;
}

int PQputCopyEnd ( PGconn conn,
const char *  errormsg 
)

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

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

Referenced by EndDBCopyMode(), handleCopyIn(), HandleCopyStream(), libpqrcv_endstreaming(), and PQexecStart().

{
    if (!conn)
        return -1;
    if (conn->asyncStatus != PGASYNC_COPY_IN &&
        conn->asyncStatus != PGASYNC_COPY_BOTH)
    {
        printfPQExpBuffer(&conn->errorMessage,
                          libpq_gettext("no COPY in progress\n"));
        return -1;
    }

    /*
     * Send the COPY END indicator.  This is simple enough that we don't
     * bother delegating it to the fe-protocol files.
     */
    if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
    {
        if (errormsg)
        {
            /* Send COPY FAIL */
            if (pqPutMsgStart('f', false, conn) < 0 ||
                pqPuts(errormsg, conn) < 0 ||
                pqPutMsgEnd(conn) < 0)
                return -1;
        }
        else
        {
            /* Send COPY DONE */
            if (pqPutMsgStart('c', false, conn) < 0 ||
                pqPutMsgEnd(conn) < 0)
                return -1;
        }

        /*
         * If we sent the COPY command in extended-query mode, we must issue a
         * Sync as well.
         */
        if (conn->queryclass != PGQUERY_SIMPLE)
        {
            if (pqPutMsgStart('S', false, conn) < 0 ||
                pqPutMsgEnd(conn) < 0)
                return -1;
        }
    }
    else
    {
        if (errormsg)
        {
            /* Ooops, no way to do this in 2.0 */
            printfPQExpBuffer(&conn->errorMessage,
                              libpq_gettext("function requires at least protocol version 3.0\n"));
            return -1;
        }
        else
        {
            /* Send old-style end-of-data marker */
            if (pqPutMsgStart(0, false, conn) < 0 ||
                pqPutnchar("\\.\n", 3, conn) < 0 ||
                pqPutMsgEnd(conn) < 0)
                return -1;
        }
    }

    /* Return to active duty */
    if (conn->asyncStatus == PGASYNC_COPY_BOTH)
        conn->asyncStatus = PGASYNC_COPY_OUT;
    else
        conn->asyncStatus = PGASYNC_BUSY;
    resetPQExpBuffer(&conn->errorMessage);

    /* Try to flush data */
    if (pqFlush(conn) < 0)
        return -1;

    return 1;
}

int PQputline ( PGconn conn,
const char *  s 
)

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

References PQputnbytes().

Referenced by init().

{
    return PQputnbytes(conn, s, strlen(s));
}

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

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

References PQputCopyData().

Referenced by PQputline().

{
    if (PQputCopyData(conn, buffer, nbytes) > 0)
        return 0;
    else
        return EOF;
}

char* PQresStatus ( ExecStatusType  status  ) 

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

References libpq_gettext, and pgresStatus.

Referenced by try_complete_step().

{
    if ((unsigned int) status >= sizeof pgresStatus / sizeof pgresStatus[0])
        return libpq_gettext("invalid ExecStatusType code");
    return pgresStatus[status];
}

void* PQresultAlloc ( PGresult res,
size_t  nBytes 
)

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

References pqResultAlloc(), and TRUE.

Referenced by PQsetResultAttrs().

{
    return pqResultAlloc(res, nBytes, TRUE);
}

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

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

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

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

{
    char       *space;
    PGresult_data *block;

    if (!res)
        return NULL;

    if (nBytes <= 0)
        return res->null_field;

    /*
     * If alignment is needed, round up the current position to an alignment
     * boundary.
     */
    if (isBinary)
    {
        int         offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;

        if (offset)
        {
            res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
            res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
        }
    }

    /* If there's enough space in the current block, no problem. */
    if (nBytes <= (size_t) res->spaceLeft)
    {
        space = res->curBlock->space + res->curOffset;
        res->curOffset += nBytes;
        res->spaceLeft -= nBytes;
        return space;
    }

    /*
     * If the requested object is very large, give it its own block; this
     * avoids wasting what might be most of the current block to start a new
     * block.  (We'd have to special-case requests bigger than the block size
     * anyway.)  The object is always given binary alignment in this case.
     */
    if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
    {
        block = (PGresult_data *) malloc(nBytes + PGRESULT_BLOCK_OVERHEAD);
        if (!block)
            return NULL;
        space = block->space + PGRESULT_BLOCK_OVERHEAD;
        if (res->curBlock)
        {
            /*
             * Tuck special block below the active block, so that we don't
             * have to waste the free space in the active block.
             */
            block->next = res->curBlock->next;
            res->curBlock->next = block;
        }
        else
        {
            /* Must set up the new block as the first active block. */
            block->next = NULL;
            res->curBlock = block;
            res->spaceLeft = 0; /* be sure it's marked full */
        }
        return space;
    }

    /* Otherwise, start a new block. */
    block = (PGresult_data *) malloc(PGRESULT_DATA_BLOCKSIZE);
    if (!block)
        return NULL;
    block->next = res->curBlock;
    res->curBlock = block;
    if (isBinary)
    {
        /* object needs full alignment */
        res->curOffset = PGRESULT_BLOCK_OVERHEAD;
        res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - PGRESULT_BLOCK_OVERHEAD;
    }
    else
    {
        /* we can cram it right after the overhead pointer */
        res->curOffset = sizeof(PGresult_data);
        res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - sizeof(PGresult_data);
    }

    space = block->space + res->curOffset;
    res->curOffset += nBytes;
    res->spaceLeft -= nBytes;
    return space;
}

char* PQresultErrorField ( const PGresult res,
int  fieldcode 
)

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

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

Referenced by dblink_res_error(), dot_pg_pass_warning(), ecpg_raise_backend(), ECPGnoticeReceiver(), minimal_error_message(), pgfdw_report_error(), PQconnectPoll(), pqGetErrorNotice3(), and try_complete_step().

{
    PGMessageField *pfield;

    if (!res)
        return NULL;
    for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
    {
        if (pfield->code == fieldcode)
            return pfield->contents;
    }
    return NULL;
}

char* PQresultErrorMessage ( const PGresult res  ) 

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

References pg_result::errMsg.

Referenced by defaultNoticeReceiver(), ecpg_check_PQresult(), ecpg_execute(), pqPrepareAsyncResult(), ReceiveXlogStream(), and try_complete_step().

{
    if (!res || !res->errMsg)
        return "";
    return res->errMsg;
}

ExecStatusType PQresultStatus ( const PGresult res  ) 

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

References pg_result::resultStatus.

Referenced by _doSetSessionAuth(), _doSetWithOids(), _selectOutputSchema(), _selectTablespace(), AcceptResult(), BaseBackup(), check_loadable_libraries(), close_cursor(), create_cursor(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_record_internal(), do_sql_command(), do_watch(), doCustom(), dumpTableData_copy(), ecpg_check_PQresult(), ecpg_execute(), ecpg_is_type_an_array(), EndDBCopyMode(), ExecQueryUsingCursor(), executeCommand(), executeMaintenanceCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlQuery(), ExecuteSqlStatement(), executeStatement(), fetch_more_data(), get_create_function_cmd(), get_remote_estimate(), handleCopyIn(), handleCopyOut(), HandleCopyStream(), init(), libpqrcv_endstreaming(), libpqrcv_identify_system(), libpqrcv_PQexec(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_startstreaming(), lo_close(), lo_creat(), lo_create(), lo_lseek(), lo_lseek64(), lo_open(), lo_read(), lo_tell(), lo_tell64(), lo_truncate(), lo_truncate64(), lo_unlink(), lo_write(), lockTableNoWait(), lookup_function_oid(), main(), materializeQueryResult(), materializeResult(), pgfdw_subxact_callback(), pgfdw_xact_callback(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresEndForeignModify(), postgresExecForeignDelete(), postgresExecForeignInsert(), postgresExecForeignUpdate(), postgresReScanForeignScan(), pqSetenvPoll(), prepare_foreign_modify(), PrintQueryResults(), ProcessResult(), PSQLexec(), ReceiveAndUnpackTarFile(), ReceiveTarFile(), ReceiveXlogStream(), run_permutation(), SendQuery(), sql_exec(), storeQueryResult(), StreamLog(), try_complete_step(), and vacuumlo().

{
    if (!res)
        return PGRES_FATAL_ERROR;
    return res->resultStatus;
}

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

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

References pqResultAlloc().

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

{
    char       *space = (char *) pqResultAlloc(res, strlen(str) + 1, FALSE);

    if (space)
        strcpy(space, str);
    return space;
}

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

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

References pg_conn::asyncStatus, pg_result::attDescs, pgresAttDesc::format, i, pgresAttValue::len, pgDataValue::len, pg_conn::next_result, NULL, pg_result::null_field, pg_result::numAttributes, PG_COPYRES_ATTRS, PG_COPYRES_EVENTS, PG_COPYRES_NOTICEHOOKS, pqAddTuple(), PQclear(), PQcopyResult(), pqResultAlloc(), pg_conn::result, pg_result::resultStatus, pg_conn::rowBuf, pg_conn::singleRowMode, val, value, and pgresAttValue::value.

Referenced by getAnotherTuple().

{
    PGresult   *res = conn->result;
    int         nfields = res->numAttributes;
    const PGdataValue *columns = conn->rowBuf;
    PGresAttValue *tup;
    int         i;

    /*
     * In single-row mode, make a new PGresult that will hold just this one
     * row; the original conn->result is left unchanged so that it can be used
     * again as the template for future rows.
     */
    if (conn->singleRowMode)
    {
        /* Copy everything that should be in the result at this point */
        res = PQcopyResult(res,
                           PG_COPYRES_ATTRS | PG_COPYRES_EVENTS |
                           PG_COPYRES_NOTICEHOOKS);
        if (!res)
            return 0;
    }

    /*
     * Basically we just allocate space in the PGresult for each field and
     * copy the data over.
     *
     * Note: on malloc failure, we return 0 leaving *errmsgp still NULL, which
     * caller will take to mean "out of memory".  This is preferable to trying
     * to set up such a message here, because evidently there's not enough
     * memory for gettext() to do anything.
     */
    tup = (PGresAttValue *)
        pqResultAlloc(res, nfields * sizeof(PGresAttValue), TRUE);
    if (tup == NULL)
        goto fail;

    for (i = 0; i < nfields; i++)
    {
        int         clen = columns[i].len;

        if (clen < 0)
        {
            /* null field */
            tup[i].len = NULL_LEN;
            tup[i].value = res->null_field;
        }
        else
        {
            bool        isbinary = (res->attDescs[i].format != 0);
            char       *val;

            val = (char *) pqResultAlloc(res, clen + 1, isbinary);
            if (val == NULL)
                goto fail;

            /* copy and zero-terminate the data (even if it's binary) */
            memcpy(val, columns[i].value, clen);
            val[clen] = '\0';

            tup[i].len = clen;
            tup[i].value = val;
        }
    }

    /* And add the tuple to the PGresult's tuple array */
    if (!pqAddTuple(res, tup))
        goto fail;

    /*
     * Success.  In single-row mode, make the result available to the client
     * immediately.
     */
    if (conn->singleRowMode)
    {
        /* Change result status to special single-row value */
        res->resultStatus = PGRES_SINGLE_TUPLE;
        /* Stash old result for re-use later */
        conn->next_result = conn->result;
        conn->result = res;
        /* And mark the result ready to return */
        conn->asyncStatus = PGASYNC_READY;
    }

    return 1;

fail:
    /* release locally allocated PGresult, if we made one */
    if (res != conn->result)
        PQclear(res);
    return 0;
}

void pqSaveErrorResult ( PGconn conn  ) 

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

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

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

{
    /*
     * If no old async result, just let PQmakeEmptyPGresult make one. Likewise
     * if old result is not an error message.
     */
    if (conn->result == NULL ||
        conn->result->resultStatus != PGRES_FATAL_ERROR ||
        conn->result->errMsg == NULL)
    {
        pqClearAsyncResult(conn);
        conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
    }
    else
    {
        /* Else, concatenate error message to existing async result. */
        pqCatenateResultError(conn->result, conn->errorMessage.data);
    }
}

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

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

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

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

{
    PGMessageField *pfield;

    pfield = (PGMessageField *)
        pqResultAlloc(res,
                      sizeof(PGMessageField) + strlen(value),
                      TRUE);
    if (!pfield)
        return;                 /* out of memory? */
    pfield->code = code;
    strcpy(pfield->contents, value);
    pfield->next = res->errFields;
    res->errFields = pfield;
}

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

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

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

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

{
    pgParameterStatus *pstatus;
    pgParameterStatus *prev;

    if (conn->Pfdebug)
        fprintf(conn->Pfdebug, "pqSaveParameterStatus: '%s' = '%s'\n",
                name, value);

    /*
     * Forget any old information about the parameter
     */
    for (pstatus = conn->pstatus, prev = NULL;
         pstatus != NULL;
         prev = pstatus, pstatus = pstatus->next)
    {
        if (strcmp(pstatus->name, name) == 0)
        {
            if (prev)
                prev->next = pstatus->next;
            else
                conn->pstatus = pstatus->next;
            free(pstatus);      /* frees name and value strings too */
            break;
        }
    }

    /*
     * Store new info as a single malloc block
     */
    pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
                                           strlen(name) +strlen(value) + 2);
    if (pstatus)
    {
        char       *ptr;

        ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
        pstatus->name = ptr;
        strcpy(ptr, name);
        ptr += strlen(name) + 1;
        pstatus->value = ptr;
        strcpy(ptr, value);
        pstatus->next = conn->pstatus;
        conn->pstatus = pstatus;
    }

    /*
     * Special hacks: remember client_encoding and
     * standard_conforming_strings, and convert server version to a numeric
     * form.  We keep the first two of these in static variables as well, so
     * that PQescapeString and PQescapeBytea can behave somewhat sanely (at
     * least in single-connection-using programs).
     */
    if (strcmp(name, "client_encoding") == 0)
    {
        conn->client_encoding = pg_char_to_encoding(value);
        /* if we don't recognize the encoding name, fall back to SQL_ASCII */
        if (conn->client_encoding < 0)
            conn->client_encoding = PG_SQL_ASCII;
        static_client_encoding = conn->client_encoding;
    }
    else if (strcmp(name, "standard_conforming_strings") == 0)
    {
        conn->std_strings = (strcmp(value, "on") == 0);
        static_std_strings = conn->std_strings;
    }
    else if (strcmp(name, "server_version") == 0)
    {
        int         cnt;
        int         vmaj,
                    vmin,
                    vrev;

        cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);

        if (cnt < 2)
            conn->sversion = 0; /* unknown */
        else
        {
            if (cnt == 2)
                vrev = 0;
            conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
        }
    }
}

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

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

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

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

{
    /* Treat null desc_target as empty string */
    if (!desc_target)
        desc_target = "";

    if (!PQsendQueryStart(conn))
        return 0;

    /* This isn't gonna work on a 2.0 server */
    if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
    {
        printfPQExpBuffer(&conn->errorMessage,
         libpq_gettext("function requires at least protocol version 3.0\n"));
        return 0;
    }

    /* construct the Describe message */
    if (pqPutMsgStart('D', false, conn) < 0 ||
        pqPutc(desc_type, conn) < 0 ||
        pqPuts(desc_target, conn) < 0 ||
        pqPutMsgEnd(conn) < 0)
        goto sendFailed;

    /* construct the Sync message */
    if (pqPutMsgStart('S', false, conn) < 0 ||
        pqPutMsgEnd(conn) < 0)
        goto sendFailed;

    /* remember we are doing a Describe */
    conn->queryclass = PGQUERY_DESCRIBE;

    /* reset last-query string (not relevant now) */
    if (conn->last_query)
    {
        free(conn->last_query);
        conn->last_query = NULL;
    }

    /*
     * Give the data a push.  In nonblock mode, don't complain if we're unable
     * to send it all; PQgetResult() will do any additional flushing needed.
     */
    if (pqFlush(conn) < 0)
        goto sendFailed;

    /* OK, it's launched! */
    conn->asyncStatus = PGASYNC_BUSY;
    return 1;

sendFailed:
    pqHandleSendFailure(conn);
    return 0;
}

int PQsendDescribePortal ( PGconn conn,
const char *  portal 
)

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

References PQsendDescribe().

{
    return PQsendDescribe(conn, 'P', portal);
}

int PQsendDescribePrepared ( PGconn conn,
const char *  stmt 
)

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

References PQsendDescribe().

{
    return PQsendDescribe(conn, 'S', stmt);
}

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

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

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

Referenced by PQprepare().

{
    if (!PQsendQueryStart(conn))
        return 0;

    /* check the arguments */
    if (!stmtName)
    {
        printfPQExpBuffer(&conn->errorMessage,
                        libpq_gettext("statement name is a null pointer\n"));
        return 0;
    }
    if (!query)
    {
        printfPQExpBuffer(&conn->errorMessage,
                        libpq_gettext("command string is a null pointer\n"));
        return 0;
    }
    if (nParams < 0 || nParams > 65535)
    {
        printfPQExpBuffer(&conn->errorMessage,
                        libpq_gettext("number of parameters must be between 0 and 65535\n"));
        return 0;
    }

    /* This isn't gonna work on a 2.0 server */
    if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
    {
        printfPQExpBuffer(&conn->errorMessage,
         libpq_gettext("function requires at least protocol version 3.0\n"));
        return 0;
    }

    /* construct the Parse message */
    if (pqPutMsgStart('P', false, conn) < 0 ||
        pqPuts(stmtName, conn) < 0 ||
        pqPuts(query, conn) < 0)
        goto sendFailed;

    if (nParams > 0 && paramTypes)
    {
        int         i;

        if (pqPutInt(nParams, 2, conn) < 0)
            goto sendFailed;
        for (i = 0; i < nParams; i++)
        {
            if (pqPutInt(paramTypes[i], 4, conn) < 0)
                goto sendFailed;
        }
    }
    else
    {
        if (pqPutInt(0, 2, conn) < 0)
            goto sendFailed;
    }
    if (pqPutMsgEnd(conn) < 0)
        goto sendFailed;

    /* construct the Sync message */
    if (pqPutMsgStart('S', false, conn) < 0 ||
        pqPutMsgEnd(conn) < 0)
        goto sendFailed;

    /* remember we are doing just a Parse */
    conn->queryclass = PGQUERY_PREPARE;

    /* and remember the query text too, if possible */
    /* if insufficient memory, last_query just winds up NULL */
    if (conn->last_query)
        free(conn->last_query);
    conn->last_query = strdup(query);

    /*
     * Give the data a push.  In nonblock mode, don't complain if we're unable
     * to send it all; PQgetResult() will do any additional flushing needed.
     */
    if (pqFlush(conn) < 0)
        goto sendFailed;

    /* OK, it's launched! */
    conn->asyncStatus = PGASYNC_BUSY;
    return 1;

sendFailed:
    pqHandleSendFailure(conn);
    return 0;
}

int PQsendQuery ( PGconn conn,
const char *  query 
)

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

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

Referenced by BaseBackup(), dblink_send_query(), doCustom(), libpqrcv_PQexec(), PQexec(), pqSetenvPoll(), run_permutation(), and storeQueryResult().

{
    if (!PQsendQueryStart(conn))
        return 0;

    /* check the argument */
    if (!query)
    {
        printfPQExpBuffer(&conn->errorMessage,
                        libpq_gettext("command string is a null pointer\n"));
        return 0;
    }

    /* construct the outgoing Query message */
    if (pqPutMsgStart('Q', false, conn) < 0 ||
        pqPuts(query, conn) < 0 ||
        pqPutMsgEnd(conn) < 0)
    {
        pqHandleSendFailure(conn);
        return 0;
    }

    /* remember we are using simple query protocol */
    conn->queryclass = PGQUERY_SIMPLE;

    /* and remember the query text too, if possible */
    /* if insufficient memory, last_query just winds up NULL */
    if (conn->last_query)
        free(conn->last_query);
    conn->last_query = strdup(query);

    /*
     * Give the data a push.  In nonblock mode, don't complain if we're unable
     * to send it all; PQgetResult() will do any additional flushing needed.
     */
    if (pqFlush(conn) < 0)
    {
        pqHandleSendFailure(conn);
        return 0;
    }

    /* OK, it's launched! */
    conn->asyncStatus = PGASYNC_BUSY;
    return 1;
}

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

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

Referenced by PQsendQueryParams(), and PQsendQueryPrepared().

{
    int         i;

    /* This isn't gonna work on a 2.0 server */
    if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
    {
        printfPQExpBuffer(&conn->errorMessage,
         libpq_gettext("function requires at least protocol version 3.0\n"));
        return 0;
    }

    /*
     * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync,
     * using specified statement name and the unnamed portal.
     */

    if (command)
    {
        /* construct the Parse message */
        if (pqPutMsgStart('P', false, conn) < 0 ||
            pqPuts(stmtName, conn) < 0 ||
            pqPuts(command, conn) < 0)
            goto sendFailed;
        if (nParams > 0 && paramTypes)
        {
            if (pqPutInt(nParams, 2, conn) < 0)
                goto sendFailed;
            for (i = 0; i < nParams; i++)
            {
                if (pqPutInt(paramTypes[i], 4, conn) < 0)
                    goto sendFailed;
            }
        }
        else
        {
            if (pqPutInt(0, 2, conn) < 0)
                goto sendFailed;
        }
        if (pqPutMsgEnd(conn) < 0)
            goto sendFailed;
    }

    /* Construct the Bind message */
    if (pqPutMsgStart('B', false, conn) < 0 ||
        pqPuts("", conn) < 0 ||
        pqPuts(stmtName, conn) < 0)
        goto sendFailed;

    /* Send parameter formats */
    if (nParams > 0 && paramFormats)
    {
        if (pqPutInt(nParams, 2, conn) < 0)
            goto sendFailed;
        for (i = 0; i < nParams; i++)
        {
            if (pqPutInt(paramFormats[i], 2, conn) < 0)
                goto sendFailed;
        }
    }
    else
    {
        if (pqPutInt(0, 2, conn) < 0)
            goto sendFailed;
    }

    if (pqPutInt(nParams, 2, conn) < 0)
        goto sendFailed;

    /* Send parameters */
    for (i = 0; i < nParams; i++)
    {
        if (paramValues && paramValues[i])
        {
            int         nbytes;

            if (paramFormats && paramFormats[i] != 0)
            {
                /* binary parameter */
                if (paramLengths)
                    nbytes = paramLengths[i];
                else
                {
                    printfPQExpBuffer(&conn->errorMessage,
                                      libpq_gettext("length must be given for binary parameter\n"));
                    goto sendFailed;
                }
            }
            else
            {
                /* text parameter, do not use paramLengths */
                nbytes = strlen(paramValues[i]);
            }
            if (pqPutInt(nbytes, 4, conn) < 0 ||
                pqPutnchar(paramValues[i], nbytes, conn) < 0)
                goto sendFailed;
        }
        else
        {
            /* take the param as NULL */
            if (pqPutInt(-1, 4, conn) < 0)
                goto sendFailed;
        }
    }
    if (pqPutInt(1, 2, conn) < 0 ||
        pqPutInt(resultFormat, 2, conn))
        goto sendFailed;
    if (pqPutMsgEnd(conn) < 0)
        goto sendFailed;

    /* construct the Describe Portal message */
    if (pqPutMsgStart('D', false, conn) < 0 ||
        pqPutc('P', conn) < 0 ||
        pqPuts("", conn) < 0 ||
        pqPutMsgEnd(conn) < 0)
        goto sendFailed;

    /* construct the Execute message */
    if (pqPutMsgStart('E', false, conn) < 0 ||
        pqPuts("", conn) < 0 ||
        pqPutInt(0, 4, conn) < 0 ||
        pqPutMsgEnd(conn) < 0)
        goto sendFailed;

    /* construct the Sync message */
    if (pqPutMsgStart('S', false, conn) < 0 ||
        pqPutMsgEnd(conn) < 0)
        goto sendFailed;

    /* remember we are using extended query protocol */
    conn->queryclass = PGQUERY_EXTENDED;

    /* and remember the query text too, if possible */
    /* if insufficient memory, last_query just winds up NULL */
    if (conn->last_query)
        free(conn->last_query);
    if (command)
        conn->last_query = strdup(command);
    else
        conn->last_query = NULL;

    /*
     * Give the data a push.  In nonblock mode, don't complain if we're unable
     * to send it all; PQgetResult() will do any additional flushing needed.
     */
    if (pqFlush(conn) < 0)
        goto sendFailed;

    /* OK, it's launched! */
    conn->asyncStatus = PGASYNC_BUSY;
    return 1;

sendFailed:
    pqHandleSendFailure(conn);
    return 0;
}

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

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

Referenced by doCustom(), and PQexecParams().

{
    if (!PQsendQueryStart(conn))
        return 0;

    /* check the arguments */
    if (!command)
    {
        printfPQExpBuffer(&conn->errorMessage,
                        libpq_gettext("command string is a null pointer\n"));
        return 0;
    }
    if (nParams < 0 || nParams > 65535)
    {
        printfPQExpBuffer(&conn->errorMessage,
                        libpq_gettext("number of parameters must be between 0 and 65535\n"));
        return 0;
    }

    return PQsendQueryGuts(conn,
                           command,
                           "",  /* use unnamed statement */
                           nParams,
                           paramTypes,
                           paramValues,
                           paramLengths,
                           paramFormats,
                           resultFormat);
}

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

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

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

Referenced by doCustom(), and PQexecPrepared().

{
    if (!PQsendQueryStart(conn))
        return 0;

    /* check the arguments */
    if (!stmtName)
    {
        printfPQExpBuffer(&conn->errorMessage,
                        libpq_gettext("statement name is a null pointer\n"));
        return 0;
    }
    if (nParams < 0 || nParams > 65535)
    {
        printfPQExpBuffer(&conn->errorMessage,
                        libpq_gettext("number of parameters must be between 0 and 65535\n"));
        return 0;
    }

    return PQsendQueryGuts(conn,
                           NULL,    /* no command to parse */
                           stmtName,
                           nParams,
                           NULL,    /* no param types */
                           paramValues,
                           paramLengths,
                           paramFormats,
                           resultFormat);
}

static bool PQsendQueryStart ( PGconn conn  )  [static]

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

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

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

{
    if (!conn)
        return false;

    /* clear the error string */
    resetPQExpBuffer(&conn->errorMessage);

    /* Don't try to send if we know there's no live connection. */
    if (conn->status != CONNECTION_OK)
    {
        printfPQExpBuffer(&conn->errorMessage,
                          libpq_gettext("no connection to the server\n"));
        return false;
    }
    /* Can't send while already busy, either. */
    if (conn->asyncStatus != PGASYNC_IDLE)
    {
        printfPQExpBuffer(&conn->errorMessage,
                  libpq_gettext("another command is already in progress\n"));
        return false;
    }

    /* initialize async result-accumulation state */
    conn->result = NULL;
    conn->next_result = NULL;

    /* reset single-row processing mode */
    conn->singleRowMode = false;

    /* ready to send command message */
    return true;
}

int PQsetnonblocking ( PGconn conn,
int  arg 
)

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

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

{
    bool        barg;

    if (!conn || conn->status == CONNECTION_BAD)
        return -1;

    barg = (arg ? TRUE : FALSE);

    /* early out if the socket is already in the state requested */
    if (barg == conn->nonblocking)
        return 0;

    /*
     * to guarantee constancy for flushing/query/result-polling behavior we
     * need to flush the send queue at this point in order to guarantee proper
     * behavior. this is ok because either they are making a transition _from_
     * or _to_ blocking mode, either way we can block them.
     */
    /* if we are going from blocking to non-blocking flush here */
    if (pqFlush(conn))
        return -1;

    conn->nonblocking = barg;

    return 0;
}

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

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

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

Referenced by PQcopyResult().

{
    int         i;

    /* If attrs already exist, they cannot be overwritten. */
    if (!res || res->numAttributes > 0)
        return FALSE;

    /* ignore no-op request */
    if (numAttributes <= 0 || !attDescs)
        return TRUE;

    res->attDescs = (PGresAttDesc *)
        PQresultAlloc(res, numAttributes * sizeof(PGresAttDesc));

    if (!res->attDescs)
        return FALSE;

    res->numAttributes = numAttributes;
    memcpy(res->attDescs, attDescs, numAttributes * sizeof(PGresAttDesc));

    /* deep-copy the attribute names, and determine format */
    res->binary = 1;
    for (i = 0; i < res->numAttributes; i++)
    {
        if (res->attDescs[i].name)
            res->attDescs[i].name = pqResultStrdup(res, res->attDescs[i].name);
        else
            res->attDescs[i].name = res->null_field;

        if (!res->attDescs[i].name)
            return FALSE;

        if (res->attDescs[i].format == 0)
            res->binary = 0;
    }

    return TRUE;
}

void pqSetResultError ( PGresult res,
const char *  msg 
)

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

References pg_result::errMsg, and pqResultStrdup().

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

{
    if (!res)
        return;
    if (msg && *msg)
        res->errMsg = pqResultStrdup(res, msg);
    else
        res->errMsg = NULL;
}

int PQsetSingleRowMode ( PGconn conn  ) 

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

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

Referenced by storeQueryResult().

{
    /*
     * Only allow setting the flag when we have launched a query and not yet
     * received any results.
     */
    if (!conn)
        return 0;
    if (conn->asyncStatus != PGASYNC_BUSY)
        return 0;
    if (conn->queryclass != PGQUERY_SIMPLE &&
        conn->queryclass != PGQUERY_EXTENDED)
        return 0;
    if (conn->result)
        return 0;

    /* OK, set flag */
    conn->singleRowMode = true;
    return 1;
}

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

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

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

Referenced by PQcopyResult().

{
    PGresAttValue *attval;

    if (!check_field_number(res, field_num))
        return FALSE;

    /* Invalid tup_num, must be <= ntups */
    if (tup_num < 0 || tup_num > res->ntups)
        return FALSE;

    /* need to allocate a new tuple? */
    if (tup_num == res->ntups)
    {
        PGresAttValue *tup;
        int         i;

        tup = (PGresAttValue *)
            pqResultAlloc(res, res->numAttributes * sizeof(PGresAttValue),
                          TRUE);

        if (!tup)
            return FALSE;

        /* initialize each column to NULL */
        for (i = 0; i < res->numAttributes; i++)
        {
            tup[i].len = NULL_LEN;
            tup[i].value = res->null_field;
        }

        /* add it to the array */
        if (!pqAddTuple(res, tup))
            return FALSE;
    }

    attval = &res->tuples[tup_num][field_num];

    /* treat either NULL_LEN or NULL value pointer as a NULL field */
    if (len == NULL_LEN || value == NULL)
    {
        attval->len = NULL_LEN;
        attval->value = res->null_field;
    }
    else if (len <= 0)
    {
        attval->len = 0;
        attval->value = res->null_field;
    }
    else
    {
        attval->value = (char *) pqResultAlloc(res, len + 1, TRUE);
        if (!attval->value)
            return FALSE;
        attval->len = len;
        memcpy(attval->value, value, len);
        attval->value[len] = '\0';
    }

    return TRUE;
}

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

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

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

Referenced by dumpTrigger().

{
    size_t      strtextlen,
                buflen;
    unsigned char *buffer,
               *tmpbuf;
    size_t      i,
                j;

    if (strtext == NULL)
        return NULL;

    strtextlen = strlen((const char *) strtext);

    if (strtext[0] == '\\' && strtext[1] == 'x')
    {
        const unsigned char *s;
        unsigned char *p;

        buflen = (strtextlen - 2) / 2;
        /* Avoid unportable malloc(0) */
        buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
        if (buffer == NULL)
            return NULL;

        s = strtext + 2;
        p = buffer;
        while (*s)
        {
            char        v1,
                        v2;

            /*
             * Bad input is silently ignored.  Note that this includes
             * whitespace between hex pairs, which is allowed by byteain.
             */
            v1 = get_hex(*s++);
            if (!*s || v1 == (char) -1)
                continue;
            v2 = get_hex(*s++);
            if (v2 != (char) -1)
                *p++ = (v1 << 4) | v2;
        }

        buflen = p - buffer;
    }
    else
    {
        /*
         * Length of input is max length of output, but add one to avoid
         * unportable malloc(0) if input is zero-length.
         */
        buffer = (unsigned char *) malloc(strtextlen + 1);
        if (buffer == NULL)
            return NULL;

        for (i = j = 0; i < strtextlen;)
        {
            switch (strtext[i])
            {
                case '\\':
                    i++;
                    if (strtext[i] == '\\')
                        buffer[j++] = strtext[i++];
                    else
                    {
                        if ((ISFIRSTOCTDIGIT(strtext[i])) &&
                            (ISOCTDIGIT(strtext[i + 1])) &&
                            (ISOCTDIGIT(strtext[i + 2])))
                        {
                            int         byte;

                            byte = OCTVAL(strtext[i++]);
                            byte = (byte << 3) + OCTVAL(strtext[i++]);
                            byte = (byte << 3) + OCTVAL(strtext[i++]);
                            buffer[j++] = byte;
                        }
                    }

                    /*
                     * Note: if we see '\' followed by something that isn't a
                     * recognized escape sequence, we loop around having done
                     * nothing except advance i.  Therefore the something will
                     * be emitted as ordinary data on the next cycle. Corner
                     * case: '\' at end of string will just be discarded.
                     */
                    break;

                default:
                    buffer[j++] = strtext[i++];
                    break;
            }
        }
        buflen = j;             /* buflen is the length of the dequoted data */
    }

    /* Shrink the buffer to be no larger than necessary */
    /* +1 avoids unportable behavior when buflen==0 */
    tmpbuf = realloc(buffer, buflen + 1);

    /* It would only be a very brain-dead realloc that could fail, but... */
    if (!tmpbuf)
    {
        free(buffer);
        return NULL;
    }

    *retbuflen = buflen;
    return tmpbuf;
}


Variable Documentation

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

Referenced by get_hex().

const char hextbl[] = "0123456789abcdef" [static]

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

Referenced by PQescapeByteaInternal().

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"
}

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

Referenced by PQresStatus().

int static_client_encoding = PG_SQL_ASCII [static]

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

Referenced by PQescapeString(), and pqSaveParameterStatus().

bool static_std_strings = false [static]

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

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