Header And Logo

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

Functions | Variables

pqexpbuffer.c File Reference

#include "postgres_fe.h"
#include <limits.h>
#include "pqexpbuffer.h"
Include dependency graph for pqexpbuffer.c:

Go to the source code of this file.

Functions

static void markPQExpBufferBroken (PQExpBuffer str)
PQExpBuffer createPQExpBuffer (void)
void initPQExpBuffer (PQExpBuffer str)
void destroyPQExpBuffer (PQExpBuffer str)
void termPQExpBuffer (PQExpBuffer str)
void resetPQExpBuffer (PQExpBuffer str)
int enlargePQExpBuffer (PQExpBuffer str, size_t needed)
void printfPQExpBuffer (PQExpBuffer str, const char *fmt,...)
void appendPQExpBuffer (PQExpBuffer str, const char *fmt,...)
void appendPQExpBufferStr (PQExpBuffer str, const char *data)
void appendPQExpBufferChar (PQExpBuffer str, char ch)
void appendBinaryPQExpBuffer (PQExpBuffer str, const char *data, size_t datalen)

Variables

static const char oom_buffer [1] = ""

Function Documentation

void appendBinaryPQExpBuffer ( PQExpBuffer  str,
const char *  data,
size_t  datalen 
)

Definition at line 362 of file pqexpbuffer.c.

References PQExpBufferData::data, enlargePQExpBuffer(), and PQExpBufferData::len.

Referenced by appendPQExpBufferStr(), createViewAsClause(), and pqGets_internal().

{
    /* Make more room if needed */
    if (!enlargePQExpBuffer(str, datalen))
        return;

    /* OK, append the data */
    memcpy(str->data + str->len, data, datalen);
    str->len += datalen;

    /*
     * Keep a trailing null in place, even though it's probably useless for
     * binary data...
     */
    str->data[str->len] = '\0';
}

void appendPQExpBuffer ( PQExpBuffer  str,
const char *  fmt,
  ... 
)

Definition at line 284 of file pqexpbuffer.c.

References PQExpBufferData::data, enlargePQExpBuffer(), PQExpBufferData::len, PQExpBufferData::maxlen, PQExpBufferBroken, and vsnprintf().

Referenced by _doSetSessionAuth(), _doSetWithOids(), _getObjectDescription(), _printTocEntry(), _reconnectToDB(), _selectOutputSchema(), _selectTablespace(), add_tablespace_footer(), AddAcl(), binary_upgrade_extension_member(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_rel_oid(), binary_upgrade_set_type_oids_by_type_oid(), buildACLCommands(), buildDefaultACLCommands(), buildMatViewRefreshDependencies(), buildShSecLabelQuery(), cluster_one_database(), collectComments(), collectSecLabels(), connectDBStart(), connectFailureMessage(), connectNoDelay(), constructConnStr(), createViewAsClause(), describeAggregates(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOperators(), describeRoles(), describeTableDetails(), describeTablespaces(), describeTypes(), do_copy(), doShellQuoting(), dot_pg_pass_warning(), dumpAgg(), dumpAttrDef(), dumpBaseType(), dumpBlob(), dumpCast(), dumpCollation(), dumpComment(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConstraint(), dumpConversion(), dumpCreateDB(), dumpDatabase(), dumpDatabaseConfig(), dumpDefaultACL(), dumpDomain(), dumpEncoding(), dumpEnumType(), dumpEventTrigger(), dumpExtension(), dumpForeignDataWrapper(), dumpForeignServer(), dumpFunc(), dumpIndex(), dumpNamespace(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpProcLang(), dumpRangeType(), dumpRoles(), dumpRule(), dumpSecLabel(), dumpSequence(), dumpSequenceData(), dumpShellType(), dumpStdStrings(), dumpTable(), dumpTableComment(), dumpTableConstraintComment(), dumpTableData(), dumpTableData_copy(), dumpTableData_insert(), dumpTableSchema(), dumpTableSecLabel(), dumpTablespaces(), dumpTrigger(), dumpTSConfig(), dumpTSDictionary(), dumpTSParser(), dumpTSTemplate(), dumpUserConfig(), dumpUserMappings(), emitShSecLabels(), ExecQueryUsingCursor(), expand_schema_name_patterns(), expand_table_name_patterns(), findLastBuiltinOid_V71(), fmtCopyColumnList(), fmtQualifiedId(), format_aggregate_signature(), format_function_arguments(), format_function_arguments_old(), format_function_signature(), GenerateRecoveryConf(), 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(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), lockTableNoWait(), lookup_function_oid(), main(), makeAlterConfigCommand(), myFormatType(), objectDescription(), parseAclItem(), permissionsList(), PQconnectPoll(), pqGetErrorNotice3(), printACLColumn(), processSQLNamePattern(), refreshMatViewData(), reindex_one_database(), reindex_system_catalogs(), reportErrorPosition(), runPgDump(), selectSourceSchema(), setKeepalivesCount(), setKeepalivesIdle(), setKeepalivesInterval(), setup_connection(), and vacuum_one_database().

{
    va_list     args;
    size_t      avail;
    int         nprinted;

    if (PQExpBufferBroken(str))
        return;                 /* already failed */

    for (;;)
    {
        /*
         * Try to format the given string into the available space; but if
         * there's hardly any space, don't bother trying, just fall through to
         * enlarge the buffer first.
         */
        if (str->maxlen > str->len + 16)
        {
            avail = str->maxlen - str->len - 1;
            va_start(args, fmt);
            nprinted = vsnprintf(str->data + str->len, avail,
                                 fmt, args);
            va_end(args);

            /*
             * Note: some versions of vsnprintf return the number of chars
             * actually stored, but at least one returns -1 on failure. Be
             * conservative about believing whether the print worked.
             */
            if (nprinted >= 0 && nprinted < (int) avail - 1)
            {
                /* Success.  Note nprinted does not include trailing null. */
                str->len += nprinted;
                break;
            }
        }
        /* Double the buffer size and try again. */
        if (!enlargePQExpBuffer(str, str->maxlen))
            return;             /* oops, out of memory */
    }
}

void appendPQExpBufferChar ( PQExpBuffer  str,
char  ch 
)
void appendPQExpBufferStr ( PQExpBuffer  str,
const char *  data 
)
PQExpBuffer createPQExpBuffer ( void   ) 

Definition at line 68 of file pqexpbuffer.c.

References initPQExpBuffer(), malloc, and NULL.

Referenced by _doSetSessionAuth(), _doSetWithOids(), _printTocEntry(), _reconnectToDB(), _selectOutputSchema(), _selectTablespace(), _WriteBlobData(), appendStringLiteralDQ(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_rel_oid(), binary_upgrade_set_type_oids_by_type_oid(), buildACLCommands(), buildDefaultACLCommands(), buildMatViewRefreshDependencies(), buildShSecLabels(), collectComments(), collectSecLabels(), constructConnStr(), createViewAsClause(), defaultGetLocalPQExpBuffer(), dump_lo_buf(), dumpACL(), dumpAgg(), dumpAttrDef(), dumpBaseType(), dumpBlob(), dumpCast(), dumpCollation(), dumpComment(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConstraint(), dumpConversion(), dumpCreateDB(), dumpDatabase(), dumpDatabaseConfig(), dumpDbRoleConfig(), dumpDefaultACL(), dumpDomain(), dumpEncoding(), dumpEnumType(), dumpEventTrigger(), dumpExtension(), dumpForeignDataWrapper(), dumpForeignServer(), dumpFunc(), dumpGroups(), dumpIndex(), dumpNamespace(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpProcLang(), dumpRangeType(), dumpRoles(), dumpRule(), dumpSecLabel(), dumpSequence(), dumpSequenceData(), dumpShellType(), dumpStdStrings(), dumpTable(), dumpTableComment(), dumpTableConstraintComment(), dumpTableData(), dumpTableData_copy(), dumpTableData_insert(), dumpTableSchema(), dumpTableSecLabel(), dumpTablespaces(), dumpTrigger(), dumpTSConfig(), dumpTSDictionary(), dumpTSParser(), dumpTSTemplate(), dumpUserConfig(), dumpUserMappings(), exec_command(), ExecuteInsertCommands(), expand_schema_name_patterns(), expand_table_name_patterns(), findLastBuiltinOid_V71(), fmtQualifiedId(), GenerateRecoveryConf(), get_create_function_cmd(), getAggregates(), getBlobs(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getProcLangs(), getRules(), gets_fromFile(), getTableAttrs(), getTables(), getThreadLocalPQExpBuffer(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), lockTableNoWait(), lookup_function_oid(), main(), MainLoop(), makeAlterConfigCommand(), minimal_error_message(), myFormatType(), refreshMatViewData(), runPgDump(), selectSourceSchema(), and setup_connection().

{
    PQExpBuffer res;

    res = (PQExpBuffer) malloc(sizeof(PQExpBufferData));
    if (res != NULL)
        initPQExpBuffer(res);

    return res;
}

void destroyPQExpBuffer ( PQExpBuffer  str  ) 

Definition at line 110 of file pqexpbuffer.c.

References free, and termPQExpBuffer().

Referenced by _doSetSessionAuth(), _doSetWithOids(), _printTocEntry(), _reconnectToDB(), _selectOutputSchema(), _selectTablespace(), _WriteBlobData(), appendStringLiteralDQ(), BaseBackup(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_rel_oid(), binary_upgrade_set_type_oids_by_type_oid(), buildACLCommands(), buildDefaultACLCommands(), buildMatViewRefreshDependencies(), buildShSecLabels(), collectComments(), collectSecLabels(), constructConnStr(), createViewAsClause(), DeCloneArchive(), dump_lo_buf(), dumpACL(), dumpAgg(), dumpAttrDef(), dumpBaseType(), dumpBlob(), dumpCast(), dumpCollation(), dumpComment(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConstraint(), dumpConversion(), dumpCreateDB(), dumpDatabase(), dumpDatabaseConfig(), dumpDbRoleConfig(), dumpDefaultACL(), dumpDomain(), dumpEncoding(), dumpEnumType(), dumpEventTrigger(), dumpExtension(), dumpForeignDataWrapper(), dumpForeignServer(), dumpFunc(), dumpGroups(), dumpIndex(), dumpNamespace(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpProcLang(), dumpRangeType(), dumpRoles(), dumpRule(), dumpSecLabel(), dumpSequence(), dumpSequenceData(), dumpShellType(), dumpStdStrings(), dumpTable(), dumpTableComment(), dumpTableConstraintComment(), dumpTableData(), dumpTableData_copy(), dumpTableData_insert(), dumpTableSchema(), dumpTableSecLabel(), dumpTablespaces(), dumpTrigger(), dumpTSConfig(), dumpTSDictionary(), dumpTSParser(), dumpTSTemplate(), dumpUserConfig(), dumpUserMappings(), exec_command(), expand_schema_name_patterns(), expand_table_name_patterns(), findLastBuiltinOid_V71(), fmtQualifiedId(), get_create_function_cmd(), 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(), lockTableNoWait(), lookup_function_oid(), main(), MainLoop(), makeAlterConfigCommand(), minimal_error_message(), myFormatType(), refreshMatViewData(), runPgDump(), selectSourceSchema(), and setup_connection().

{
    if (str)
    {
        termPQExpBuffer(str);
        free(str);
    }
}

int enlargePQExpBuffer ( PQExpBuffer  str,
size_t  needed 
)

Definition at line 168 of file pqexpbuffer.c.

References PQExpBufferData::data, PQExpBufferData::len, markPQExpBufferBroken(), PQExpBufferData::maxlen, NULL, PQExpBufferBroken, and realloc.

Referenced by appendBinaryPQExpBuffer(), appendByteaLiteral(), appendPQExpBuffer(), appendPQExpBufferChar(), appendStringLiteral(), appendStringLiteralConn(), and printfPQExpBuffer().

{
    size_t      newlen;
    char       *newdata;

    if (PQExpBufferBroken(str))
        return 0;               /* already failed */

    /*
     * Guard against ridiculous "needed" values, which can occur if we're fed
     * bogus data.  Without this, we can get an overflow or infinite loop in
     * the following.
     */
    if (needed >= ((size_t) INT_MAX - str->len))
    {
        markPQExpBufferBroken(str);
        return 0;
    }

    needed += str->len + 1;     /* total space required now */

    /* Because of the above test, we now have needed <= INT_MAX */

    if (needed <= str->maxlen)
        return 1;               /* got enough space already */

    /*
     * We don't want to allocate just a little more space with each append;
     * for efficiency, double the buffer size each time it overflows.
     * Actually, we might need to more than double it if 'needed' is big...
     */
    newlen = (str->maxlen > 0) ? (2 * str->maxlen) : 64;
    while (needed > newlen)
        newlen = 2 * newlen;

    /*
     * Clamp to INT_MAX in case we went past it.  Note we are assuming here
     * that INT_MAX <= UINT_MAX/2, else the above loop could overflow.  We
     * will still have newlen >= needed.
     */
    if (newlen > (size_t) INT_MAX)
        newlen = (size_t) INT_MAX;

    newdata = (char *) realloc(str->data, newlen);
    if (newdata != NULL)
    {
        str->data = newdata;
        str->maxlen = newlen;
        return 1;
    }

    markPQExpBufferBroken(str);
    return 0;
}

void initPQExpBuffer ( PQExpBuffer  str  ) 

Definition at line 86 of file pqexpbuffer.c.

References PQExpBufferData::data, INITIAL_EXPBUFFER_SIZE, PQExpBufferData::len, malloc, PQExpBufferData::maxlen, NULL, and oom_buffer.

Referenced by add_tablespace_footer(), cluster_one_database(), createPQExpBuffer(), describeAggregates(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describeRoles(), describeTableDetails(), describeTablespaces(), describeTypes(), do_copy(), exec_command(), ExecQueryUsingCursor(), format_aggregate_signature(), format_function_arguments(), format_function_arguments_old(), format_function_signature(), getCasts(), getParameterStatus(), helpSQL(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listOneExtensionContents(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), main(), makeEmptyPGconn(), objectDescription(), permissionsList(), pqCatenateResultError(), PQconndefaults(), PQconninfo(), PQconninfoParse(), pqGetErrorNotice2(), pqGetErrorNotice3(), processSQLNamePattern(), reindex_one_database(), reindex_system_catalogs(), resetPQExpBuffer(), and vacuum_one_database().

{
    str->data = (char *) malloc(INITIAL_EXPBUFFER_SIZE);
    if (str->data == NULL)
    {
        str->data = (char *) oom_buffer;        /* see comment above */
        str->maxlen = 0;
        str->len = 0;
    }
    else
    {
        str->maxlen = INITIAL_EXPBUFFER_SIZE;
        str->len = 0;
        str->data[0] = '\0';
    }
}

static void markPQExpBufferBroken ( PQExpBuffer  str  )  [static]

Definition at line 46 of file pqexpbuffer.c.

References PQExpBufferData::data, free, PQExpBufferData::len, PQExpBufferData::maxlen, and oom_buffer.

Referenced by enlargePQExpBuffer().

{
    if (str->data != oom_buffer)
        free(str->data);

    /*
     * Casting away const here is a bit ugly, but it seems preferable to not
     * marking oom_buffer const.  We want to do that to encourage the compiler
     * to put oom_buffer in read-only storage, so that anyone who tries to
     * scribble on a broken PQExpBuffer will get a failure.
     */
    str->data = (char *) oom_buffer;
    str->len = 0;
    str->maxlen = 0;
}

void printfPQExpBuffer ( PQExpBuffer  str,
const char *  fmt,
  ... 
)

Definition at line 231 of file pqexpbuffer.c.

References PQExpBufferData::data, enlargePQExpBuffer(), PQExpBufferData::len, PQExpBufferData::maxlen, PQExpBufferBroken, resetPQExpBuffer(), and vsnprintf().

Referenced by add_tablespace_footer(), buildACLCommands(), connectOptions2(), conninfo_add_defaults(), conninfo_array_parse(), conninfo_init(), conninfo_parse(), conninfo_storeval(), conninfo_uri_decode(), conninfo_uri_parse_options(), conninfo_uri_parse_params(), describeAggregates(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describeRoles(), describeTableDetails(), describeTablespaces(), describeTypes(), do_copy(), dumpDatabaseConfig(), dumpDbRoleConfig(), dumpGroups(), dumpRoles(), dumpRule(), dumpUserConfig(), exec_command(), get_create_function_cmd(), getAnotherTuple(), getRowDescriptions(), handleSyncLoss(), 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_create(), lo_export(), lo_import_internal(), lo_initialize(), lo_lseek64(), lo_read(), lo_tell64(), lo_truncate(), lo_truncate64(), lo_write(), lookup_function_oid(), main(), minimal_error_message(), parseAclItem(), parseServiceFile(), parseServiceInfo(), permissionsList(), pg_fe_sendauth(), pg_local_sendauth(), pg_password_sendauth(), pqCheckInBufferSpace(), pqCheckOutBufferSpace(), PQconnectPoll(), pqEndcopy2(), pqEndcopy3(), PQescapeByteaInternal(), PQescapeInternal(), PQescapeStringInternal(), PQexecStart(), PQfn(), pqFunctionCall2(), pqFunctionCall3(), PQgetCopyData(), pqGetCopyData2(), pqGetCopyData3(), pqGetline3(), PQgetResult(), pqParseInput2(), pqParseInput3(), PQputCopyData(), PQputCopyEnd(), pqReadData(), PQreset(), PQresetPoll(), pqsecure_open_client(), pqsecure_read(), pqsecure_write(), PQsendDescribe(), PQsendPrepare(), PQsendQuery(), PQsendQueryGuts(), PQsendQueryParams(), PQsendQueryPrepared(), PQsendQueryStart(), pqSendSome(), pqSetenvPoll(), pqSocketCheck(), and pqWaitTimed().

{
    va_list     args;
    size_t      avail;
    int         nprinted;

    resetPQExpBuffer(str);

    if (PQExpBufferBroken(str))
        return;                 /* already failed */

    for (;;)
    {
        /*
         * Try to format the given string into the available space; but if
         * there's hardly any space, don't bother trying, just fall through to
         * enlarge the buffer first.
         */
        if (str->maxlen > str->len + 16)
        {
            avail = str->maxlen - str->len - 1;
            va_start(args, fmt);
            nprinted = vsnprintf(str->data + str->len, avail,
                                 fmt, args);
            va_end(args);

            /*
             * Note: some versions of vsnprintf return the number of chars
             * actually stored, but at least one returns -1 on failure. Be
             * conservative about believing whether the print worked.
             */
            if (nprinted >= 0 && nprinted < (int) avail - 1)
            {
                /* Success.  Note nprinted does not include trailing null. */
                str->len += nprinted;
                break;
            }
        }
        /* Double the buffer size and try again. */
        if (!enlargePQExpBuffer(str, str->maxlen))
            return;             /* oops, out of memory */
    }
}

void resetPQExpBuffer ( PQExpBuffer  str  ) 
void termPQExpBuffer ( PQExpBuffer  str  ) 

Variable Documentation

const char oom_buffer[1] = "" [static]